diff --git "a/6419.jsonl" "b/6419.jsonl" new file mode 100644--- /dev/null +++ "b/6419.jsonl" @@ -0,0 +1,625 @@ +{"seq_id":"71458590813","text":"from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nimport requests\nimport re\nimport string\nfrom bs4 import BeautifulSoup\n\ndef assignment(country):\n# def assignment():\n url = \"https://en.wikipedia.org/wiki/\"+country\n# url = \"https://en.wikipedia.org/wiki/India\"\n r = requests.get(url)\n soup=BeautifulSoup(r.content,'html.parser')\n for data in soup(['style', 'script']):\n data.decompose()\n\n def brace(str):\n str= re.sub(r'\\[[\\w]*\\]','',str)\n str=re.sub(r'\\([^)]*\\)', '', str)\n str=re.sub(r'\\s\\+','',str)\n return str\n\n\n\n table=soup.find('table',class_=(\"infobox\"))\n\n #flag link\n flag=soup.find('img',class_=\"thumbborder\")\n flagy=\"https:\"+flag['src']\n\n #Capital\n C=table.find(text=re.compile(\"Capital\")).parent.parent\n Ca=C.find_all(\"li\")\n if(Ca):\n Cap=[]\n for i in Ca:\n Cap.append(brace(i.text))\n else:\n Cap=brace(C.find(\"a\").text)\n\n #Largest City\n LC=table.find(text= re.compile(\"argest city\")).parent.parent\n Lci=LC.find_all(\"li\")\n if(Lci):\n Lcity=[] \n for i in Lci: \n Lcity.append(brace(i.text))\n\n else:\n try:\n Lcit=LC.find(\"td\").text\n except:\n Lcity=brace(C.find(\"td\").text)\n else:\n Lcity=brace(Lcit)\n\n #Official Languages\n OL=table.find(text= re.compile(\"Official\")).parent.parent\n Ola=OL.find_all(\"li\")\n if(Ola):\n olan=[]\n for i in Ola:\n olan.append(brace(i.text))\n else:\n olan=brace(OL.find(\"td\").text)\n\n #Area\n A=table.find(text= re.compile(\"Area\")).parent.parent.parent.next_sibling.find(\"td\").text\n Ar=brace(A)\n\n #Population\n P=table.find(text= re.compile(\"opulation\")).parent.parent.parent.next_sibling.find(\"td\").text\n Po=brace(P)\n\n #GDP\n G=table.find(text= re.compile(\"nominal\")).parent.parent.parent.next_sibling.find(\"td\").text\n Gd=brace(G)\n\n answer={\"flag_link\" : flagy , \"capital\" : Cap , \"largest city\":Lcity, \"official languages\": olan, \"area_total\":Ar, \"Population\": Po, \"GDP_nominal\":Gd}\n return answer\n\n# name = input(\"Enter Country: \")\n# assignment(name)\n\n\n@api_view()\ndef api(request,id):\n answer=assignment(id)\n return Response(answer)\n\n\n \n# Create your views here.\n","repo_name":"KLakshay917/SolarLabAssignment","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"42155299959","text":"# Exercício 1: Faça um programa que receba um nome e\n# imprima o mesmo na vertical em escada invertida. Exemplo:\n\ndef inverted_ladder(name):\n for removed_letters in range(len(name)):\n for letter in range(len(name) - removed_letters):\n print(name[letter], end=\"\")\n print()\n\n\nif __name__ == '__main__':\n name = input('Digite seu nome: ')\n inverted_ladder(name)\n","repo_name":"JulioCesar1402/Trybe_CS","sub_path":"32.2/exercicios/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"72676674655","text":"import numpy as np\r\nimport sys\r\nimport copy\r\n\r\nclass solve(object):\r\n\tdef __init__(self,state_space,num_cols,start,goal,technique): #num_cols is used by the heuristic for a*\r\n\t\tself.start=start\r\n\t\tself.num_cols=num_cols\r\n\t\tself.goal=goal\r\n\t\tself.state_space=state_space\r\n\t\tself.path=[]\r\n\t\tself.exact_path=[]\r\n\t\tself.explored=[]\r\n\t\tprint(\"Initialized solver, using technique \",technique)\r\n\t\tif(technique==\"bfs\"):\r\n\t\t\tstack=[]\r\n\t\t\tstack.append(state_space[start])\r\n\t\t\tself.BFS(stack)\r\n\t\t\tif(goal not in self.path):\r\n\t\t\t\tprint(\"WARNING ! a valid path does not exist, printing all expanded nodes\")\r\n\t\t\telse:\r\n\t\t\t\tprint(\"CONGRATULATIONS ! A path exists, printing all expanded nodes\")\r\n\t\t\tprint(self.path)\r\n\t\tif(technique==\"dfs\"):\r\n\t\t\tstack=[]\r\n\t\t\tstack.append(state_space[start])\r\n\t\t\tself.DFS(stack)\r\n\t\t\tif(goal not in self.path):\r\n\t\t\t\tprint(\"WARNING ! a valid path does not exist, printing all expanded nodes\")\r\n\t\t\telse:\r\n\t\t\t\tprint(\"CONGRATULATIONS ! A path exists, printing all expanded nodes\")\r\n\t\t\tprint(self.path)\r\n\t\tif(technique==\"astar\"):\r\n\t\t\tstack=[]\r\n\t\t\t#Modifying the state_space\r\n\t\t\tfor i in state_space:\r\n\t\t\t\ti[\"g\"]=0\r\n\t\t\t\ti[\"h\"]=0\r\n\t\t\tstate_space[start][\"parent \"]=-1 #To denote that it is the root\r\n\t\t\tstack.append(state_space[start])\r\n\t\t\tself.Astar(stack)\r\n\t\t\tif(goal not in self.path):\r\n\t\t\t\tprint(\"WARNING ! a valid path does not exist, printing all expanded nodes\")\r\n\t\t\t\tprint(self.path)\r\n\t\t\telse:\r\n\t\t\t\tprint(\"CONGRATULATIONS ! A path exists, printing all expanded nodes\")\r\n\t\t\t\tprint(self.path_from_visited(self.path))\r\n\tdef path_from_visited(self,path):\r\n\t\tp=[]\r\n\t\tpointer=self.goal\r\n\t\twhile pointer!=self.start:\r\n\t\t\tp.append(pointer)\r\n\t\t\tpointer=copy.copy(self.state_space[pointer][\"parent \"])\r\n\t\tp.reverse()\r\n\t\treturn p\r\n\r\n\tdef expand_stack(self,stack):\r\n\t\thead=stack.pop(0)\r\n\t\tconnects=head[\"connections \"]\r\n\t\tif(connects==[]):\r\n\t\t\treturn stack\r\n\t\tfor i in connects:\r\n\t\t\tif(i not in self.explored):\r\n\t\t\t\tstack.append(self.state_space[i])\r\n\t\treturn stack\r\n\tdef not_worth_visiting(self,node,closed_nodes,open_nodes):\r\n\t\tfor i in open_nodes:\r\n\t\t\tif(i[\"parent \"]==self.state_space[node[\"name \"]][\"parent \"]): \r\n\t\t\t\tif(i[\"g\"]+i[\"h\"]\r\n #MainMenu {visibility: hidden; }\r\n footer {visibility: hidden;}\r\n \r\n \"\"\"\r\nst.markdown(hide_menu_style, unsafe_allow_html=True)\r\n\r\ncol = st.columns(4)\r\nwith col[0]:\r\n st.image(\"Logo_UT3.jpg\")\r\n \r\nwith col[3]:\r\n st.image(\"ensiacet.jpg\")\r\n\r\nst.markdown('---')\r\n\r\n\r\n#st.sidebar.image('UT3.PNG')\r\nst.sidebar.header(\"Définition des paramètres\")\r\n\r\n \r\n\r\nHTML_BANNER = \"\"\"\r\n

Colonne de distillation

\r\n

Méthode de MacCabe-Thiele

\r\n \r\n \"\"\"\r\nstc.html(HTML_BANNER)\r\nst.markdown(\"Le dimensionnement d'une colonne de distillation consiste à déterminer son diamètre et sa hauteur. Dans cet application, on va voir les étapes clés pour déterminer **la hauteur d'une colonne de distillation** par la méthode de **MacCabe-Thiele**.\")\r\n\r\n\r\n# =============================================================================\r\n# Définir la fonction d'équilibre\r\n# =============================================================================\r\n\r\n# st.subheader(\"1. Définir la courbe d'équilibre\")\r\n \r\n# liste_équi = [\"Volatilité relative\", \"Valeurs exp\"]\r\n# courbe_équi = st.radio('', liste_équi, index=0)\r\n\r\n# if courbe_équi == liste_équi[0]:\r\nalpha = st.sidebar.text_input(\"Volatilité relative\", 2.5)\r\nalpha = float(alpha)\r\n\r\n# st.write(\"La courbe d'équilibre est déterminée par :\")\r\n# st.markdown(r'###

$$y_{eq}=\\frac{\\alpha x_{eq}}{1 + x_{eq}(\\alpha - 1}$$

', unsafe_allow_html=True)\r\ndef equi(alpha):\r\n x_eq = np.linspace(0, 1, 101)\r\n y_eq = alpha*x_eq/(1+(alpha-1)*x_eq)\r\n return x_eq, y_eq\r\n\r\nx_eq, y_eq = equi(alpha)\r\n\r\n# else:\r\n \r\n# col_x = st.columns(6)\r\n# text_x, x_1, x_2, x_3, x_4, x_5 = col_x[0].text_input(\"\", 'x(-)'), col_x[1].text_input(\"\",0.1), col_x[2].text_input(\"\",0.3), col_x[3].text_input(\"\",0.5), col_x[4].text_input(\"\",0.7), col_x[5].text_input(\"\",0.9)\r\n# x_1, x_2, x_3, x_4, x_5 = float(x_1), float(x_2), float(x_3), float(x_4), float(x_5)\r\n# xx = [0, x_1, x_2, x_3, x_4, x_5, 1]\r\n \r\n# col_y = st.columns(6)\r\n# text_y, y_1, y_2, y_3, y_4, y_5 = col_y[0].text_input(\"\", 'y(-)'), col_y[1].text_input(\"\",0.21), col_y[2].text_input(\"\",0.51), col_y[3].text_input(\"\",0.72), col_y[4].text_input(\"\",0.85), col_y[5].text_input(\"\",0.96)\r\n# y_1, y_2, y_3, y_4, y_5 = float(y_1), float(y_2), float(y_3), float(y_4), float(y_5)\r\n# yy = [0, y_1, y_2, y_3, y_4, y_5, 1]\r\n\r\n# def interpolation(xx, yy):\r\n# cs=CubicSpline(xx,yy)\r\n# x_eq=np.arange(0.00001,1,0.00001)\r\n# y_eq=cs(x_eq)\r\n# return x_eq, y_eq\r\n \r\n# x_eq, y_eq = interpolation(xx, yy)\r\n# alpha = y_eq*(x_eq-1)/(y_eq*x_eq - x_eq)\r\n# alpha = alpha.mean()\r\n\r\nst.write(\"**1. Le nombre minimum d'étages théoriques ($NET_{min}$ à Reflux total)**\")\r\n# =============================================================================\r\n# Définir quelques paramétres\r\n# =============================================================================\r\nq = st.sidebar.number_input(\"La fraction du vapeur dans l'alimentation (q)\", value= 1.0)\r\nq = float(q)\r\nif q==1:\r\n q=0.9999999999\r\n\r\nX_F = st.sidebar.slider(\"Titre molaire de l'alimentation (en plus volatil XF)\",min_value=0.0, max_value=100.0, step=0.1, value=40.0)\r\nX_F = X_F/100\r\nX_D = st.sidebar.slider(\"Titre molaire du distillat (en plus volatil XD)\",min_value=0.0, max_value=100.0, step=0.1, value=95.5)\r\nX_D = X_D/100\r\nX_W = st.sidebar.slider(\"Titre molaire du résidu (en plus volatil XW)\",min_value=0.0, max_value=100.0, step=0.1, value=06.0)\r\nX_W = X_W/100\r\n\r\n\r\n# =============================================================================\r\n# Déterminer Rmin : il faut définir une fonction qui nous retourne le point \r\n# d'intersection entre la courbe d'alimentation et la courbe d'équilibre\r\n# =============================================================================\r\n\r\ndef inter(q, X_F, alpha):\r\n c1 = (q*(alpha-1))\r\n c2 = q + X_F*(1-alpha) - alpha*(q-1)\r\n c3 = -X_F\r\n coeff = [c1, c2, c3]\r\n r = np.sort(np.roots(coeff))\r\n \r\n if r[0]>0:\r\n x_ae = r[0]\r\n else:\r\n x_ae = r[1]\r\n \r\n y_ae = alpha*x_ae/(1+ x_ae*(alpha-1))\r\n if q == 1:\r\n x_fed = [X_F, X_F]\r\n y_fed = [X_F, y_ae]\r\n else:\r\n x_fed = np.linspace(X_F, x_ae, 51)\r\n y_fed = q/(q-1)*x_fed - X_F/(q-1)\r\n \r\n return x_ae, y_ae, y_fed, x_fed\r\nx_ae, y_ae, y_fed, x_fed = inter(q, X_F, alpha)\r\n\r\n# =============================================================================\r\n# NET min\r\n# =============================================================================\r\nR = 1000\r\n\r\nx_inter = (X_F/(q-1)+X_D/(R+1))/(q/(q-1)-R/(R+1))\r\ny_inter = R/(R+1)*x_inter + X_D/(R+1)\r\n\r\n# =============================================================================\r\n# Section de rectification : établissement de la courbe d'enrichissement\r\n# =============================================================================\r\n\r\ndef rect(R, X_D, x_inter):\r\n x_rect = np.linspace(X_D, x_inter, 51)\r\n y_rect = R/(R+1)*x_rect +X_D/(R+1)\r\n return x_rect, y_rect\r\n\r\nx_rect, y_rect = rect(R, X_D, x_inter)\r\n\r\n# =============================================================================\r\n# Section d'allimentation : établissement de la courbe d'allimentation\r\n# =============================================================================\r\n\r\ndef alim(X_F, q, x_inter):\r\n x_alim = np.linspace(X_F, x_inter)\r\n y_alim = q/(q-1)*x_alim - X_F/(q-1)\r\n return x_alim, y_alim\r\n\r\nx_alim, y_alim = alim(X_F, q, x_inter)\r\n\r\n# =============================================================================\r\n# Section d'appauvrissement : établissement de la courbe d'appauvrissement\r\n# =============================================================================\r\n\r\ndef appau(X_W, x_inter, y_inter):\r\n x_appau = np.linspace(X_W, x_inter, 51)\r\n y_appau = (y_inter - X_W)/(x_inter - X_W) * (x_appau - X_W) +X_W\r\n return x_appau, y_appau\r\nx_appau, y_appau = appau(X_W, x_inter, y_inter) \r\n\r\n# =============================================================================\r\n# Construction des étages\r\n# =============================================================================\r\ns = np.zeros((1000,5)) # Empty array (s) to calculate coordinates of stages\r\n\r\nfor i in range(1,1000):\r\n # (s[i,0],s[i,1]) = (x1,y1) --> First point\r\n # (s[i,2],s[i,3]) = (x2,y2) --> Second point\r\n # Joining (x1,y1) and (x2,y2) will result into stages\r\n \r\n s[0,0] = X_D\r\n s[0,1] = X_D\r\n s[0,2] = s[0,1]/(alpha-s[0,1]*(alpha-1))\r\n s[0,3] = s[0,1]\r\n s[0,4] = 0\r\n# x1\r\n s[i,0] = s[i-1,2]\r\n \r\n # Breaking step once (x1,y1) < (xW,xW)\r\n if s[i,0] < X_W:\r\n s[i,1] = s[i,0] \r\n s[i,2] = s[i,0]\r\n s[i,3] = s[i,0]\r\n s[i,4] = i\r\n break\r\n # y1\r\n if s[i,0] > x_inter:\r\n s[i,1] = R/(R+1)*s[i,0] + X_D/(R+1)\r\n else :\r\n s[i,1] = ((y_inter - X_W)/(x_inter - X_W))*(s[i,0]-X_W) + X_W\r\n \r\n # x2\r\n if s[i,0] > X_W:\r\n s[i,2] = s[i,1]/(alpha-s[i,1]*(alpha-1))\r\n else:\r\n s[i,2] = s[i,0]\r\n \r\n # y2\r\n s[i,3] = s[i,1]\r\n \r\n # Nbr des étages\r\n if s[i,0] < x_inter:\r\n s[i,4] = i\r\n else:\r\n s[i,4] = 0\r\n\r\ns = s[~np.all(s == 0, axis=1)] # Clearing up zero containing rows \r\ns_rows = s.shape[0] \r\n\r\nS = np.zeros((s_rows*2,2)) # Empty array to rearragne 's' array for plotting\r\n\r\nfor i in range(0,s_rows):\r\n S[i*2,0] = s[i,0]\r\n S[i*2,1] = s[i,1]\r\n S[i*2+1,0] = s[i,2]\r\n S[i*2+1,1] = s[i,3]\r\n\r\n# =============================================================================\r\n# Déterminier le nombre des étages théoriques\r\n# =============================================================================\r\nx_s = s[:,2:3]\r\ny_s = s[:,3:4]\r\n\r\nstages = np.char.mod('%d', np.linspace(1,s_rows-1,s_rows-1))\r\n\r\nst.set_option('deprecation.showPyplotGlobalUse', False)\r\n\r\nfor label, x, y in zip(stages, x_s, y_s):\r\n plt.annotate(label,\r\n xy=(x, y),\r\n xytext=(0,5),\r\n textcoords='offset points', \r\n ha='right')\r\n\r\nplt.grid(linestyle='dotted')\r\n#plt.title('Distillation Column Design (MacCabe-Thiele Method)')\r\n# if courbe_équi == liste_équi[1]:\r\n# plt.scatter(xx, yy, marker='o', s=10)\r\nplt.plot(x_eq,y_eq,'-', label=\"Courbe d'équilibre\")\r\nplt.plot([0, 1],[0, 1],'black')\r\n\r\nplt.scatter(X_D,X_D, color='r', s=20)\r\nplt.scatter(X_F,X_F, color='r', s=20)\r\nplt.scatter(X_W,X_W, color='r', s=20)\r\n\r\nplt.plot(S[:,0],S[:,1],'r-.', label=\"Etages\")\r\n\r\nplt.legend(loc=\"upper left\")\r\nplt.xlabel(\"x (-)\")\r\nplt.ylabel(\"y (-)\")\r\n\r\nst.pyplot()\r\n\r\nstages_min = s_rows -1\r\n#st.write(\"Le nombre des étages theoriques minimal pour réaliser cette séparation est:\", étages_min,\"étages\")\r\nst.write(r''' $$\\hspace*{5.2cm} NET_{min} =$$''', stages_min)\r\nif stages_min > 15:\r\n st.error(\"Attention!! le nombre des étages theoriques minimal est trop élevé. La distillation à ces conditions n'est pas raisonnable \")\r\nelse :\r\n st.success(\"Parfait! l'opération qu'on souhaite mise en oeuvre est raisonnable\")\r\n\r\n\r\n\r\n\r\n# =============================================================================\r\n# Rmin\r\n# =============================================================================\r\nst.write(r'**2. Le taux de reflux minimum ($R_{min}$ à nombre de plateaux infini)**')\r\n\r\ndef Rmin(X_D, x_ae, y_ae):\r\n x_Rmin = np.linspace(X_D, 0, 51)\r\n y_Rmin = (y_ae - X_D)/(x_ae - X_D) * (x_Rmin - X_D) +X_D\r\n return x_Rmin, y_Rmin\r\nx_Rmin, y_Rmin = Rmin(X_D, x_ae, y_ae) \r\n\r\n######## R_min & R (new) ########\r\nR_min = (X_D-y_ae)/(y_ae - x_ae)\r\nordo = X_D/(R_min +1)\r\n\r\n# =============================================================================\r\n# plot\r\n# =============================================================================\r\n\r\nplt.grid(visible=True, which='major',linestyle=':',alpha=0.6)\r\nplt.grid(visible=True, which='minor',linestyle=':',alpha=0.3)\r\nplt.minorticks_on()\r\n#plt.title('Distillation Column Design (MacCabe-Thiele Method)')\r\n\r\nplt.plot(x_eq,y_eq,'-', label=\"Courbe d'équilibre\")\r\nplt.plot([0, 1],[0, 1],'black')\r\n\r\nplt.scatter(X_D, X_D, color='r', s=20)\r\nplt.scatter(X_F, X_F, color='r', s=20)\r\nplt.scatter(x_ae, y_ae, color='r', s=20)\r\n\r\nplt.plot(x_Rmin, y_Rmin, label=\"Courbe d'enrichissement\")\r\nplt.plot(x_fed,y_fed, label=\"Courbe d'alimentation\")\r\n\r\nplt.legend(loc=\"best\")\r\nplt.xlabel(\"x (-)\")\r\nplt.ylabel(\"y (-)\")\r\n\r\nplt.scatter(0,ordo, color='r', s=20)\r\nplt.text(0.01,ordo-0.08,'($\\\\frac{X_{D}}{R_{min}+1}$)',horizontalalignment='center')\r\nst.pyplot()\r\n\r\nst.markdown(r'###

$$R_{min}=\\frac{X_{D}}{Y_{min}}-1$$

', unsafe_allow_html=True)\r\nst.write(\"$\\hspace*{5.2cm} R_{min} =$\",round(R_min,3))\r\n\r\n\r\nst.write(\"**3. Le nombre d'étages théoriques NET requis pour un taux de reflux R :**\")\r\ncol1 = st.columns(2)\r\n\r\nwith col1[1]:\r\n Coeff = st.slider(\"Coeff\",min_value=1.0, max_value=2.0, step=0.01, value=1.21)\r\n R = Coeff*R_min\r\n\r\nwith col1[0]:\r\n st.write(\"Le taux de reflux réel $R$ est définit par :\")\r\n st.write(\"$R = Coeff \\\\times R_{min}$\")\r\n st.write(\"$R =$\",round(R,3))\r\n\r\n\r\n# =============================================================================\r\n# le point d'intersection entre la courbe d'alimentation et la courbe d'enrichissement\r\n# =============================================================================\r\n\r\nx_inter = (X_F/(q-1)+X_D/(R+1))/(q/(q-1)-R/(R+1))\r\ny_inter = R/(R+1)*x_inter + X_D/(R+1)\r\n\r\n# =============================================================================\r\n# Section de rectification : établissement de la courbe d'enrichissement\r\n# =============================================================================\r\n\r\ndef rect(R, X_D, x_inter):\r\n x_rect = np.linspace(X_D, x_inter, 51)\r\n y_rect = R/(R+1)*x_rect +X_D/(R+1)\r\n return x_rect, y_rect\r\n\r\nx_rect, y_rect = rect(R, X_D, x_inter)\r\n\r\n# =============================================================================\r\n# Section d'allimentation : établissement de la courbe d'allimentation\r\n# =============================================================================\r\n\r\ndef alim(X_F, q, x_inter):\r\n x_alim = np.linspace(X_F, x_inter)\r\n y_alim = q/(q-1)*x_alim - X_F/(q-1)\r\n return x_alim, y_alim\r\n\r\nx_alim, y_alim = alim(X_F, q, x_inter)\r\n\r\n# =============================================================================\r\n# Section d'appauvrissement : établissement de la courbe d'appauvrissement\r\n# =============================================================================\r\n\r\ndef appau(X_W, x_inter, y_inter):\r\n x_appau = np.linspace(X_W, x_inter, 51)\r\n y_appau = (y_inter - X_W)/(x_inter - X_W) * (x_appau - X_W) +X_W\r\n return x_appau, y_appau\r\nx_appau, y_appau = appau(X_W, x_inter, y_inter) \r\n\r\n# =============================================================================\r\n# Construction des étages\r\n# =============================================================================\r\ns = np.zeros((1000,5)) # Empty array (s) to calculate coordinates of stages\r\n\r\nfor i in range(1,1000):\r\n # (s[i,0],s[i,1]) = (x1,y1) --> First point\r\n # (s[i,2],s[i,3]) = (x2,y2) --> Second point\r\n # Joining (x1,y1) and (x2,y2) will result into stages\r\n \r\n s[0,0] = X_D\r\n s[0,1] = X_D\r\n s[0,2] = s[0,1]/(alpha-s[0,1]*(alpha-1))\r\n s[0,3] = s[0,1]\r\n s[0,4] = 0\r\n# x1\r\n s[i,0] = s[i-1,2]\r\n \r\n # Breaking step once (x1,y1) < (xW,xW)\r\n if s[i,0] < X_W:\r\n s[i,1] = s[i,0] \r\n s[i,2] = s[i,0]\r\n s[i,3] = s[i,0]\r\n s[i,4] = i\r\n break\r\n # y1\r\n if s[i,0] > x_inter:\r\n s[i,1] = R/(R+1)*s[i,0] + X_D/(R+1)\r\n else :\r\n s[i,1] = ((y_inter - X_W)/(x_inter - X_W))*(s[i,0]-X_W) + X_W\r\n \r\n # x2\r\n if s[i,0] > X_W:\r\n s[i,2] = s[i,1]/(alpha-s[i,1]*(alpha-1))\r\n else:\r\n s[i,2] = s[i,0]\r\n \r\n # y2\r\n s[i,3] = s[i,1]\r\n \r\n # Nbr des étages\r\n if s[i,0] < x_inter:\r\n s[i,4] = i\r\n else:\r\n s[i,4] = 0\r\n\r\ns = s[~np.all(s == 0, axis=1)] # Clearing up zero containing rows \r\ns_rows = s.shape[0] \r\n\r\nS = np.zeros((s_rows*2,2)) # Empty array to rearragne 's' array for plotting\r\n\r\nfor i in range(0,s_rows):\r\n S[i*2,0] = s[i,0]\r\n S[i*2,1] = s[i,1]\r\n S[i*2+1,0] = s[i,2]\r\n S[i*2+1,1] = s[i,3]\r\n\r\n# =============================================================================\r\n# Déterminier le nombre des étages théoriques\r\n# =============================================================================\r\n# (x2,y2) from 's' array as (x_s,y_s) used for stage numbering\r\nx_s = s[:,2:3]\r\ny_s = s[:,3:4]\r\n\r\nstages = np.char.mod('%d', np.linspace(1,s_rows-1,s_rows-1))\r\n\r\nNET = s_rows-1\r\n\r\n# '''\r\n# localiser l'étage d'alimentation\r\n# '''\r\ns_f = s_rows-np.count_nonzero(s[:,4:5], axis=0)\r\n\r\n# =============================================================================\r\n# FINALE\r\n# =============================================================================\r\n#st.set_option('deprecation.showPyplotGlobalUse', False)\r\n\r\nfig = plt.figure(num=None, figsize=(10, 8))\r\n\r\nfor label, x, y in zip(stages, x_s, y_s):\r\n plt.annotate(label,\r\n xy=(x, y),\r\n xytext=(0,5),\r\n textcoords='offset points', \r\n ha='right')\r\n\r\nplt.grid(linestyle='dotted')\r\nplt.title('Distillation Column Design (MacCabe-Thiele Method)')\r\n\r\nplt.plot(x_eq,y_eq,'-', label=\"Courbe d'équilibre\")\r\nplt.plot([0, 1],[0, 1],'black')\r\n\r\n\r\nplt.scatter(X_D,X_D, color='r' )\r\nplt.scatter(X_F,X_F, color='r' )\r\nplt.scatter(X_W,X_W, color='r' )\r\n\r\nplt.scatter(x_inter,y_inter )\r\nplt.plot(x_alim, y_alim, label=\"Courbe d'alimentation\")\r\nplt.plot(x_appau, y_appau, label=\"Courbe d'appauvrissement\")\r\nplt.plot(x_rect, y_rect, label=\"Courbe d'enrichissement\")\r\n# plt.plot(x_fed,y_fed, color='black' )\r\n\r\nplt.plot(S[:,0],S[:,1],'-.', label=\"Etages\")\r\n\r\nplt.legend(loc=\"upper left\")\r\nplt.xlabel(\"x (-)\")\r\nplt.ylabel(\"y (-)\")\r\n\r\nst.pyplot()\r\n\r\nst.write(r''' $$\\hspace*{5.2cm} NET =$$''', s_rows -1)\r\n\r\nst.write(\"**4. Hauteur de la colonne**\")\r\n\r\nmenu = [\"Colonne à plateaux\",\"Colonne à garnissage\"]\r\ntechno = st.selectbox(\"Technologies\",menu)\r\n\r\nst.markdown(\"La hauteur de la colonne résulte:\")\r\nst.write(\"$~~~~$- du nombre d'étages théoriques nécessaires\")\r\n\r\nif techno == menu[0]:\r\n st.write(\"$~~~~$- de l'efficacité de chaque plateau réel (eff)\")\r\n st.write(\"$~~~~$- de l'espacement entre plateaux (TS pour Tray Spacing)\")\r\n st.markdown(r'###

$$H=\\frac{NET}{eff} \\times TS$$

', unsafe_allow_html=True)\r\n \r\n col2 = st.columns(2)\r\n with col2[0]:\r\n eff = st.text_input(\"efficacité des plateaux (%) \", 90)\r\n eff = float(eff)\r\n \r\n with col2[1]:\r\n TS = st.text_input(\"espacement entre plateaux (m) \", 0.4)\r\n TS = float(TS)\r\n st.write(\"- Hauteur de la colonne =\", round(NET/(eff/100)*TS,2),\"m\")\r\nelse:\r\n st.write(\"$~~~~$- de la hauteur equivalente à un plateau théorique (HEPT)\")\r\n st.markdown(r'###

$$H=NET \\times HEPT$$

', unsafe_allow_html=True)\r\n col2 = st.columns(2)\r\n with col2[0]:\r\n HEPT = st.text_input(\"Hauteur Equivalente à un Plateau Théorique (m)\", 0.8)\r\n HEPT = float(HEPT)\r\n st.write(\"- Hauteur de garnissage à installer =\",round(NET*HEPT,2),\"m\" )\r\n\r\n\r\nButton = st.expander(\"Get In Touch With Me!\")\r\nwith Button:\r\n col31, col32, col33 = st.columns(3)\r\n col31.write(\"[Zakaria NADAH](https://www.linkedin.com/in/zakaria-nadah-00ab81160/)\")\r\n col31.write(\"Ingénieur Procédés Junior\")\r\n col31.write(\"+336.28.80.13.40\")\r\n col31.write(\"zakariaenadah@gmail.com\")\r\n \r\n col33.image(\"profil_.jpg\")\r\n","repo_name":"zakariaNADAH/zakaria","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":18204,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"24362744366","text":"import random\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\n'''\nprepare step:\n'''\n\ndef build_vocab():\n key = 0\n base_char = 'a'\n vocab = {}\n while key < 26:\n vocab[chr(ord(base_char) + key)] = key\n key += 1\n vocab['unk'] = key\n return vocab\n\n'''\n构造的索引矩阵x必须是个int,或者longint,代表词表中的映射\n'''\ndef build_datasets(vocab:dict,sentence_length,size):\n vocab_list = list(vocab.keys())\n if vocab_list.__contains__('unk'):\n vocab_list.remove('unk')\n xs=[]\n ys=[]\n for _ in range(size):\n cur_str = \"\"\n for i in range(sentence_length):\n c = random.choice(vocab_list)\n cur_str+=c\n xs.append([vocab.get(s) for s in cur_str])\n if set(cur_str) & set('abc'):\n ys.append(1)\n else:\n ys.append(0)\n return torch.LongTensor(xs),torch.FloatTensor(ys)\n\n'''\nnlp model.py\n'''\nclass NLP(nn.Module):\n def __init__(self,vector_dim,sentence_length,vocab):\n super(NLP, self).__init__()\n self.embedding = nn.Embedding(len(vocab),vector_dim) #把原本的每个词都拿vector代替,变成 sen_len * dim\n self.pooling = nn.AvgPool1d(sentence_length)\n self.linear = nn.Linear(vector_dim,1) # 向量到具体的一个值,二分类问题\n self.activation = torch.sigmoid\n\n def forward(self,x:torch.LongTensor):\n '''\n x 是一个torch tensor long int: (batch_size,sen_len)\n '''\n x=self.embedding(x) # (batch_size,sen_len) -> (batch_size,sen_len, vector_dim)\n x = x.transpose(1,2)\n x= self.pooling(x) # (batch_size,vector_dim,1)\n x=x.squeeze() # (batch_size,vector_dim)\n\n x= self.linear(x) #(batch_size,1)\n y=self.activation(x)\n return y\n\ndef evaluate(model:nn.Module,vocab,sentence_length):\n model.eval()\n # use test data\n x_test,y_test = build_datasets(vocab,sentence_length,size=200)\n print(\"本次测试集的正样本个数:{},负样本个数:{}\".format(y_test.sum(),200-y_test.sum()))\n right,wrong=0,0\n with torch.no_grad():\n y_pred=model(x_test)\n y_pred=y_pred.squeeze()\n for y_p,y_t in zip(y_pred,y_test):\n if float(y_p) < 0.5 and int(y_t) == 0:\n right += 1 # 负样本判断正确\n elif float(y_p) >= 0.5 and int(y_t) == 1:\n right += 1 # 正样本判断正确\n else:\n wrong += 1\n print(\"正确预测个数:%d, 正确率:%f\"%(right, right/(right+wrong)))\n return right/(right+wrong)\n\ndef plot_log(log):\n import matplotlib.pyplot as plt\n x=range(len(log))\n acc = [l[0] for l in log]\n loss = [l[1] for l in log]\n plt.subplot(211)\n plt.plot(x,acc,label='acc')\n plt.legend()\n plt.subplot(212)\n plt.plot(x,loss,label='loss')\n plt.legend()\n plt.show()\n\n\n\n\ndef main():\n epochs = 100\n sentence_length = 6\n vector_dim=20\n trainning_size_each_epoch = 500\n batch_size = 32\n learning_rate=0.001\n vocab = build_vocab()\n\n model = NLP(vector_dim=vector_dim,vocab=vocab,sentence_length=sentence_length)\n criterion = nn.MSELoss()\n optim = torch.optim.Adam(model.parameters(),lr=learning_rate)\n\n log = []\n\n for epoch in range(epochs):\n model.train()\n watch_loss = []\n for i in range(trainning_size_each_epoch// batch_size):\n start = i*batch_size\n end = (i+1)* batch_size\n if end > trainning_size_each_epoch:\n end = trainning_size_each_epoch\n x,y=build_datasets(vocab,sentence_length,end-start)\n optim.zero_grad()\n y_pred = model(x)\n y_pred = y_pred.squeeze()\n\n loss = criterion(y_pred,y)\n loss.backward()\n optim.step()\n watch_loss.append(loss.item())\n print(\"epoch:{}, loss:{}\".format(epoch+1,np.mean(watch_loss)))\n acc = evaluate(model,vocab,sentence_length)\n log.append([acc,np.mean(watch_loss)])\n plot_log(log)\n\n\nif __name__ =='__main__':\n main()","repo_name":"Yangjianxiao0203/deeplearning-vm-codes","sub_path":"week3/learning/NLPSelfDemo.py","file_name":"NLPSelfDemo.py","file_ext":"py","file_size_in_byte":4090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"71405849053","text":"import sys\nimport json\nimport random\nimport numpy\nimport numpy.random\nimport keras.utils\nfrom keras.preprocessing.sequence import pad_sequences\nimport model\nfrom gensim.models import KeyedVectors\nfrom gensim.models.keyedvectors import Vocab\n\nID,FORM,LEMMA,UPOS,XPOS,FEATS,HEAD,DEPREL,DEPS,MISC=range(10)\n\ndef read_conll(inp,max_sent=0,drop_tokens=True,drop_nulls=True):\n comments=[]\n sent=[]\n yielded=0\n for line in inp:\n line=line.strip()\n if line.startswith(\"#\"):\n comments.append(line)\n elif not line:\n if sent:\n yield sent,comments\n yielded+=1\n if max_sent>0 and yielded==max_sent:\n break\n sent,comments=[],[]\n else:\n cols=line.split(\"\\t\")\n if drop_tokens and \"-\" in cols[ID]:\n continue\n if drop_nulls and \".\" in cols[ID]:\n continue\n sent.append(cols)\n else:\n if sent:\n yield sent,comments\n\n \ndef read_embeddings(embeddings_filename,max_rank_emb):\n \"\"\"Reads .vector or .bin file, modifies it to include and and \"\"\"\n if embeddings_filename.endswith(\".bin\"):\n binary=True\n else:\n binary=False\n gensim_vectors=KeyedVectors.load_word2vec_format(embeddings_filename, binary=binary, limit=max_rank_emb)\n gensim_vectors.vocab[\"\"]=Vocab(index=1)\n gensim_vectors.vocab[\"\"]=Vocab(index=0)\n gensim_vectors.vocab[\"\"]=Vocab(index=2)\n for word_record in gensim_vectors.vocab.values():\n word_record.index+=3\n two_random_rows=numpy.random.uniform(low=-0.01, high=0.01, size=(3,gensim_vectors.vectors.shape[1]))\n # stack the two rows, and the embedding matrix on top of each other\n gensim_vectors.vectors=numpy.vstack([two_random_rows,gensim_vectors.vectors])\n gensim_vectors.vectors=keras.utils.normalize(gensim_vectors.vectors,axis=0)\n gensim_vectors.vectors=keras.utils.normalize(gensim_vectors.vectors)\n return gensim_vectors\n\ndef build_dicts(inp):\n char_dict={\"\":0,\"\":1}\n pos_dict={\"\":0}\n deprel_dict={\"\":0}\n feat_val_dict={} #\"number\" -> {\"\":0,\"sg\":1}\n for tree,comments in read_conll(inp):\n for cols in tree:\n for char in cols[FORM]:\n char_dict.setdefault(char,len(char_dict))\n pos_dict.setdefault(cols[UPOS],len(pos_dict))\n deprel_dict.setdefault(cols[DEPREL],len(deprel_dict))\n deprel_dict.setdefault(cols[DEPREL]+\"-left\",len(deprel_dict))\n deprel_dict.setdefault(cols[DEPREL]+\"-right\",len(deprel_dict))\n if cols[FEATS]!=\"_\":\n for feat_val in cols[FEATS].split(\"|\"):\n feat,val=feat_val.split(\"=\",1)\n feat_dict=feat_val_dict.setdefault(feat,{\"\":0})\n feat_dict.setdefault(val,len(feat_dict))\n return char_dict,pos_dict,deprel_dict,feat_val_dict\n\n\nID,FORM,LEMMA,UPOS,XPOS,FEATS,HEAD,DEPREL,DEPS=range(10)\ndef vectorize_document(doc,word_vocab,lemma_vocab):\n words=[]\n lemmas=[]\n #doc is a list of conllu sentences\n for sent,comment in doc:\n for cols in sent:\n if cols[FORM] in word_vocab:\n words.append(word_vocab[cols[FORM]].index)\n else:\n words.append(word_vocab[\"\"].index)\n if cols[LEMMA] in lemma_vocab:\n lemmas.append(lemma_vocab[cols[LEMMA]].index)\n else:\n lemmas.append(lemma_vocab[\"\"].index)\n return words, lemmas\n\ndef vectorize_data(docs, word_vocab, lemma_vocab):\n docs_words,docs_lemmas=[],[]\n for doc in docs:\n words, lemmas = vectorize_document(doc,word_vocab,lemma_vocab)\n docs_words.append(words)\n docs_lemmas.append(lemmas)\n docs_words=pad_sequences(np.array(docs_words),padding=\"post\",maxlen=word_seq_len)\n docs_lemmas=pad_sequences(np.array(docs_lemmas),padding=\"post\",maxlen=word_seq_len)\n assert docs_words.shape==docs_lemmas.shape\n return {\"inp_words\":docs_words,\"inp_lemmas\":docs_lemmas}\n\n \n \n","repo_name":"fginter/tw_sent_v2","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"15887269821","text":"from uuid import UUID\nimport uuid\nfrom django.forms import model_to_dict\nfrom django.test import TestCase\nimport mock\nfrom casexml.apps.case.tests.util import delete_all_cases, delete_all_xforms\nfrom corehq.apps.case_importer.tasks import do_import\nfrom corehq.apps.case_importer.tests.test_importer import make_worksheet_wrapper\nfrom corehq.apps.case_importer.tracking.case_upload_tracker import CaseUpload\nfrom corehq.apps.case_importer.tracking.dbaccessors import get_case_upload_records, \\\n get_case_ids_for_case_upload\nfrom corehq.apps.case_importer.tracking.models import CaseUploadRecord\nfrom corehq.apps.case_importer.util import ImporterConfig\nfrom corehq.apps.users.models import WebUser, CouchUser\nfrom corehq.form_processor.interfaces.dbaccessors import CaseAccessors\n\n\nclass DbaccessorsTest(TestCase):\n domain = 'test-case-importer-dbaccessors'\n\n @classmethod\n def setUpClass(cls):\n super(DbaccessorsTest, cls).setUpClass()\n cls.case_upload_1 = CaseUploadRecord(\n upload_id=UUID('7ca20e75-8ba3-4d0d-9c9c-66371e8895dc'),\n task_id=UUID('a2ebc913-11e6-4b6b-b909-355a863e0682'),\n domain=cls.domain,\n )\n cls.case_upload_2 = CaseUploadRecord(\n upload_id=UUID('63d07615-7f89-458e-863d-5f9b5f4f4b7b'),\n task_id=UUID('fe47f168-0632-40d9-b01a-79612e98298b'),\n domain=cls.domain,\n )\n cls.case_upload_1.save()\n cls.case_upload_2.save()\n\n @classmethod\n def tearDownClass(cls):\n cls.case_upload_1.delete()\n cls.case_upload_2.delete()\n super(DbaccessorsTest, cls).tearDownClass()\n\n def assert_model_lists_equal(self, list_1, list_2):\n self.assertEqual([(type(model), model_to_dict(model)) for model in list_1],\n [(type(model), model_to_dict(model)) for model in list_2])\n\n def test_get_case_uploads(self):\n self.assert_model_lists_equal(\n get_case_upload_records(self.domain, limit=1),\n # gets latest\n [self.case_upload_2])\n self.assert_model_lists_equal(\n get_case_upload_records(self.domain, limit=2),\n # gets latest first\n [self.case_upload_2,\n self.case_upload_1])\n\n\nclass FormAndCaseIdsTest(TestCase):\n case_type = 'test_case_ids'\n domain = 'form-and-case-ids-test'\n couch_user_id = 'lalalalalala'\n\n @classmethod\n def tearDownClass(cls):\n delete_all_cases()\n delete_all_xforms()\n super(FormAndCaseIdsTest, cls).tearDownClass()\n\n def _get_config(self, excel_fields):\n return ImporterConfig(\n couch_user_id=self.couch_user_id,\n case_type=self.case_type,\n excel_fields=excel_fields,\n case_fields=[''] * len(excel_fields),\n custom_fields=excel_fields,\n search_column=excel_fields[0],\n search_field='case_id',\n create_new_cases=True,\n )\n\n @mock.patch.object(CouchUser, 'get_by_user_id')\n def _import_rows(self, rows, get_by_user_id):\n get_by_user_id.return_value = WebUser(\n _id=self.couch_user_id, domain=self.domain, username='lalala@example.com')\n case_upload_record = CaseUploadRecord(\n upload_id=uuid.uuid4(),\n task_id=uuid.uuid4(),\n domain=self.domain,\n )\n case_upload_record.save()\n self.addCleanup(case_upload_record.delete)\n tracker = CaseUpload(case_upload_record.upload_id)\n # mock internals to have record_cases use our case_upload_record\n tracker.__dict__['_case_upload_record'] = case_upload_record\n\n config = self._get_config(rows[0])\n xls_file = make_worksheet_wrapper(*rows)\n do_import(xls_file, config, self.domain,\n record_form_callback=tracker.record_form)\n\n return case_upload_record\n\n def test_order(self):\n data = [\n ['name'],\n ['john'],\n ['paul'],\n ['george'],\n ['ringo'],\n ]\n case_upload_record = self._import_rows(data)\n case_ids = list(get_case_ids_for_case_upload(case_upload_record))\n cases = CaseAccessors(self.domain).get_cases(case_ids, ordered=True)\n self.assertEqual(case_ids, [case.case_id for case in cases])\n should_match_original_data_order = [['name']] + [[case.name] for case in cases]\n self.assertEqual(should_match_original_data_order, data)\n","repo_name":"WDDCP/commcare-wddcp","sub_path":"corehq/apps/case_importer/tracking/tests/test_dbaccessors.py","file_name":"test_dbaccessors.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"35023114661","text":"from myapp import myFLask\nfrom flask import render_template, request, flash, redirect\nfrom myapp.forms import TopCities\nfrom myapp import db\nfrom myapp.models import citydata\n\n@myFlask.route(\"/\", methods = ['GET' , 'POST'])\ndef hello():\n\tname = 'Bao Thien Vu'\n\ttitle = 'Top Cities'\n\tform = TopCities()\n\tdb.create_all()\n\tcities = citydata.query.all()\n\t\n\tif form.validate_on_submit():\n\t\tif db.session.query(citydata).filter_by(city_Rank = form.city_Rank.data).first():\n\t\t\tflash(f'{form.city_Name.data} was added')\t\t\t\n\t\t\tname = request.form['city_Name']\n\t\t\trank = len(citydata)\n\t\t\tcity = citydata(name, rank)\n\t\t\tdb.session.add(city)\n\t\t\tdb.session.commit()\n\t\t\treturn redirect('/')\n\t\tname = request.form['city_Name']\n\t\trank = request.form['city_Rank']\n\t\tflash(f'{form.city_Name.data} was added')\t\t\t\n\t\tcity = citydata(name, rank)\t\t\n\t\tdb.session.add(city)\n\t\tdb.session.commit()\t\n\t\t\n\t\treturn redirect('/')\n\treturn render_template('home.html',name=name,title=title,form=form,cities=cities)\n\n\t","repo_name":"baovu98/Flask.HW","sub_path":"myapp/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"7746910089","text":"import os\nimport secrets\nfrom flask import Flask, render_template, request, flash\nimport main\nfrom binance_api import fetch_available_pairs\nimport asyncio\nfrom threading import Thread\n\napp = Flask(__name__)\napp.secret_key = secrets.token_hex(16) # Generates a random 32-character-long hexadecimal string\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n results = None\n currency_pairs = []\n if request.method == 'POST':\n currency_pairs = [\n request.form['currency_pair_1'],\n request.form['currency_pair_2'],\n request.form['currency_pair_3'],\n request.form['currency_pair_4'],\n request.form['currency_pair_5'],\n request.form['currency_pair_6']\n ]\n if validate_currency_pairs(currency_pairs):\n results = asyncio.run(main.run_analysis(currency_pairs))\n no_arbitrage_bounds = results['no_arbitrage_bounds']\n\n # Start real-time analysis in a separate thread\n analysis_thread = Thread(target=main.start_real_time_analysis, args=(currency_pairs, no_arbitrage_bounds))\n analysis_thread.start()\n\n return render_template('index.html', results=results, currency_pairs=currency_pairs)\n\ndef validate_currency_pairs(currency_pairs):\n available_pairs = fetch_available_pairs()\n fiat_currencies = set()\n btc_pairs = set()\n\n for pair in currency_pairs:\n if pair not in available_pairs:\n flash(f\"Invalid currency pair: {pair}. Please provide pairs available in the Binance API.\", \"danger\")\n return False\n\n if 'BTC' in pair:\n btc_pairs.add(pair)\n fiat_currencies.add(pair.replace('BTC', ''))\n\n if len(fiat_currencies) != 3 or len(btc_pairs) != 3:\n flash(\"Please provide pairs that can form two different triangular arbitrages with two different FIAT currencies and BTC.\", \"danger\")\n return False\n\n return True\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"Lagrange-fi/Triangular-Arbitrage-Data","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"5045924127","text":"import argparse\nimport os\nimport sys\n\n## Make all dirs under the project's root dir importable\nsys.path.append(os.environ['GITHUB_ACTION_PATH'])\n\nfrom src.get_clone_urls import get_clone_urls\nfrom src.run import run\n\n\ndef main():\n\n p = argparse.ArgumentParser()\n s = p.add_subparsers(dest='cmd')\n\n x = s.add_parser('get-clone-urls')\n x.add_argument('raw')\n\n x = s.add_parser('run')\n\n args = p.parse_args()\n if args.cmd == 'get-clone-urls':\n print(' '.join(get_clone_urls(args.raw))) # Output the result to the shell\n elif args.cmd == 'run':\n run()\n\n\nif __name__ == '__main__':\n main()","repo_name":"nvfp/Line-O-Saurus","sub_path":"src/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"37478140468","text":"\nimport random, h5py\nimport numpy as np\nfrom skimage.transform import resize as skimage_resize\n\nfrom QFlow import config\n\n# class for preparing subimages from large scan for training.\nclass DataCropper():\n\n def __init__(self, excl_range):\n '''\n Class for cropping subimages from larg maps, keeping only data needed \n for training.\n\n inputs:\n excl_range: number of pixels from the edge of the image to exclude \n from subimages.\n '''\n # number of excluded pixels at edge of image\n self.excl_range = excl_range\n\n @staticmethod\n def prob_vec(x):\n '''\n Finds the label for region x. Note that data is multiplied\n by 2 to avoid fractional labels\n Args:\n x = dictionary with label data\n '''\n dist = np.histogram(2*x['state'],[0,1,2,3,4,5])[0]\n prob = dist/np.sum(dist)\n return prob\n\n @staticmethod\n def data_label(x):\n '''\n Generates labels to be stored in data dictionary\n Args:\n x = dictionary with label data\n '''\n x['state'] = DataCropper.prob_vec(x)\n return x\n\n def crop_data(self, noisy_out, noisy_state, noisy_x, noisy_y, noise_factor):\n '''\n Gets cropped data from full noisy_outputs.\n\n inputs:\n noisy_out: 2d ndarray of noisy sensor data.\n noisy_state: 2d ndarray of state data.\n noisy_x: 1d ndarray of x data.\n noisy_y: 1d ndarray of y data.\n noise_factor: float specifying level of noise in data (white noise,\n 1/f noise, and telegraph noise [sensor jumps])\n outputs:\n data: dict containing noise_factor and cropped noisy_out, \n noisy_state, noisy_x, and noisy_y.\n '''\n data = {}\n\n # function to randomly pick an origin for a subimage\n def sub_position(x):\n return random.sample(\n range(int(self.excl_range),\n int(x-config.SUB_SIZE-self.excl_range)), 1)[0]\n\n x_len = len(noisy_x)\n y_len = len(noisy_y)\n\n # get origin for cropped image with clever random sample\n x0, y0 = sub_position(x_len), sub_position(y_len)\n\n # get cropped data starting from randomly generated x0, y0\n data['sensor'] = noisy_out[y0:y0 + config.SUB_SIZE, x0:x0 + config.SUB_SIZE]\n data['state'] = noisy_state[y0:y0 + config.SUB_SIZE, x0:x0 + config.SUB_SIZE]\n\n # get noise level number \n data['noise_mag_factor'] = noise_factor\n\n # save similarly cropped x and y voltages\n data['V_P1'] = np.linspace(noisy_x[x0],\n noisy_x[x0 + config.SUB_SIZE], config.SUB_SIZE)\n data['V_P2'] = np.linspace(noisy_y[y0],\n noisy_y[y0 + config.SUB_SIZE], config.SUB_SIZE)\n\n # get and add data label as prob vector of states\n self.data_label(data)\n\n return data\n\n def crop_full_dataset(self, h5_filename, data_key='noisy_sensor', \n x_key='V_P1_vec', y_key='V_P2_vec', subs_per_map=10, save_data=True,\n return_data=False):\n '''\n Crop all entries in an hdf5 file into subimages.\n\n inputs:\n h5_filename: str path to h5 file containing training data.\n data_key: str key of z data in h5 file.\n x_key: str key of x data in h5 file.\n y_key: str key of y data in h5 file.\n subs_per_map: int number of subimages to get per map.\n save_data: bool whether to save data (as compressed .npz)\n return_data: bool whether to return data (as dict)\n outputs:\n cropped_data: np.ndarray containing training data as subimages.\n '''\n # make sure that either save_data or return_data is true\n if not save_data and not return_data:\n raise ValueError(\n 'save_data False and return_data False. Choose one!')\n\n cropped_data_dict = {}\n with h5py.File(h5_filename, 'r') as h5f:\n for k, v in h5f.items():\n for i in range(subs_per_map):\n data = self.crop_data(\n v['output'][data_key][()], v['output']['state'][()], \n v[x_key][()], v[y_key][()], v['noise_mag_factor'][()])\n\n # create list of cropped data if wanted to save memory\n cropped_data_dict[k+('%i'%i)] = data\n\n print(len(cropped_data_dict.keys()))\n if save_data:\n numpy_filename = '.'.join(h5_filename.split('.')[:-1])+'.npz'\n np.savez_compressed(numpy_filename, **cropped_data_dict)\n\n if return_data:\n return cropped_data_dict\n else:\n return None","repo_name":"jpzwolak/QFlow-suite","sub_path":"QFlow-2.0/QFlow/Crop_Data.py","file_name":"Crop_Data.py","file_ext":"py","file_size_in_byte":4814,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"33"} +{"seq_id":"18898972301","text":"from kelas import *\n\n#dir=str(input(\"Masukkan direktori file : \\n\"))\ntestfile=open(\"C:\\\\users\\\\LENOVO\\\\Desktop\\\\dilla\\\\tesmainan.txt\",\"r\",encoding=\"utf 8\")\nprint(testfile.read())\n\ntestfile.seek(0)\ncounts={}\nfor baris in testfile:\n katakata = baris.split(\" \") #nama saya Dilla rumah: -> [nama,saya,Dilla, rumah:, rumah-rumah]\n for kata in katakata: #nama->saya->Dilla->rumah\n for katabersih in ilanginsimbol(kata): #nama-> nama, rumah: -> rumah, rumah-rumah -> [rumah,rumah]\n counts[katabersih.lower()]=counts.get(katabersih.lower(),0)+1\nprint(counts)\n\nkataterbanyak=str()\njumlahkata=0\n\nfor f in counts.keys():\n if counts[f]>jumlahkata:\n kataterbanyak=f\n jumlahkata=counts[f]\n\nprint(kataterbanyak,\":\",jumlahkata)\n","repo_name":"fadilla996/Projek-Python","sub_path":"mainan2upgrade.py","file_name":"mainan2upgrade.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"14736657291","text":"#Bottom Up Approach \ndef Longest_Subseq(str1,str2):\n m = len(str1)\n n = len(str2)\n maxLength = 0\n\n dp = [[0 for x in range(n + 1)] for y in range(m + 1)]\n\n for i in range(1,m+1):\n for j in range(1,n+1):\n \n if str1[i-1] == str2[j-1]:\n dp[i][j] = 1 + dp[i-1][j-1]\n\n else:\n dp[i][j] = max(dp[i][j-1],dp[i-1][j])\n\n if dp[i][j] > maxLength:\n maxLength = dp[i][j] \n\n print(maxLength)\n return maxLength\n\nstr1 = 'zxvio'\nstr2 = 'zcvm'\n\nLongest_Subseq(str1,str2)","repo_name":"Rajthilakam/DataStructures_Kal","sub_path":"Dynamic Programming/Longest_Common_SubSequence.py","file_name":"Longest_Common_SubSequence.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"8020109358","text":"import streamlit as st\nimport seaborn as sns\n\n\n\n# DATA DISPLAY ELEMENTS\n## interactive dataframe \n## st.dataframe(data=None, width=None, height=None)\ndf = sns.load_dataset('titanic')\n## default\nst.write(\"dataframe default size\")\nst.dataframe(df)\n## 1000 px x 100 px\nst.write(\"dataframe default size\")\nst.dataframe(df, 1000, 100)\n\n## static table\n## st.table(data=None)\nst.write(\"table default\")\n#st.table(df)\n#st.table(df.iloc[0:5,0:3])\n\n\n## metric\n## st.metric(label, value, delta=None, delta_color=\"normal\", help=None)\nst.metric(\n label = \"My bills\",\n value = \"RM 60\",\n delta = \"8%\"\n)\n\n## 3 metric in 1 row\ncol1, col2, col3 = st.columns(3)\ncol1.metric(\"Temperature\", \"30 °C\", \"1.2 °C\")\ncol2.metric(\"Wind\", \"9 mph\", \"-8%\")\ncol3.metric(\"Humidity\", \"86%\", \"4%\")","repo_name":"norsyahidahzul/Intro_StreamlitTutorial","sub_path":"3_datadisplay.py","file_name":"3_datadisplay.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"30409116456","text":"from flask import Flask, render_template, redirect, request, session, flash\n\napp = Flask(__name__)\napp.secret_key = \"Whatever\"\n\n@app.route('/')\ndef index():\n return render_template(\"index.html\")\n\n@app.route('/This/is/the/route')\ndef new():\n return \"You found the route!\"\n\n@app.route('/process', methods=[\"POST\"])\ndef process():\n print(request.form)\n name = request.form['name']\n email = request.form['email']\n\n if not name:\n flash(\"Name is required.\")\n if not email:\n flash(\"Email is required.\")\n\n if '_flashes' in session.keys():\n return redirect('/')\n else:\n session['name'] = name\n session['email'] = email\n return redirect('/success')\n\n@app.route('/success')\ndef success():\n return render_template('success.html')\n\n@app.route('/id/')\ndef id(num):\n session['id'] = num\n return redirect('/success')\n\n@app.route('/clear')\ndef clear():\n session.clear() # clears all keys in session\n return redirect('/')\n\napp.run(debug=True, port=5432)\n","repo_name":"nramiscal/flaskDemo","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"30642261533","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # TORCH 03. Autograd: automotic differentiation\n# - `autograd` package provides automatic differentiation for all operations on Tensors\n\n# ## Tensor\n\n# In[1]:\n\n\nimport torch\nprint(torch.__version__)\n\n\n# In[2]:\n\n\n# Create a tensor and set `requires_grad=True` to track computation with it\nx = torch.ones(2, 2, requires_grad=True)\nprint(x)\n\n\n# In[3]:\n\n\n# Do a tensor operation\ny = x + 2\nprint(y, end='\\n\\n')\n\n# y was created as a result of an operation, so it has a `grad_fn`\nprint(y.grad_fn, end='\\n\\n')\n\n# Do more operations on y\nz = y * y * 3\nout = z.mean()\nprint(z, out)\n\n\n# In[4]:\n\n\n# `.requires_grad_( ... )` changes an existing Tensor's `requires_grad` flag in-place.\n# The input flag defaults to `False` if not given.\na = torch.randn(2, 2)\na = ((a * 3) / (a - 1))\nprint(a.requires_grad) # default is False\na.requires_grad_(True) # Set requres_grad as True\nprint(a.requires_grad) # It will be a True\nb = (a * a).sum()\nprint(b.grad_fn) # Since requires_grad is True, exists grad_fn\n\n\n# ## Gradients\n\n# In[5]:\n\n\nout\n\n\n# In[6]:\n\n\n# Since `out` contains a single scalar,\n# `out.backward()` is equivalent to `out.backward(torch.tensor(1,))`.\nout.backward() # 역전파 실시\n\n\n# In[7]:\n\n\n# Print gradients d(out)/dx\nprint(x.grad)\n\n\n# $$o = {\\cfrac{1}{4}}{\\sum_{i}{z_{i}}}$$\n# $$z_{i} = 3(x_{i}+2)^{2}$$\n# $$z_{i}|_{x_{i}=1}=27$$\n# $$\\text{Therefore,}{\\;}\\cfrac{{\\partial}o}{{\\partial}x_{i}}=\\cfrac{3}{2}(x_{i}+2)$$\n# $${\\cfrac{{\\partial}o}{{\\partial}x_{i}}}\\bigg{|}_{x_{i}=1}=\\cfrac{9}{2}=4.5$$\n\n# $$\\text{Mathematically, if you have a vector valued function}\\;\\vec{y}=f(\\vec{x}),$$\n# $$\\text{then the gradient of}\\;\\vec{y}\\text{ with respect to}\\;\\vec{x}\\text{ is a jacobian matrix:}$$\n# $$J=\\begin{pmatrix}\n# \\cfrac{{\\partial}y_{1}}{{\\partial}x_{1}} & \\cdots & \\cfrac{{\\partial}y_{1}}{{\\partial}x_{n}}\\\\\n# \\vdots & \\ddots & \\vdots\\\\\n# \\cfrac{{\\partial}y_{m}}{{\\partial}x_{1}} & \\cdots & \\cfrac{{\\partial}y_{m}}{{\\partial}x_{n}}\\\\\n# \\end{pmatrix}$$\n\n# $$\\text{Generally speaking, `torch.autograd` is an engine for computing vector-Jacobian product.}$$\n# $$\\text{That is, given any vector }v=(v1{\\quad}v2{\\quad}{\\cdots}{\\quad}v_{m})^{T}\\text{, compute the product }v^{T}{\\cdot}J$$\n# $$\\text{If }v\\text{ happens to be the gradient of a scalar function }l=g\\big{(}\\vec{y}\\big{)}\\text{, that is, }v=\\bigg{(}\\cfrac{{\\partial}l}{{\\partial}y_{1}}\\;\\cdots\\;\\cfrac{{\\partial}l}{{\\partial}y_{m}}\\bigg{)}^{T}\\text{,}$$\n# $$\\text{then by the chain rule, the vector-Jacobian product would be the gradient of }l\\text{ with respect to }\\vec{x}\\text{:}$$\n# $$J^{T}\\cdot{v}=\\begin{pmatrix}\n# \\cfrac{{\\partial}y_{1}}{{\\partial}x_{1}} & \\cdots & \\cfrac{{\\partial}y_{m}}{{\\partial}x_{1}}\\\\\n# \\vdots & \\ddots & \\vdots\\\\\n# \\cfrac{{\\partial}y_{1}}{{\\partial}x_{n}} & \\cdots & \\cfrac{{\\partial}y_{m}}{{\\partial}x_{n}}\\\\\n# \\end{pmatrix}\\begin{pmatrix}\n# \\cfrac{{\\partial}l}{{\\partial}y_{1}}\\\\\n# \\vdots\\\\\n# \\cfrac{{\\partial}l}{{\\partial}y_{m}}\\\\\n# \\end{pmatrix}=\\begin{pmatrix}\n# \\cfrac{{\\partial}l}{{\\partial}x_{1}}\\\\\n# \\vdots\\\\\n# \\cfrac{{\\partial}l}{{\\partial}x_{n}}\\\\\n# \\end{pmatrix}$$\n# $$\\text{(Note that }v^{T}\\cdot{J}\\text{ gives a row vector which can be treated as a column vector by taking }{J}^{T}\\cdot{v}\\text{)}$$\n# $$\\text{This characteristic of vector-Jacobian product makes it very convenient to feed external gradients into a model that has non-scalar output.}$$\n\n# In[8]:\n\n\n# vector-Jacobian product example\nx = torch.randn(3, requires_grad=True)\nprint('x :', x)\ny = x * 2\nwhile y.data.norm() < 1000:\n y = y * 2\nprint('y :', y)\n\n\n# In[9]:\n\n\n# y is not a scalar,\n# `torch.autograd` could not compute the full jacobian directly,\n# but if we just want the vector-jacobian product,\n# simply pass the vector to `backward` as argument.\nv = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)\ny.backward(v)\n\nprint(x.grad)\n\n\n# In[10]:\n\n\n# Stop autograd from tracking history on Tensors with `.requires_grad=True`\n# By wrapping the code block in `with torch.no_grad():`\nprint(x.requires_grad)\nprint((x ** 2).requires_grad)\n\nwith torch.no_grad():\n print((x ** 2).requires_grad)\n\n\n# In[11]:\n\n\n# Or by using `.detach()` to get a new Tensor with the same content\n# but that does not require gradients\nprint(x.requires_grad)\ny = x.detach()\nprint(y.requires_grad)\nprint(x.eq(y).all())\n\n\n# ## AUTOMATIC DIFFERENTIATION PACKAGE - TORCH.AUTOGRAD\n\n# ## `__init__.py`\n\n# In[12]:\n\n\n# SOURCE CODE FOR TORCH.AUTOGRAD\nimport torch\nimport warnings\n\nfrom torch.autograd.variable import Variable\nfrom torch.autograd.function import Function, NestedIOFunction\nfrom torch.autograd.gradcheck import gradcheck, gradgradcheck\nfrom torch.autograd.grad_mode import no_grad, enable_grad, set_grad_enabled\nfrom torch.autograd.anomaly_mode import detect_anomaly, set_detect_anomaly\nfrom torch.autograd import profiler\n\n\n# In[13]:\n\n\n__all__ = ['Variable', 'Function', 'backward', 'grad_modea']\n\n\n# In[14]:\n\n\ndef _make_grads(outputs, grads):\n new_grads = []\n for out, grad in zip(outputs, grads):\n # Gradient가 torch.Tensor객체 일 경우\n if isinstance(grad, torch.Tensor):\n # out과 grad의 shape 체크\n if not out.shape == grad.shape:\n raise RuntimeError(\"Mismatch in shape: grad_output[\"\n + str(grads.index(grad)) + \"] has a shape of \"\n + str(grad.shape) + \" and output[\"\n + str(outputs.index(out)) + \"] has a shape of \"\n + str(out.shape) + \".\")\n new_grads.append(grad)\n # Gradient가 None일 경우\n elif grad is None:\n # requires_grad == True :\n if out.requires_grad:\n # out이 scalar가 아닐 경우 에러 처리\n if out.numel() != 1:\n '''\n # Returns the total number of elements in the `input` tensor.\n >>> a = torch.randn(1, 2, 3, 4, 5)\n >>> torch.numel(a)\n 120\n >>> a = torch.zeros(4, 4)\n >>> torch.numel(a)\n 16\n '''\n raise RuntimeError(\"grad can be implicitly created only for scalar outputs\")\n \n new_grads.append(torch.ones_like(out, memory_format=torch.preserve_format))\n # requires_grad == False : None 추가\n else:\n new_grads.append(None)\n # Gradient가 torch.Tensor 혹은 None이 아닐 경우 에러처리\n else:\n raise TypeError(\"gradients can be either Tensors or None, but got \" +\n type(grad).__name__)\n # tuple로 return\n return tuple(new_grads)\n\n\n# In[15]:\n\n\ndef backward(tensors, grad_tensors=None, retain_graph=None, create_graph=False,\n grad_variables=None):\n \"\"\"\n Computes the sum of gradients of given tensors w.r.t. graph leaves.\n \"\"\"\n if grad_variables is not None:\n warnings.warn(\"'grad_variables' is deprecated. Use 'grad_tensors' instead.\")\n if grad_tensors is None:\n grad_tensors = grad_variables\n else:\n raise RuntimeErorr(\"'grad_tensors' and 'grad_variables' (deprecated) \"\n \"arguments both passed to backward(). Please only \"\n \"use 'grad_tensors'.\")\n \n tensors = (tensors, ) if isinstance(tensors, torch.Tensor) else tuple(tensors)\n \n if grad_tensors is None:\n grad_tensors = [None] * len(tensors)\n elif isinstance(grad_tensors, torch.Tensor):\n grad_tensors = [grad_tensors]\n else:\n grad_tensors = list(grad_tensors)\n \n grad_tensors = _make_grads(tensors, grad_tensors)\n if retain_graph is None:\n retain_graph = create_graph\n \n # 위에서 설정만 잡아주고 돌리는건 C++ Imperative Engine에서 돌린다.\n Variable._execution_engine.run_backward(\n tensors, grad_tensors, retain_graph, create_graph,\n allow_unreachable=True) # allow_unreachable flag\n\n\n# In[16]:\n\n\ndef grad(outputs, inputs, grad_outputs=None, retain_graph=None, create_graph=False,\n only_inputs=True, allow_unused=False):\n \"\"\"\n Computes and returns the sum of gradients of outputs w.r.t. the inputs.\n \"\"\"\n if not only_inputs:\n warnings.warn(\"only_inputs argument is deprecated and is ignored now \"\n \"(defualts to True). To accumulate gradient for other \"\n \"parts of the graph, please use torch.autograd.backward.\")\n \n outputs = (outputs,) if isinstance(outputs, torch.Tensor) else tuple(outputs)\n inputs = (inputs,) if isinstance(inputs, torch.Tensor) else tuple(inputs)\n \n if grad_outpus is None:\n grad_outputs = [None] * len(outputs)\n elif isinstance(grad_outputs, torch.Tensor):\n grad_outputs = [grad_outputs]\n else:\n grad_outputs = list(grad_outputs)\n \"\"\"\n 아니, 지금 elif랑 else랑 차이가 뭐야?\n ```python\n >>> a\n tensor([[1.8083, 1.6985],\n [2.0055, 1.6993]], requires_grad=True)\n >>> [a]\n [tensor([[1.8083, 1.6985],\n [2.0055, 1.6993]], requires_grad=True)]\n >>> list(a)\n [tensor([1.8083, 1.6985], grad_fn=),\n tensor([2.0055, 1.6993], grad_fn=)]\n ```\n 때문에 위와 같이 다르게 처리해줘야한다!\n \"\"\"\n grad_outputs = _make_grads(outputs, grad_outputs)\n \n if retain_graph is None:\n retain_graph = create_graph\n \n return Variable._execution_engine.run_backward(\n outputs, grad_outputs, retain_graph, create_graph,\n inputs, allow_unused)\n\n\n# In[17]:\n\n\n# This function applies in case of gradient checkpointing for memory\n# optimization. Currently, for gradient checkpointing, we only support imperative\n# backwards call i.e. torch.autograd.backward() and the torch.autograd.grad() won't\n# work. The reason being that: torch.autograd.grad() only calculates the grads\n# for the inputs that are passed by user but it doesn't calculate grad for\n# anything else e.g. model parameters like weights, bias etc. However, for\n# torch.autograd.backward(), we would actually compute the grad for the weights as well.\n#\n# This function returns whether the checkpointing is valid i.e. torch.autograd.backward\n# or not i.e. torch.autograd.grad. The implementation works by maintaining a thread\n# local variable in torch/csrc/autograd/engine.cpp which looks at the NodeTask\n# in the stack and before a NodeTask is executed in evaluate_function, it\n# checks for whether reentrant backwards is imperative or not.\n# See https://github.com/pytorch/pytorch/pull/4594 for more discussion/context\ndef _is_checkpoint_valid():\n return Variable._execution_engine.is_checkpoint_valid()\n\n\n# In[18]:\n\n\ndef variable(*args, **kwargs):\n warnings.warn(\"torch.autograd.variable(...) is deprecated, use torch.tensor(...) instead\")\n return torch.tensor(*args, **kwargs)\n\n\n# ```python\n# if not torch._C._autograd_init():\n# raise RuntimeError(\"autograd initialization failed\")\n# ```\n\n# ## Locally disabling gradient computation\n\n# ### `torch.autograd.no_grad`\n# - Context-manager that disabled gradient calculation\n\n# In[19]:\n\n\nno_grad\n\n\n# In[27]:\n\n\nx = torch.tensor([1], requires_grad=True)\n\n\n# https://github.com/pytorch/pytorch/issues/17345\n# Bug in here:\n# ```\n# pytorch/torch/multiprocessing/reductions.py\n# \n# 83 t = torch.nn.parameter.Parameter(t) \n# 84 t.requires_grad = requires_grad \n# ```\n\n# In[28]:\n\n\nx = torch.tensor([1.0], requires_grad=True)\nx\n\n\n# In[31]:\n\n\nx2 = x * 2\nx.requires_grad\n\n\n# In[32]:\n\n\nwith torch.no_grad():\n y = x * 2\ny.requires_grad\n\n\n# In[33]:\n\n\n@torch.no_grad()\ndef doubler(x):\n return x * 2\n\nz = doubler(x)\nz.requires_grad\n\n\n# ### `torch.autograd.enable_grad`\n# - Context-manager that enables gradient calculation\n\n# In[34]:\n\n\nenable_grad\n\n\n# In[35]:\n\n\nx = torch.tensor([1.0], requires_grad=True)\n\nwith torch.no_grad():\n with torch.enable_grad():\n y = x * 2\ny.requires_grad\n\n\n# In[36]:\n\n\ny.backward()\n\n\n# In[37]:\n\n\nx.grad\n\n\n# In[38]:\n\n\n@torch.enable_grad()\ndef doubler(x):\n return x * 2\n\nwith torch.no_grad():\n z = doubler(x)\n \nz.requires_grad\n\n\n# ### `torch.autograd.set_grad_enabled`\n# - Context-manager that sets gradient calculation to on or off\n# - When using `enabled_grad` context manager, `set_grad_enabled(False)` has no effect.\n\n# In[40]:\n\n\nx = torch.tensor([1.0], requires_grad=True)\nis_train = False\n\nwith torch.set_grad_enabled(is_train):\n y = x * 2\n \ny.requires_grad\n\n\n# In[41]:\n\n\ntorch.set_grad_enabled(True)\ny = x * 2\ny.requires_grad\n\n\n# In[42]:\n\n\ntorch.set_grad_enabled(False)\ny = x * 2\ny.requires_grad\n\n\n# In[47]:\n\n\n# 응용해보자\nx = torch.tensor([1.0], requires_grad=True)\n\n@torch.enable_grad()\ndef linear_transform(x, a, b):\n return a * x + b\n\ndef linear_transform2(x, a, b):\n return a * x + b\n\nis_train = False\nwith torch.set_grad_enabled(is_train):\n y = linear_transform(x, 2, 3)\n z = linear_transform2(x, 2, 3)\n\ny.requires_grad, z.requires_grad\n\n\n# ## In-place operations on Tensors\n# - `Variable` is deprecated\n\n# ```python\n# class Tensor(torch._C._TensorBase):\n# ...\n# def backward(self, gradient=None, retain_graph=None, create_graph=False):\n# torch.autograd.backward(self, gradient, retain_graph, create_graph)\n# ...\n# ```\n","repo_name":"jinmang2/Advanced_Python","sub_path":"DeepPytorch/TORCH03_autograd.py","file_name":"TORCH03_autograd.py","file_ext":"py","file_size_in_byte":13437,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"33"} +{"seq_id":"13613888954","text":"nome = \"Kratos\"\nprofissao = \"Deus da Guerra\"\nnascimento = \"Esparta\"\n\nprint(f\"Meu nome é {nome}! Atualmente, atuo como {profissao} na mitologia Nórdica. Entretanto, sou natural de {nascimento}\")\n\nPI = 3.14159\n\nprint(f\"Valor de PI: {PI:.2f}\")\n\nnome = \"Brenno\"\nprofissao = \"Dev\"\nlinguagem = \"Python\"\n\nprint(\"Nome: %s profissao: %s linguagem: %s\" % (nome, profissao, linguagem))\n\nprint(\"Nome: {} profissão: {}\" .format(nome, profissao))\n\ndados = {\"nome\": \"Guilherme\", \"idade\": 28}\nprint(\"Nome: {nome} Idade: {idade}\" .format(**dados))\n","repo_name":"brennocm/formacao-python-developer","sub_path":"04-string-e-fatiamento/02-interpolacao_de_variavel.py","file_name":"02-interpolacao_de_variavel.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"27655231733","text":"from lxml import html\nimport requests\nimport re\nimport csv\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup as bs\nfrom selenium import webdriver \nfrom selenium.webdriver import Chrome, ChromeOptions\nfrom selenium.webdriver.chrome.service import Service \nfrom selenium.webdriver.common.by import By \nfrom webdriver_manager.chrome import ChromeDriverManager\n\ndef html_parse_tree(url):\n options = ChromeOptions()\n options.add_argument(\"--headless=new\")\n options.add_experimental_option('excludeSwitches', ['enable-logging'])\n options.page_load_strategy = 'normal' \n chrome_path = \"./bin/chromedriver.exe\" #ChromeDriverManager()#.install() \n chrome_service = Service(chrome_path) \n driver = Chrome(options=options, service=chrome_service) \n #driver.implicitly_wait(5)\n driver.get(url) \n return html.fromstring(driver.page_source)\n\ndef xpath_parse(tree, xpath):\n result = tree.xpath(xpath)\n return result\n\ndef regex_strip_array(array):\n for i in range(0, len(array)):\n array[i] = regex_strip_string(array[i]).strip()\n return array\n\ndef regex_strip_string(string):\n string = re.sub('\\n', '', string).strip()\n string = re.sub('\\r', '', string).strip()\n string = re.sub('\\t', '', string).strip()\n return string\n\ndef format_spacing(max_spacing, variable):\n spacing_count = max_spacing - len(variable)\n output = ''\n for i in range(0, spacing_count):\n output += ' '\n return output\n\ndef fraction_stats(string):\n string = string.replace('(', '')\n string = string.replace(')', '')\n return string.split('/')\n\ndef add2csv(array, filename):\n with open(filename, 'a',newline='',encoding=\"utf8\") as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(array)\n\ndef array2csv(array, filename):\n with open(filename, \"w+\",newline='',encoding=\"utf8\") as my_csv:\n csvWriter = csv.writer(my_csv, delimiter = ',')\n csvWriter.writerows(array)\n\ndef html2csv(html, filename):\n with open(filename, \"a\",encoding=\"utf8\") as my_file:\n my_file.write(html)","repo_name":"chboudry/PariTennis","sub_path":"scrap_atp_utils.py","file_name":"scrap_atp_utils.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"16282993118","text":"# Evaluate pretrained models on cinic10 dataset. \nimport os \nimport json\nimport subprocess\nfrom plot_metrics import dataindex\n\nhere = os.path.dirname(os.path.abspath(__file__))\nresultpath = os.path.join(here,\"../results\") \n\ndef get_ckptpath(orig_stub):\n metadata = os.path.join(resultpath,orig_stub+\"_meta.json\")\n with open(metadata,\"r\") as f:\n metadict = json.load(f)\n checkpointpath = metadict[\"save_path\"]\n checkpoint = os.listdir(checkpointpath)\n classifier = metadict[\"classifier\"]\n softmax = metadict.get(\"softmax\",\"1\")\n command_data = {\"checkpointpath\":os.path.join(checkpointpath,checkpoint[0]),\"classifier\":classifier,\"softmax\":str(softmax)} \n return command_data \n\ndef run_eval(command_data):\n \"\"\"Assume not checkpoint \n\n \"\"\"\n\n command = [\"export MKL_THREADING_LAYER=GNU;\",\"python\", os.path.join(here,\"train.py\"),\"--classifier\",command_data[\"classifier\"],\"--softmax\",command_data[\"softmax\"],\"--checkpoint\",command_data[\"checkpointpath\"],\"--test_phase\",\"1\",\"--ood_dataset\",\"cinic10\",\"--module\",\"base\"]\n try:\n subprocess.run(\" \".join(command),shell = True,check = True)\n except subprocess.CalledProcessError as e: \n print(e.output)\n \n\nif __name__ == \"__main__\":\n ## dictionary: {\"modelcode\":{\"checkpoint\":\"checkpointpath\",\"orig_stub\":,\"cinic10_path\":}\n # 1. get the metadata files containing model checkpoints: -> checkpointpath\n # 2. run train.py for each of these model checkpoints. -> cinic10_path\n for d,dstub in dataindex.items():\n try:\n if not d.startswith(\"Ensemble\"):\n command_data = get_ckptpath(dstub)\n run_eval(command_data)\n except Exception as e: \n print(\"Encountered issue for {}: {}\".format(dstub,e))\n \n","repo_name":"cellistigs/interp_ensembles","sub_path":"scripts/eval_cinic10.py","file_name":"eval_cinic10.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"33"} +{"seq_id":"20744941765","text":"import elkai\nimport networkx as nx\nimport numpy as np\n\n\ndef decode(output_words_list, G_for_decode, queries_features, titles_features):\n if \"\" in output_words_list:\n output_words_list.remove(\"\")\n if \"\" in output_words_list:\n output_words_list.remove(\"\")\n ordered_output_words, success = heuristic_decode(output_words_list, queries_features, titles_features)\n if success:\n return ordered_output_words\n\n ordered_output_words = ATSP_decode(output_words_list, G_for_decode, queries_features, titles_features)\n return ordered_output_words\n\n\ndef heuristic_decode(output_words_list, queries_features, titles_features):\n success = False\n ordered_output_words = []\n num_output_words = len(output_words_list)\n features = queries_features + titles_features\n\n for feat in features:\n num_words = len(feat[\"word\"])\n if num_words < num_output_words:\n continue\n\n for i in range(num_words - num_output_words + 1):\n chunk = feat[\"word\"][i:i + num_output_words]\n if set(chunk) == set(output_words_list): # continuous full matching\n ordered_output_words = chunk\n success = True\n return ordered_output_words, success\n\n return ordered_output_words, success\n\n\ndef ATSP_decode(output_words_list, G_for_decode, queries_features, titles_features):\n # STEP1: refine graph for decoding\n features = queries_features + titles_features\n\n # Connect node with the first word that belongs to output_words_list in each query or title\n for feat in features:\n for w in feat[\"word\"]:\n if w in output_words_list:\n if not G_for_decode.has_edge(\"\", w):\n G_for_decode.add_edges_from([(\"\", w, {\"label\": \"s\", \"edge_type\": \"s\", \"color\": \"red\", \"seq_id\": 0})])\n break\n\n # Connect node with the last word that belongs to output_words_list in each query or title\n for feat in features:\n feat[\"word\"].reverse()\n for w in feat[\"word\"]:\n if w in output_words_list:\n if not G_for_decode.has_edge(w, \"\"):\n G_for_decode.add_edges_from([(w, \"\", {\"label\": \"s\", \"edge_type\": \"s\", \"color\": \"red\", \"seq_id\": 0})])\n break\n feat[\"word\"].reverse()\n\n # define distances\n output_words_list = [\"\"] + output_words_list + [\"\"]\n num_nodes = len(output_words_list)\n D = np.zeros((num_nodes, num_nodes), dtype=int)\n for i in range(num_nodes):\n for j in range(num_nodes):\n src = output_words_list[i]\n tgt = output_words_list[j]\n if src == tgt:\n D[i, j] = 0\n continue\n if src == \"\" and tgt == \"\":\n D[i, j] = 0\n continue\n try:\n D[i, j] = nx.shortest_path_length(G_for_decode, src, tgt)\n except:\n D[i, j] = 10e5 # no path between src and tgt, then infinite distance\n continue\n\n # if EGTSP\n # transform into file format: http://www.cs.rhul.ac.uk/home/zvero/GTSPLIB/\n # solve by program: http://akira.ruc.dk/~keld/research/GLKH/\n\n # if ATSP\n ATSP_path = elkai.solve_int_matrix(D)\n ordered_output_words = [output_words_list[idx] for idx in ATSP_path]\n ordered_output_words.remove(\"\")\n ordered_output_words.remove(\"\")\n return ordered_output_words\n","repo_name":"BangLiu/GIANT","sub_path":"model/EGTSP_decoder.py","file_name":"EGTSP_decoder.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"33"} +{"seq_id":"72086050655","text":"\"\"\"Discrete distributions with finite support for the umf package.\"\"\"\nfrom __future__ import annotations\n\nimport math\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom umf.functions.other.support_functions import combinations\nfrom umf.meta.api import SummaryStatisticsAPI\nfrom umf.meta.functions import DiscreteP\n\n\nif TYPE_CHECKING:\n from umf.types.static_types import UniversalArray\n\n__all__: list[str] = [\"BernoulliDistribution\", \"BinomialDistribution\"]\n\n\nclass BernoulliDistribution(DiscreteP):\n r\"\"\"Bernoulli distribution.\n\n The Bernoulli distribution is a discrete distribution with two possible\n outcomes, 0 and 1. It is the simplest discrete distribution. It is a\n special case of the binomial distribution where a single trial is\n conducted (n=1).\n\n Examples:\n >>> # PMF Example\n >>> import matplotlib.pyplot as plt\n >>> import numpy as np\n >>> from umf.functions.distributions.discrete_finite_support import (\n ... BernoulliDistribution\n ... )\n >>> x = np.linspace(0, 1, 1000)\n >>> y_05 = BernoulliDistribution(x, p=0.5).__eval__\n >>> y_07 = BernoulliDistribution(x, p=0.7).__eval__\n >>> y_09 = BernoulliDistribution(x, p=0.9).__eval__\n >>> fig = plt.figure()\n >>> ax = plt.subplot()\n >>> _ = ax.plot(x, y_05, label=\"p=0.5\")\n >>> _ = ax.plot(x, y_07, label=\"p=0.7\")\n >>> _ = ax.plot(x, y_09, label=\"p=0.9\")\n >>> _ = ax.set_xlabel(\"x\")\n >>> _ = ax.set_ylabel(\"f(x)\")\n >>> _ = ax.legend()\n >>> plt.savefig(\"BernoulliDistribution.png\", dpi=300, transparent=True)\n\n Notes:\n The Bernoulli distribution is defined as follows:\n\n $$\n f(x;p) = p^x (1-p)^{1-x}\n $$\n\n where $x \\in \\{0, 1\\}$ and $p \\in [0, 1]$.\n\n Args:\n *x (UniversalArray): The value(s) at which the function is evaluated.\n p (float): The probability of success.\n \"\"\"\n\n def probability_mass_function(self) -> UniversalArray:\n \"\"\"Probability mass function of the Bernoulli distribution.\"\"\"\n return self.p**self._x * (self.q) ** (1 - self._x)\n\n @property\n def __summary__(self) -> SummaryStatisticsAPI:\n \"\"\"Summary statistics of the Bernoulli distribution.\"\"\"\n\n def _mode() -> float | tuple[float, float]:\n \"\"\"Mode of the Bernoulli distribution.\"\"\"\n threshold = 0.5\n if self.p > threshold:\n return 1\n return 0 if self.p < threshold else (0, 1)\n\n return SummaryStatisticsAPI(\n mean=self.p,\n variance=self.p * self.q,\n mode=_mode(),\n doc=self.__doc__,\n )\n\n\nclass BinomialDistribution(DiscreteP):\n r\"\"\"Binomial distribution.\n\n The binomial distribution is a discrete distribution with two possible\n outcomes, 0 and 1. It is a generalization of the Bernoulli distribution\n where $n$ trials are conducted.\n\n Examples:\n >>> # PMF Example\n >>> import matplotlib.pyplot as plt\n >>> import numpy as np\n >>> from umf.functions.distributions.discrete_finite_support import (\n ... BinomialDistribution\n ... )\n >>> x = np.arange(0, 50, dtype=int)\n >>> y_05 = BinomialDistribution(x, p=0.5).__eval__\n >>> y_07 = BinomialDistribution(x,p=0.7).__eval__\n >>> y_09 = BinomialDistribution(x,p=0.9).__eval__\n >>> fig = plt.figure()\n >>> ax = plt.subplot()\n >>> _ = ax.plot(x, y_05, label=\"p=0.5\")\n >>> _ = ax.plot(x, y_07, label=\"p=0.7\")\n >>> _ = ax.plot(x, y_09, label=\"p=0.9\")\n >>> _ = ax.set_xlabel(\"x\")\n >>> _ = ax.set_ylabel(\"f(x)\")\n >>> _ = ax.legend()\n >>> plt.savefig(\"BinomialDistribution.png\", dpi=300, transparent=True)\n\n >>> # CDF Example\n >>> import matplotlib.pyplot as plt\n >>> import numpy as np\n >>> from umf.functions.distributions.discrete_finite_support import (\n ... BinomialDistribution\n ... )\n >>> x = np.arange(0, 50, dtype=int )\n >>> y_05 = BinomialDistribution(x, p=0.5, cumulative=True).__eval__\n >>> y_07 = BinomialDistribution(x, p=0.7, cumulative=True).__eval__\n >>> y_09 = BinomialDistribution(x, p=0.9, cumulative=True).__eval__\n >>> fig = plt.figure()\n >>> ax = plt.subplot()\n >>> _ = ax.plot(x, y_05, label=\"p=0.5\")\n >>> _ = ax.plot(x, y_07, label=\"p=0.7\")\n >>> _ = ax.plot(x, y_09, label=\"p=0.9\")\n >>> _ = ax.set_xlabel(\"x\")\n >>> _ = ax.set_ylabel(\"F(x)\")\n >>> _ = ax.legend()\n >>> plt.savefig(\"BinomialDistribution-cml.png\", dpi=300, transparent=True)\n\n Notes:\n The binomial distribution is defined as follows for probability mass function:\n\n $$\n f(x;n,p) = \\binom{n}{k} p^k (1-p)^{n-k}\n $$\n\n where $k \\in \\{0, 1, ..., n\\}$, $n \\in \\mathbb{N}$, and $p \\in [0, 1]$ and\n $\\binom{n}{k}$ is the binomial coefficient. $1 - p$ is also denoted as $q$.\n\n The binomial distribution is defined as follows for cumulative distribution\n function:\n\n $$\n F(x;n,p) = \\sum_{k=0}^x \\binom{n}{k} p^k (1-p)^{n-k}\n $$\n\n where $k \\in \\{0, 1, ..., n\\}$, $n \\in \\mathbb{N}$, and $p \\in [0, 1]$ and\n $\\binom{n}{k}$ is the binomial coefficient. $1 - p$ is also denoted as $q$.\n This expression is also known as the regularized incomplete beta function.\n\n $$\n F(x;n,p) = I_{1-p}(n-k, k+1)\n $$\n\n\n\n Args:\n *x (UniversalArray): The value(s) at which the function is evaluated.\n p (float): The probability of success.\n cumulative: If True, the cumulative distribution function is returned.\n Defaults to False.\n \"\"\"\n\n def __init__(self, *x: UniversalArray, p: float, cumulative: bool = False) -> None:\n \"\"\"Initialize the Binomial distribution.\"\"\"\n super().__init__(*x, p=p, cumulative=cumulative)\n self.n = np.full_like(self._x, self._x[-1])\n self.k = self._x\n\n def probability_mass_function(self) -> UniversalArray:\n \"\"\"Probability mass function of the Binomial distribution.\"\"\"\n return (\n combinations(self.n, self.k)\n * self.p**self.k\n * self.q ** (self.n - self.k)\n )\n\n def cumulative_distribution_function(self) -> UniversalArray:\n \"\"\"Cumulative distribution function of the Binomial distribution.\"\"\"\n return np.array(\n [\n np.sum(\n [\n combinations(self.n[i], k)\n * self.p**k\n * self.q ** (self.n[i] - k)\n for k in range(self.k[i] + 1)\n ],\n )\n for i in range(len(self._x))\n ],\n )\n\n @property\n def __summary__(self) -> SummaryStatisticsAPI:\n \"\"\"Summary statistics of the Binomial distribution.\"\"\"\n return SummaryStatisticsAPI(\n mean=self.n.max() * self.p,\n variance=self.n.max() * self.p * self.q,\n mode=math.ceil((self.n.max() + 1) * self.p) - 1,\n doc=self.__doc__,\n )\n","repo_name":"Anselmoo/useful-math-functions","sub_path":"umf/functions/distributions/discrete_finite_support.py","file_name":"discrete_finite_support.py","file_ext":"py","file_size_in_byte":7238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"38305899372","text":"def encrypt(text, key):\n try:\n a = int(key['a'])\n b = int(key['b'])\n encrypted = [] # Initialize an empty list to store encrypted characters.\n for char in text: # Loop through each character in the input text.\n if char.isalpha(): # Check if the character is a letter.\n base = ord('A') if char.isupper() else ord('a') # Set the base value based on whether the letter is uppercase or lowercase.\n # Encrypt the character using the affine cipher formula and append the result to the 'encrypted' list.\n encrypted.append(chr((a * (ord(char) - base) + b) % 26 + base))\n else:\n encrypted.append(char) # If the character is not a letter, append it to the 'encrypted' list as is.\n return ''.join(encrypted) # Join the characters in the 'encrypted' list into a string and return it as the output.\n except ValueError:\n return \"Error!\" # If the 'a' or 'b' key cannot be converted to an integer, return an error message.\n\n\ndef decrypt(text, key):\n try:\n a = int(key['a'])\n b = int(key['b'])\n decrypted = []\n x = [ i for i in range(26) if (a * i) % 26 == 1 ] or [0] # Calculate the modular inverse of 'a'.\n for char in text:\n if char.isalpha():\n base = ord('A') if char.isupper() else ord('a')\n # Decrypt the character using the affine cipher formula and append the result to the 'decrypted' list.\n decrypted.append(chr((x[0] * ((ord(char) - base) - b)) % 26 + base))\n else:\n decrypted.append(char)\n return ''.join(decrypted)\n except ValueError:\n return \"Error!\"","repo_name":"msrezaie/personal_portfolio","sub_path":"cryptoden/ciphers/affine.py","file_name":"affine.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"21539016215","text":"if __name__ == '__main__':\r\n #Nomor 4\r\n num = int(input('Enter the Nth Fibonacci number you wish to calculate or QUIT to quit: '))\r\n a = 0\r\n b = 1\r\n if num <= 0:\r\n print('The Output of your input is ' , a)\r\n else:\r\n print(a, b, end=\" \")\r\n for i in range(2 , num):\r\n c = a + b\r\n print(c, end=\" \")\r\n a = b\r\n b = c","repo_name":"fathurizkym/Pengumpulan-Tugas","sub_path":"Tugas-2/Soal 4.py","file_name":"Soal 4.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"40475225486","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom MyDR.LocalPCADR import LocalPCADR\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.decomposition import PCA\n\n\n# 程序循环运行的示例\n\n\ndef run_loop():\n \"\"\"\n 循环版的运行\n :return:\n \"\"\"\n path = \"E:\\\\ChinaGraph\\\\Data\\\\\"\n data_name = \"coilObjCenterBack10[2]\" # fashionCenter\n path = path + data_name + \"\\\\\"\n X0 = np.loadtxt(path + \"data.csv\", dtype=np.float, delimiter=\",\")\n label = np.loadtxt(path + \"label.csv\", dtype=np.int, delimiter=\",\")\n (n, m) = X0.shape\n\n # 如果是三维的,则画出三维散点图\n if m == 3:\n ax3d = Axes3D(plt.figure())\n ax3d.scatter(X0[:, 0], X0[:, 1], X0[:, 2], c=label)\n plt.title('original data')\n plt.show()\n\n if m > 64:\n print(\"原数据维度过高,现降维至 50 维\")\n pca = PCA(n_components=50)\n X = pca.fit_transform(X0)\n else:\n X = X0\n\n params = {}\n params['neighborhood_type'] = 'knn' # 'knn' or 'rnn' or 'iter'\n params['n_neighbors'] = 10 # Only used when neighborhood_type is 'knn'\n params['neighborhood_size'] = 0.2 # Only used when neighborhood_type is 'rnn'\n params['alpha'] = 0.9 # the weight of euclidean distance\n params['beta'] = 1.0 - params['alpha'] # the weight of local PCA\n params['distance_type'] = 'spectralNorm' # 'spectralNorm' or 'mahalanobis'\n params['manifold_dimension'] = 2 # the real dimension of manifolds\n params['perplexity'] = 30.0708 # perplexity in t-SNE\n params['MAX_Distance_iter'] = 10 # max iter of distance computing\n params['use_skeleton'] = False # boolean value. Whether use skeleton method.\n params['save_path'] = None # path\n\n affinity = 'Q' # affinity 的取值可以为 'cov' 'expCov' 'Q' 'expQ' 'MDS' 't-SNE' 'PCA' 'Isomap' 'LLE'\n # 'geo-t-SNE' 'cTSNE\n frame_work = 't-SNE+' # frame 的取值可以为 'MDS' 't-SNE' 't-SNE+'\n import time\n\n # 需要循环的参数\n n_neighbors_list = [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 30]\n alpha_list = [0.1, 0.2, 0.3, 0.15, 0.25, 0.35]\n dimension_list = [2, 3, 1, 4, 5, 6, 7, 8]\n\n loop_count = 0\n for manifold_dimension in dimension_list:\n for n_neighbors in n_neighbors_list:\n for alpha in alpha_list:\n plt.figure(figsize=(20, 20)) # 指定输出文件大小\n loop_count += 1\n print(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n print(loop_count)\n params['manifold_dimension'] = manifold_dimension\n params['n_neighbors'] = n_neighbors\n params['alpha'] = alpha\n params['beta'] = 1.0 - alpha\n\n start = time.time()\n dr = LocalPCADR(n_components=2, affinity=affinity, parameters=params, frame=frame_work)\n\n Y = dr.fit_transform(X)\n finish = time.time()\n print(\"总共用时:\", finish - start)\n run_str = '' # 用于存放结果的文件名\n\n # 经典降维方法的文件路径\n classic_methods = ['PCA', 'MDS', 't-SNE', 'Isomap', 'LLE', 'geo-t-SNE']\n if affinity in classic_methods:\n title_str = affinity\n if affinity == 't-SNE':\n title_str = title_str + \" perplexity=\" + str(params['perplexity'])\n elif affinity == 'Isomap' or affinity == 'LLE':\n title_str = title_str + ' n_neighbors=' + str(params['n_neighbors'])\n elif affinity == 'geo-t-SNE':\n title_str = title_str + 'n_neighbors=' + str(params['n_neighbors']) + ' perplexity=' + str(\n params['perplexity'])\n run_str = title_str\n else:\n # 我们的降维方法的文件路径\n plt.scatter(Y[:, 0], Y[:, 1], c=label)\n ax = plt.gca()\n ax.set_aspect(1)\n title_str = 'Frame[' + frame_work + '] ' + affinity + ' alpha=' + str(params['alpha']) + ' beta=' + str(\n params['beta']) + ' manifold_dimension=' + str(params['manifold_dimension'])\n if params['use_skeleton']:\n title_str = 'skeletonMethod ' + title_str\n if params['neighborhood_type'] == 'knn':\n title_str = title_str + ' k=' + str(params['n_neighbors'])\n elif params['neighborhood_type'] == 'rnn':\n title_str = title_str + ' r=' + str(params['neighborhood_size'])\n if frame_work == 't-SNE' or frame_work == 't-SNE+':\n title_str = title_str + \" perplexity=\" + str(params['perplexity'])\n if params['neighborhood_type'] == 'iter':\n title_str = title_str + ' distanceIter=' + str(params['MAX_Distance_iter'])\n plt.title(title_str)\n run_str = title_str\n np.savetxt(path + run_str + \".csv\", Y, fmt='%.18e', delimiter=\",\")\n plt.savefig(path + run_str + \".png\")\n plt.close()\n\n\nif __name__ == '__main__':\n run_loop()\n","repo_name":"sdubrz/ChinaGraph","sub_path":"Run/loop_run0711.py","file_name":"loop_run0711.py","file_ext":"py","file_size_in_byte":5353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"14125491883","text":"import json, os, sys\nimport pickle\nfrom pprint import pprint\n\ndef analysis(dataset, output = None):\n '''分析数据集\n '''\n with open(dataset, 'r') as datafile:\n data = json.load(datafile)\n fout = open(output, 'w')\n video_cnt = 0\n labeled_video_cnt = 0\n segment_cnt = 0\n resolution_statistics = {}\n length_sum = 0.0\n labeled_length = 0.0\n dataset_version = data['version']\n for one in data['database'].items():\n item = one[1]\n video_cnt += 1\n if len(item['annotations']) > 0:\n labeled_video_cnt += 1\n segment_cnt += len(item['annotations'])\n for _ in item['annotations']:\n labeled_length += _['segment'][1] - _['segment'][0]\n if resolution_statistics.get(item['resolution']) is None:\n resolution_statistics[item['resolution']] = 1\n else:\n resolution_statistics[item['resolution']] += 1\n length_sum += item['duration']\n fout.write('DATASET : ' + dataset_version + '\\n')\n fout.write('all ' + str(video_cnt) + ' videos, ' + str(labeled_video_cnt) + ' Videos labeled\\n')\n fout.write(str(segment_cnt) + ' labeled segments\\n')\n fout.write(str(int(length_sum / 3600)) + ' hours ')\n fout.write(str(int(labeled_length / 3600)) + ' hours are labeled\\n')\n for res, number in resolution_statistics.items():\n fout.write(res + ' : ' + str(number) + '\\n')\n fout.close()\n\n\nif __name__ == '__main__':\n analysis('activity_net.v1-3.min.json', 'output.txt')\n","repo_name":"tsstss123/ActivityNet2017","sub_path":"analysis_dataset.py","file_name":"analysis_dataset.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"20677702516","text":"import sys\n\nimport autograd.numpy as np\nfrom autograd import grad\nfrom pubsub import pub\n\n\ndef DefaultOutput(step, progress, mag, nuggets, scales):\n sys.stdout.write(\n \"\\rProcessing %i iteration, progress = %.1f%% gradient magnitude = %2.6f, nuggets = %2.3f, scales = %s \" %\n (step,\n progress,\n mag,\n nuggets,\n np.array2string(\n scales,\n formatter={\n \"float_kind\": lambda x: \"%02.3f\" %\n x}),\n ))\n if progress == 100:\n sys.stdout.write(\"\\n\")\n sys.stdout.flush()\n\n\ndef NewLine():\n pass\n # print('')\n\n\ndef UseDefaultOutput():\n pub.subscribe(DefaultOutput, \"GradientProgress\")\n pub.subscribe(NewLine, \"GradientEnd\")\n\n\ndef GetOptimizer(name, *args, **kwargs):\n if name == \"GradientDescent\":\n return GradientDescentForEmulator(*args, **kwargs)\n elif name == \"MomentumDescent\":\n return MomentumDescentForEmulator(*args, **kwargs)\n elif name == \"RMSProp\":\n return RMSPropForEmulator(*args, **kwargs)\n elif name == \"Adam\":\n return AdamForEmulator(*args, **kwargs)\n\n\nclass GradientDescentForEmulator:\n class ProgressCalculator:\n def __init__(self):\n self.startMag = None\n self.tolMag = None\n self.magSlope = None\n self.lastProgress = None\n self.scale_max = 5000 # larger than this number and covariant matrix will not pos define due to numerical errors\n\n def Get(self, nsteps, step, mag, tolerance):\n stepProgress = step / nsteps * 100\n if self.startMag is None:\n # progress is calculated with log scale, with progress = 0 at\n # first step and 1 when mag = tolerance\n self.startMag = np.log(mag)\n self.totMag = np.log(tolerance)\n self.magSlope = self.totMag - self.startMag\n self.lastProgress = 0\n magProgress = (np.log(mag) - self.startMag) * 100 / self.magSlope\n progress = magProgress if magProgress > stepProgress else stepProgress\n # progress could only move forward\n # prevent it from going back\n if progress > self.lastProgress:\n self.lastProgress = progress\n else:\n progress = self.lastProgress\n return progress if progress < 100 else 100\n\n def __init__(self, step_size_scales, step_size_nuggets):\n self.step_scales_size = step_size_scales\n self.step_nuggets_size = step_size_nuggets\n self.func = None\n self.grad_scales_exp = None\n self.grad_nuggets_exp = None\n self.nuggets_log = None\n self.scales_log = None\n self.scaleMax = 1000\n\n def SetFunc(self, func):\n self.func = func\n\n def exp_cal(t_para_log):\n return func(np.exp(t_para_log))\n\n self.grad_exp = grad(exp_cal)\n\n def StepDescent(self, para):\n self.para_log = np.log(para)\n gradient = self.grad_exp(self.para_log)\n\n para = self.para_log + gradient * self.step_size\n\n return np.exp(para), gradient\n\n def Descent(\n self,\n scales,\n nuggets,\n nsteps=10,\n tolerance=1e-5,\n progress=DefaultOutput):\n history_para = []\n scales = np.atleast_1d(scales)\n nuggets = np.atleast_1d(nuggets)\n para = np.concatenate([nuggets, scales])\n self.step_size = np.full((1,), self.step_nuggets_size)\n self.step_size = np.concatenate(\n [self.step_size, np.full(scales.shape, self.step_scales_size)]\n )\n\n pCalculator = GradientDescentForEmulator.ProgressCalculator()\n progress = 0\n for i in range(nsteps):\n new_para, grad = self.StepDescent(para)\n\n # stop updating parameters that reaches max values\n idCap = new_para > self.scaleMax\n new_para[idCap] = self.scaleMax\n grad[idCap] = 0\n\n para = new_para\n history_para.append(new_para)\n (scales, nuggets) = new_para[1:], new_para[0]\n\n mag = np.linalg.norm(grad * self.step_size)\n\n progress = pCalculator.Get(nsteps, i, mag, tolerance)\n pub.sendMessage(\n \"GradientProgress\",\n step=i,\n progress=progress,\n mag=mag,\n nuggets=nuggets,\n scales=scales,\n )\n # or mag < 0.5*(self.step_scales_size + self.step_nuggets_size):\n if (mag < tolerance):\n break\n if progress < 100:\n pub.sendMessage(\n \"GradientProgress\",\n step=i,\n progress=100,\n mag=mag,\n nuggets=nuggets,\n scales=scales,\n )\n pub.sendMessage(\"GradientEnd\")\n return np.array(history_para)\n\n\nclass MomentumDescentForEmulator(GradientDescentForEmulator):\n def __init__(self, step_size_scales, step_size_nuggets, momentum=0.95):\n GradientDescentForEmulator.__init__(\n self, step_size_scales, step_size_nuggets)\n self.momentum = momentum\n self.momentum_vector = None\n\n def StepDescent(self, para):\n self.para_log = np.log(para)\n if self.momentum_vector is None:\n self.momentum_vector = np.zeros_like(self.para_log)\n\n gradient = self.grad_exp(self.para_log)\n\n self.momentum_vector = (\n self.momentum * self.momentum_vector - self.step_size * gradient\n )\n\n para_temp = self.para_log - self.momentum_vector\n return np.exp(para_temp), gradient\n\n\nclass RMSPropForEmulator(GradientDescentForEmulator):\n def __init__(self, step_size_scales, step_size_nuggets, momentum=0.9):\n GradientDescentForEmulator.__init__(\n self, step_size_scales, step_size_nuggets)\n self.momentum = momentum\n self.momentum_vector = None\n\n def StepDescent(self, para):\n self.para_log = np.log(para)\n gradient = self.grad_exp(self.para_log)\n if self.momentum_vector is None:\n self.momentum_vector = np.zeros_like(self.para_log)\n\n self.momentum_vector = (\n self.momentum * self.momentum_vector\n + (1 - self.momentum) * gradient * gradient\n )\n\n para_temp = self.para_log + self.step_size * gradient / np.sqrt(\n self.momentum_vector + 1e-10\n )\n\n return np.exp(para_temp), gradient\n\n\nclass AdamForEmulator(GradientDescentForEmulator):\n def __init__(\n self,\n step_size_scales,\n step_size_nuggets,\n beta1=0.9,\n beta2=0.99):\n GradientDescentForEmulator.__init__(\n self, step_size_scales, step_size_nuggets)\n self.beta1 = beta1\n self.beta2 = beta2\n self.m_para = None\n self.s_para = None\n self.iteration = 1\n\n def StepDescent(self, parameters):\n self.para_log = np.log(parameters)\n gradient = self.grad_exp(self.para_log)\n if self.m_para is None:\n self.m_para = np.zeros_like(self.para_log)\n self.s_para = np.zeros_like(self.para_log)\n\n self.m_para = self.beta1 * self.m_para - (1 - self.beta1) * gradient\n self.s_para = self.beta2 * self.s_para + \\\n (1 - self.beta2) * gradient * gradient\n\n para_temp = self.para_log - self.step_size * self.m_para / np.sqrt(\n self.s_para + 1e-10\n )\n return np.exp(para_temp), gradient\n","repo_name":"ssedd1123/Bayesian-package","sub_path":"Utilities/GradientDescent.py","file_name":"GradientDescent.py","file_ext":"py","file_size_in_byte":7603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"14758685605","text":"from os.path import join\nfrom unittest import TestCase\n\nfrom db.pscale_strategy import PScaleStrategy\nfrom settings import Settings\nfrom utils.case import CaseDetails, SearchItem\nfrom utils.utils import read_json_from_file\n\n\nclass TestPScaleStrategy(TestCase):\n\n def test_save_case(self):\n example_case = CaseDetails(SearchItem(read_json_from_file(join(\n Settings.APP_HOME_DIRECTORY.value, 'db/example_data/49K01-2201-EV-ABCDEF.json'\n ))))\n PScaleStrategy().save_case(example_case)\n blob = PScaleStrategy().get_case_by_ucn('49K01-2201-EV-ABCDEF')\n self.assertIsNotNone(blob)\n\n def test_update_case(self):\n example_case = CaseDetails(SearchItem(read_json_from_file(join(\n Settings.APP_HOME_DIRECTORY.value, 'db/example_data/49K01-2201-EV-ABCDEF.updated.json'\n ))))\n PScaleStrategy().update_case(example_case)\n blob = PScaleStrategy().get_case_by_ucn('49K01-2201-EV-ABCDEF')\n self.assertIsNotNone(blob)\n\n def test_get_case(self):\n cd = CaseDetails(\n SearchItem(\n PScaleStrategy().get_case_by_ucn('49K01-2201-EV-ABCDEF').pop()\n )\n )\n self.assertIsNotNone(cd)\n","repo_name":"indy-tenants/mycase-scraper","sub_path":"mycase_scraper/db/pscale_strategy_test.py","file_name":"pscale_strategy_test.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"8111415851","text":"N = (int)(input())\r\nmod = 10**10\r\nprod = 0\r\nfor i in range(1,N+1):\r\n\ttemp = i\r\n\tfor j in range(1,i):\r\n\t\ttemp *=i\r\n\t\ttemp %= mod\r\n\tprod += temp\r\n\tprod %= mod\r\nprint(prod)\r\n\r\n\r\n\r\n\r\n","repo_name":"raokartikkumar24/CodingCompetition","sub_path":"Hackerrank/pe_self_power2.py","file_name":"pe_self_power2.py","file_ext":"py","file_size_in_byte":179,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"73798949535","text":"import torch\nfrom torch.distributions import Distribution, Uniform\nfrom torch.distributions.transforms import SigmoidTransform, AffineTransform\nfrom torch.distributions import TransformedDistribution\n\nclass Logistic(TransformedDistribution):\n def __init__(self, loc, scale, validate_args=None):\n self.loc = loc\n self.scale = scale\n base_distribution = Uniform(torch.Tensor([0]).to(loc.device), torch.Tensor([1]).to(loc.device))\n transforms = [SigmoidTransform().inv, AffineTransform(loc=loc, scale=scale)]\n super().__init__(base_distribution, transforms, validate_args=validate_args)\n\ndef truncated_logistic_cdf(g, loc, scale, alpha, g0, gk):\n t1 = torch.sigmoid((g - loc)/scale)\n t2 = torch.sigmoid((g0 - alpha/2 - loc) / scale)\n t3 = torch.sigmoid((gk + alpha/2 - loc) / scale)\n return (t1 - t2) / (t3 - t2)\n\nclass DLogistic(Distribution):\n def __init__(self, loc, scale, alpha, g0, gk, validate_args=None):\n self.loc = loc\n self.scale = scale\n self.alpha = alpha\n self.g0 = g0\n self.gk = gk\n super().__init__(batch_shape=loc.size(0), event_shape=loc.size(1), validate_args=validate_args)\n\n def log_prob(self, x):\n return torch.log(self.pmf(x))\n\n def pmf(self, x):\n left = truncated_logistic_cdf(x - self.alpha/2, self.loc.unsqueeze(-1), self.scale.unsqueeze(-1), self.alpha, self.g0, self.gk)\n right = truncated_logistic_cdf(x + self.alpha/2, self.loc.unsqueeze(-1), self.scale.unsqueeze(-1), self.alpha, self.g0, self.gk)\n return right - left\n\n\nif __name__ == \"__main__\":\n loc = torch.Tensor([[1.5]])\n scale = torch.Tensor([[1]])\n alpha = 1\n g0 = -10\n gk = 10\n d = DLogistic(loc, scale, alpha, g0, gk)\n x = torch.arange(g0, gk + 1).view(1, -1)\n print(d.pmf(x), torch.sum(d.pmf(x)))\n","repo_name":"eelcovdw/pytorch-PWL","sub_path":"pwl/logistic.py","file_name":"logistic.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"32688902302","text":"\nwhile True:\n \n\n amount = int(input(\"Enter the Bill Amount: \"))\n\n\n\n\n\n if amount >=500:\n discount =0\n discount = amount * 0.25\n final_price = amount - discount\n print(\"You are totall Bill is\", final_price)\n print()\n print(\"Thank you\")\n\n else:\n print(\"Sorry you wont get the 25% discount, to get this please make bill of 500rs or greater\")\n","repo_name":"PavanjDot/pythonbible","sub_path":"discount.py","file_name":"discount.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"1331203694","text":"import pickle\nimport sklearn\nimport sklearn.ensemble\nimport sklearn.neural_network as nn\nimport pandas as pd\nimport numpy as np\n\n# how many files to test on\nTEST_SIZE = 1\n# how many files to train on\nTRAIN_SIZE = 1\n# how many files to train on at a time\nBATCH_SIZE = 1\n\n#shuffled_files = np.random.permutation(np.arange(1, 675))\ntrain_files = 1+np.arange(TEST_SIZE,TEST_SIZE+TRAIN_SIZE)#shuffled_files[:TRAIN_SIZE]\ntest_files = 1+np.arange(TEST_SIZE)#shuffled_files[TRAIN_SIZE:TRAIN_SIZE+TEST_SIZE]\n\n# the features you want to use for training\nfeatures = [\n # \"vid\",\n # \"ps\",\n # \"wkday\",\n \"start_time\",\n # \"euc_dist\",\n \"real_dist\",\n # \"humidity\",\n # \"windspeed\",\n # \"vis\",\n # \"temp\",\n # \"haze\",\n # \"fog\",\n # \"rain\",\n # \"snow\",\n # \"hday\",\n]\n# for i in range(2,4+1):\n# features.append('wkday^{}'.format(i))\n# for i in range(2,6+1):\n# features.append('hour^{}'.format(i))\nfor i in range(6):\n for j in range(6):\n features.append(\"bor{}to{}\".format(i,j))\n# for i in range(14):\n# features.append('weatherType_{}'.format(i))\n\n\ndef reportErr(err,attention=''):\n print(\"RMSE(L2): {}\".format( np.linalg.norm(err)/np.sqrt(len(err)) ))\n print(attention+\"L1 Error: {}\".format( np.mean(np.abs(err)) ))\n print(\"Median Error: {}\".format( np.median(np.abs(err)) ))\n\n\n\ntest_dfs = []\nprint(\"Loading Test Data\")\nfor idx in test_files:\n df = pickle.load(open(\"PreProcessedData_eagle/df_{}.pkl\".format(idx), \"rb\"))\n print(\"Loaded df_{}\".format(idx))\n test_dfs.append(df)\ntest_df = pd.concat(test_dfs)\ntest_df = test_df[test_df['travel_time'] >= 60]\ntest_df = test_df[test_df['travel_time'] <= 3600*4]\ntest_X = test_df[features]\ntest_y = test_df[\"travel_time\"]\nprint('travel_time - max, min, mean:',np.max(test_y),np.min(test_y),np.mean(test_y))\n\n\n\n\nfor feat in features:\n corr = np.corrcoef(test_X[feat], test_y)[0,1]\n print(\"{}: {}\".format(feat, corr))\n\n\nprint(\"\\n\\n\\n\\n\\n\\n\\ntraining\")\n\nMLP_list = []\nmlp = sklearn.neural_network.MLPRegressor(hidden_layer_sizes=(10,3),verbose=True,max_iter=20,learning_rate_init=0.1,warm_start=True,early_stopping=True,tol=0.00010)\n\nfor idx in range(TRAIN_SIZE // BATCH_SIZE):\n slice = train_files[BATCH_SIZE * idx:BATCH_SIZE * (idx + 1)]\n train_dfs = []\n for i in slice:\n train_dfs.append(pickle.load(open(\"PreProcessedData_eagle/df_{}.pkl\".format(i), \"rb\")))\n df = pd.concat(train_dfs)\n df = df[df['travel_time'] >= 60]\n df = df[df['travel_time'] <= 3600 * 0.5]\n print(\"Loaded Batch-{}\".format(idx))\n X = df[features]\n y = df[\"travel_time\"]\n\n mlp.fit(X, y)\n #MLP_list.append(mlp)\n\n if idx % 1 == 0:\n print(\"Training Error\")\n reportErr(mlp.predict(X)-y)\n\n #preds = [MLP.predict(test_X) for MLP in MLP_list]\n #preds = np.mean(preds, axis=0)\n print(\"Testing Error\")\n reportErr(mlp.predict(test_X)-test_y,'****************')\n\n print(\"Naive Testing:\")\n reportErr(np.mean(y)-test_y)\n\n#pickle.dump(MLP_list, open(\"Models/LinearRegression.pkl\", \"wb\"))\n","repo_name":"eaglez1111/PredictingTaxiTravelTime","sub_path":"mlp_sk.py","file_name":"mlp_sk.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"22456013011","text":"#coding=utf-8\nimport pygame\nimport time\nfrom pygame.locals import *\nimport random\n\nclass BasePlane(object):\n def __init__(self, screen_temp, x, y, image_name):\n self.x = x\n self.y = y\n self.screen = screen_temp\n self.image = pygame.image.load(image_name)\n self.bullet_list = []\n\n def display(self):\n self.screen.blit(self.image, (self.x, self.y))\n for bullet in self.bullet_list:\n bullet.display()\n bullet.move()\n if bullet.judge():\n self.bullet_list.remove(bullet)\n\n\nclass HeroPlane(BasePlane):\n def __init__(self, screen_temp):\n BasePlane.__init__(self, screen_temp, 210, 500, \"./resources/hero1.png\")\n \n def move_left(self):\n self.x -= 5\n\n def move_right(self):\n self.x += 5\n\n def fire(self):\n self.bullet_list.append(Bullet(self.screen, self.x, self.y))\n\n\nclass EnemyPlane(BasePlane):\n def __init__(self, screen_temp):\n BasePlane.__init__(self, screen_temp, 0, 0, \"./resources/enemy0.png\")\n self.sign = 0\n\n\n\n def move(self):\n if self.sign == 0:\n self.x += 5\n elif self.sign == 1:\n self.x -= 5\n\n if self.x > 320:\n self.sign = 1\n elif self.x < 0:\n self.sign = 0\n\n # def move_left(self):\n # self.x -= 5\n\n # def move_right(self):\n # self.x += 5\n\n def fire(self):\n random_num = random.randint(1, 100)\n if random_num == 30 or random_num == 50:\n self.bullet_list.append(EnemyBullet(self.screen, self.x, self.y))\n\nclass BaseBullet(object):\n def __init__(self, screen_temp, x, y, image_name):\n self.x = x\n self.y = y\n self.screen = screen_temp\n self.image = pygame.image.load(image_name)\n\n def display(self):\n self.screen.blit(self.image, (self.x, self.y))\n\n\nclass Bullet(BaseBullet):\n def __init__(self, screen_temp, x, y):\n BaseBullet.__init__(self, screen_temp, x+40, y-20, \"./resources/bullet.png\")\n\n def move(self):\n self.y -= 8\n\n def judge(self):\n if self.y < 0:\n return True\n else:\n return False\n\n\nclass EnemyBullet(BaseBullet):\n def __init__(self, screen_temp, x, y):\n BaseBullet.__init__(self, screen_temp, x+25, y+40, \"./resources/bullet1.png\")\n\n def move(self):\n self.y += 5\n\n def judge(self):\n if self.y > 852:\n return True\n else:\n return False\n\ndef key_control(hero):\n for event in pygame.event.get():\n if event.type == QUIT:\n print(\"exit\")\n exit()\n elif event.type == KEYDOWN:\n if event.key == K_a or event.key == K_LEFT:\n print('left')\n hero.move_left()\n\n elif event.key == K_d or event.key == K_RIGHT:\n print('right')\n hero.move_right()\n\n elif event.key == K_SPACE:\n print('space')\n hero.fire()\n\ndef main():\n screen = pygame.display.set_mode((380, 652), 0, 32)\n\n background = pygame.image.load(\"./resources/background.png\")\n\n hero = HeroPlane(screen)\n enemy = EnemyPlane(screen)\n while True:\n screen.blit(background, (0,0))\n hero.display()\n enemy.display()\n enemy.move()\n enemy.fire()\n pygame.display.update()\n key_control(hero)\n time.sleep(0.02)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"qjb1991/plane","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"37093941312","text":"import numpy as np\nimport pytest\n\nfrom pyrender import (DirectionalLight, SpotLight, PointLight, Texture,\n PerspectiveCamera, OrthographicCamera)\nfrom pyrender.constants import SHADOW_TEX_SZ\n\n\ndef test_directional_light():\n\n d = DirectionalLight()\n assert d.name is None\n assert np.all(d.color == 1.0)\n assert d.intensity == 1.0\n\n d.name = 'direc'\n with pytest.raises(ValueError):\n d.color = None\n with pytest.raises(TypeError):\n d.intensity = None\n\n d = DirectionalLight(color=[0.0, 0.0, 0.0])\n assert np.all(d.color == 0.0)\n\n d._generate_shadow_texture()\n st = d.shadow_texture\n assert isinstance(st, Texture)\n assert st.width == st.height == SHADOW_TEX_SZ\n\n sc = d._get_shadow_camera(scene_scale=5.0)\n assert isinstance(sc, OrthographicCamera)\n assert sc.xmag == sc.ymag == 5.0\n assert sc.znear == 0.01 * 5.0\n assert sc.zfar == 10 * 5.0\n\n\ndef test_spot_light():\n\n s = SpotLight()\n assert s.name is None\n assert np.all(s.color == 1.0)\n assert s.intensity == 1.0\n assert s.innerConeAngle == 0.0\n assert s.outerConeAngle == np.pi / 4.0\n assert s.range is None\n\n with pytest.raises(ValueError):\n s.range = -1.0\n\n with pytest.raises(ValueError):\n s.range = 0.0\n\n with pytest.raises(ValueError):\n s.innerConeAngle = -1.0\n\n with pytest.raises(ValueError):\n s.innerConeAngle = np.pi / 3.0\n\n with pytest.raises(ValueError):\n s.outerConeAngle = -1.0\n\n with pytest.raises(ValueError):\n s.outerConeAngle = np.pi\n\n s.range = 5.0\n s.outerConeAngle = np.pi / 2 - 0.05\n s.innerConeAngle = np.pi / 3\n s.innerConeAngle = 0.0\n s.outerConeAngle = np.pi / 4.0\n\n s._generate_shadow_texture()\n st = s.shadow_texture\n assert isinstance(st, Texture)\n assert st.width == st.height == SHADOW_TEX_SZ\n\n sc = s._get_shadow_camera(scene_scale=5.0)\n assert isinstance(sc, PerspectiveCamera)\n assert sc.znear == 0.01 * 5.0\n assert sc.zfar == 10 * 5.0\n assert sc.aspectRatio == 1.0\n assert np.allclose(sc.yfov, np.pi / 16.0 * 9.0) # Plus pi / 16\n\n\ndef test_point_light():\n\n s = PointLight()\n assert s.name is None\n assert np.all(s.color == 1.0)\n assert s.intensity == 1.0\n assert s.range is None\n\n with pytest.raises(ValueError):\n s.range = -1.0\n\n with pytest.raises(ValueError):\n s.range = 0.0\n\n s.range = 5.0\n\n with pytest.raises(NotImplementedError):\n s._generate_shadow_texture()\n\n with pytest.raises(NotImplementedError):\n s._get_shadow_camera(scene_scale=5.0)\n","repo_name":"mmatl/pyrender","sub_path":"tests/unit/test_lights.py","file_name":"test_lights.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","stars":1149,"dataset":"github-code","pt":"33"} +{"seq_id":"24971233041","text":"'''\n Fichier : Noeud\n Projet : TP1\n Cours : IFT2015 - Stuctures de données\n Auteurs : Olivier Provost (20101738)\n Moïka Sauvé (20090119)\n'''\n\nimport math\n\nclass Noeud:\n def __init__(self, xmin, xmax, ymin, ymax, parent=None):\n self.x_min = xmin\n self.x_max = xmax\n self.y_min = ymin\n self.y_max = ymax\n self.NO = None\n self.NE = None\n self.SE = None\n self.SO = None\n self.parent = parent\n self.x_centre = (xmin + xmax) / 2\n self.y_centre = (ymin + ymax) / 2\n self.frontieres = {\"NO\" : None, \"NE\" : None, \"SE\" : None, \"SO\" : None}\n\n\n def __str__(self):\n return str('<' + ('0 ' if(self.NO is None) else '1 ') +\n ('0 ' if(self.NE is None) else '1 ') +\n ('0 ' if(self.SE is None) else '1 ') +\n ('0' if(self.SO is None) else '1') + '>')\n\n\n def enfants(self):\n return [ self.NO, self.NE, self.SE, self.SO ]\n\n\n def creer_frontieres(self):\n # Si la frontière est plus grande que 1 on peut la diviser.\n if((self.x_max - self.x_min > 1) or (self.y_max - self.y_min > 1)):\n # Si la frontière n'est pas divisible par 2, on prend le plafond de la moitié de celle-ci.\n if not isinstance(self.x_centre, int) or not isinstance(self.y_centre, int):\n self.x_centre = math.ceil(self.x_centre)\n self.y_centre = math.ceil(self.y_centre)\n\n\n self.frontieres[\"NO\"] = Noeud(self.x_min, self.x_centre, self.y_min, self.y_centre, self)\n self.frontieres[\"NE\"] = Noeud(self.x_centre, self.x_max, self.y_min, self.y_centre, self)\n self.frontieres[\"SE\"] = Noeud(self.x_centre, self.x_max, self.y_centre, self.y_max, self)\n self.frontieres[\"SO\"] = Noeud(self.x_min, self.x_centre, self.y_centre, self.y_max, self)\n\n\n def dans_frontieres(self, bateau):\n if((bateau.x <= self.x_max and bateau.x >= self.x_min) and (bateau.y <= self.y_max and bateau.y >= self.y_min)):\n return True\n else:\n return False\n\n\n def enfants_nuls(self):\n if(self.NO is None and self.NE is None and self.SE is None and self.SO is None):\n return True\n else:\n return False","repo_name":"prooli22/TP1","sub_path":"Noeud.py","file_name":"Noeud.py","file_ext":"py","file_size_in_byte":2303,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"40752833491","text":"\"\"\"\nToolbar for running main actions like validate and build.\n\"\"\"\n\nimport logging\n\nimport maya.cmds as cmds\n\nfrom ..vendor.Qt import QtGui, QtWidgets\nfrom ..core import BlueprintSettings\nfrom . import utils\nfrom .core import BlueprintUIModel\nfrom .main_settings import MainSettingsWindow\nfrom .action_editor import ActionEditorWindow\nfrom .designtoolkit import DesignToolkitWindow\n\nfrom .gen.main_toolbar import Ui_MainToolbar\n\nLOG = logging.getLogger(__name__)\n\n\nclass MainToolbar(QtWidgets.QWidget):\n def __init__(self, parent=None):\n super(MainToolbar, self).__init__(parent=parent)\n\n # used to cause a latent refresh after builds\n self._isStateDirty = False\n\n self.blueprint_model = BlueprintUIModel.get_default_model()\n\n self.ui = Ui_MainToolbar()\n self.ui.setupUi(self)\n utils.set_custom_context_menu(self.ui.build_btn, self._show_build_context_menu)\n\n self._clean_state()\n self._update_mode()\n self._update_rig_name()\n\n # connect signals\n self.blueprint_model.change_scene_finished.connect(self._on_change_scene_finished)\n self.blueprint_model.file_changed.connect(self._on_file_changed)\n self.blueprint_model.is_file_modified_changed.connect(self._on_file_modified_changed)\n self.blueprint_model.rig_exists_changed.connect(self._on_rig_exists_changed)\n self.blueprint_model.read_only_changed.connect(self._on_read_only_changed)\n self.blueprint_model.setting_changed.connect(self._on_setting_changed)\n\n self.ui.new_blueprint_btn.clicked.connect(self.blueprint_model.new_file)\n self.ui.validate_btn.clicked.connect(self.blueprint_model.run_validation)\n self.ui.build_btn.clicked.connect(self.blueprint_model.run_build)\n self.ui.interactive_next_btn.clicked.connect(self.blueprint_model.interactive_build_next_action)\n self.ui.interactive_next_step_btn.clicked.connect(self.blueprint_model.interactive_build_next_step)\n self.ui.interactive_continue_btn.clicked.connect(self.blueprint_model.continue_interactive_build)\n self.ui.open_blueprint_btn.clicked.connect(self.blueprint_model.open_blueprint_scene)\n\n self.ui.settings_btn.clicked.connect(MainSettingsWindow.toggleWindow)\n self.ui.design_toolkit_btn.clicked.connect(DesignToolkitWindow.toggleWindow)\n self.ui.action_editor_btn.clicked.connect(ActionEditorWindow.toggleWindow)\n\n def _show_build_context_menu(self, position):\n menu = QtWidgets.QMenu()\n interactive_action = menu.addAction(\"Interactive Build\")\n interactive_action.setStatusTip(\"Start an interactive build that can be stepped through incrementally.\")\n interactive_action.triggered.connect(self.blueprint_model.run_interactive_build)\n interactive_action.setEnabled(self.blueprint_model.can_interactive_build())\n menu.exec_(self.ui.build_btn.mapToGlobal(position))\n\n def mousePressEvent(self, event: QtGui.QMouseEvent):\n super(MainToolbar, self).mousePressEvent(event)\n\n def does_rig_exist(self):\n return self.blueprint_model.does_rig_exist\n\n def showEvent(self, event):\n super(MainToolbar, self).showEvent(event)\n self._on_state_dirty()\n\n def _on_change_scene_finished(self):\n self._update_mode()\n self._update_rig_name()\n\n def _on_file_changed(self):\n self._update_mode()\n self._update_rig_name()\n\n def _on_file_modified_changed(self, is_modified):\n self._update_rig_name()\n\n def _on_setting_changed(self, key: str, value: object):\n if key == BlueprintSettings.RIG_NAME:\n self._update_rig_name()\n\n def _update_rig_name(self):\n # prevent updating rig and file name while changing scenes\n if self.blueprint_model.is_changing_scenes:\n return\n\n file_name = self.blueprint_model.get_blueprint_file_name()\n if file_name is None:\n file_name = \"untitled\"\n if self.blueprint_model.is_file_modified():\n file_name += \"*\"\n\n self.ui.rig_name_label.setText(self.blueprint_model.get_setting(BlueprintSettings.RIG_NAME))\n self.ui.blueprint_file_name_label.setText(file_name)\n self.ui.blueprint_file_name_label.setToolTip(self.blueprint_model.get_blueprint_file_path())\n\n def _on_rig_exists_changed(self):\n self._clean_state()\n self._update_mode()\n\n def _on_read_only_changed(self, is_read_only):\n # TODO: represent read-only state somewhere\n pass\n\n def _clean_state(self):\n self._isStateDirty = False\n self.setEnabled(True) # TODO: True if isBuilding\n\n def _on_state_dirty(self):\n if not self._isStateDirty:\n self._isStateDirty = True\n self.setEnabled(False)\n cmds.evalDeferred(self._clean_state)\n\n def _update_mode(self):\n \"\"\"\n Update the mode header and visible page, blueprint or rig.\n \"\"\"\n # prevent mode changes while changing scenes to avoid flickering\n # since a file may be briefly closed before a new one is opened\n if self.blueprint_model.is_changing_scenes:\n return\n\n if self.blueprint_model.is_file_open():\n self.ui.main_stack.setCurrentWidget(self.ui.opened_page)\n else:\n self.ui.main_stack.setCurrentWidget(self.ui.new_page)\n\n if self.does_rig_exist():\n # rig read-only mode\n self.ui.validate_btn.setEnabled(False)\n self.ui.build_btn.setEnabled(False)\n self.ui.open_blueprint_btn.setEnabled(True)\n # switch active model label\n self.ui.blueprint_mode_label.setEnabled(False)\n self.ui.rig_mode_label.setEnabled(True)\n # update mode frame color\n self.ui.mode_frame.setProperty(\"cssClasses\", \"toolbar-rig\")\n else:\n # blueprint editing mode\n self.ui.validate_btn.setEnabled(True)\n self.ui.build_btn.setEnabled(True)\n self.ui.open_blueprint_btn.setEnabled(False)\n # switch active model label\n self.ui.blueprint_mode_label.setEnabled(True)\n self.ui.rig_mode_label.setEnabled(False)\n # update mode frame color\n self.ui.mode_frame.setProperty(\"cssClasses\", \"toolbar-blueprint\")\n\n if self.blueprint_model.is_interactive_building():\n # show button to step interactive build forward\n self.ui.interactive_build_frame.setVisible(True)\n else:\n self.ui.interactive_build_frame.setVisible(False)\n\n # refresh stylesheet for mode frame\n self.ui.mode_frame.setStyleSheet(\"\")\n","repo_name":"bohdon/maya-pulse","sub_path":"src/pulse/scripts/pulse/ui/main_toolbar.py","file_name":"main_toolbar.py","file_ext":"py","file_size_in_byte":6667,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"33"} +{"seq_id":"72106157534","text":"\"\"\"\nThese are the unit tests for the data_extract.py module\n\"\"\"\n\nimport sys\n\nsys.path.append('..')\n\nimport pandas as pd\nimport data_extract\n\ndef test_txt_to_csv():\n \"\"\"\n Test that the output dataframe is a pandas DataFrame\n Test that the data types are strings\n \"\"\"\n data_frame = data_extract.txt_to_csv\\\n ('../../genocode/data/23andMe_data.txt', '../../genocode/data/23andMe_data.csv')\n assert isinstance(data_frame, pd.core.frame.DataFrame),\\\n \"Returned dataset is not a pandas dataframe\"\n assert isinstance(data_frame['rsid'][1], str),\\\n \"data in the dataset are not strings\"\n","repo_name":"majornuw/Genes-N-Risks","sub_path":"genocode/test/test_data_extract.py","file_name":"test_data_extract.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"70157281055","text":"\"\"\" Architect controls architecture of cell by computing gradients of alphas \"\"\"\nimport copy\nimport torch\n\n#注意,此处是量化版本的,计算loss过程(使用quantize_forward而不是forward)区别于原版\n#疑问,Architect有什么用?\nclass Architect():\n \"\"\" Compute gradients of alphas \"\"\"\n def __init__(self, net, w_momentum, w_weight_decay):\n \"\"\"\n Args:\n net\n w_momentum: weights momentum\n \"\"\"\n self.net = net\n self.v_net = copy.deepcopy(net)\n self.w_momentum = w_momentum\n self.w_weight_decay = w_weight_decay\n\n #疑问:这里的virtual_step就是更新梯度,为啥不直接loss.backward()?\n def virtual_step(self, trn_X, trn_y, xi, w_optim):\n \"\"\"\n Compute unrolled weight w' (virtual step)\n\n Step process:\n 1) forward\n 2) calc loss\n 3) compute gradient (by backprop)\n 4) update gradient\n\n Args:\n xi: learning rate for virtual gradient step (same as weights lr)\n w_optim: weights optimizer\n \"\"\"\n\n # forward & calc loss\n #bug, loss_qat出现NaN\n #fix DataParallel\n loss_qat = self.net.module.loss_quantized(trn_X, trn_y) # L_trn(w)\n\n # 此处使用的self.net.weights()除了量化算子的,还包括非量化算子的,导致以下Bug\n # bug fixed: RuntimeError: One of the differentiated Tensors appears to \n # not have been used in the graph. \n # Set allow_unused=True if this is the desired behavior.\n # 只需要保证optim的输入参数是生成并参与计算图计算的,我将原版的非量化算子参数排除后解决了\n\n # test w_optim的输入参数\n # file_path = 'param_name.txt'\n # import os\n # if os.path.exists(file_path):\n # os.remove(file_path)\n # res = []\n # for n, p in self.net.named_parameters():\n # if 'stem' not in n and 'cell' not in n:\n # with open(file_path, 'a') as file:\n # file.write(n + '\\n')\n \n #bug NaN here!!!\n #test\n # 启用异常检测,没有作用,根本没检测出来,对backward和grad都不起作用\n # torch.autograd.detect_anomaly(True)\n # loss_qat.backward(retain_graph=True)\n\n # compute gradient: loss_qat对weights的导数\n #fix DataParallel\n gradients = torch.autograd.grad(loss_qat, self.net.module.weights())\n\n #test, gradients存在NaN\n # contains_nan = torch.isnan(gradients[0])\n # if contains_nan.any():\n # print(\"张量包含 NaN 值\")\n # else:\n # print(\"张量不包含 NaN 值\")\n\n #test\n # print('-------gradients:', gradients, '\\n')\n # print('-------after grad:')\n # for alpha in self.net.alpha_normal:\n # print(alpha.grad)\n\n # do virtual step (update gradient)\n # below operations do not need gradient tracking\n with torch.no_grad():\n # dict key is not the value, but the pointer. So original network weight have to\n # be iterated also.\n #fix DataParallel\n for w, vw, g in zip(self.net.module.weights(), self.v_net.module.weights(), gradients):\n #bug,当config.w_momentum被设置为0,get方法返回一个None,为什么?\n if w_optim.state[w].get('momentum_buffer', 0.) == None:\n w_optim.state[w]['momentum_buffer'] = 0.\n\n m = w_optim.state[w].get('momentum_buffer', 0.) * self.w_momentum\n vw.copy_(w - xi * (m + g + self.w_weight_decay*w))\n\n # synchronize alphas\n #fix DataParallel\n for a, va in zip(self.net.module.alphas(), self.v_net.module.alphas()):\n va.copy_(a)\n\n #疑问:这里的unrolled是什么意思?\n def unrolled_backward(self, trn_X, trn_y, val_X, val_y, xi, w_optim):\n \"\"\" Compute unrolled loss and backward its gradients\n Args:\n xi: learning rate for virtual gradient step (same as net lr)\n w_optim: weights optimizer - for virtual step\n \"\"\"\n # do virtual step (calc w`)\n self.virtual_step(trn_X, trn_y, xi, w_optim)\n\n # calc unrolled loss_quantized\n #fix DataParallel\n loss_qat = self.v_net.module.loss_quantized(val_X, val_y) # L_val(w`)\n\n # compute gradient\n #fix DataParallel\n v_alphas = tuple(self.v_net.module.alphas())\n v_weights = tuple(self.v_net.module.weights())\n v_grads = torch.autograd.grad(loss_qat, v_alphas + v_weights)#为什么alpha + weights?\n dalpha = v_grads[:len(v_alphas)]\n dw = v_grads[len(v_alphas):]\n\n hessian = self.compute_hessian(dw, trn_X, trn_y)\n\n # update final gradient = dalpha - xi*hessian\n with torch.no_grad():#这里为什么要禁止梯度计算(no_grad的作用是禁止梯度计算,但不会屏蔽梯度的数值)\n #fix DataParallel\n for alpha, da, h in zip(self.net.module.alphas(), dalpha, hessian):\n alpha.grad = da - xi*h\n\n #注意,此处会改变self.net.weights()的数值,而不仅仅计算海森矩阵\n def compute_hessian(self, dw, trn_X, trn_y):\n \"\"\"\n dw = dw` { L_val(w`, alpha) }\n w+ = w + eps * dw\n w- = w - eps * dw\n hessian = (dalpha { L_trn(w+, alpha) } - dalpha { L_trn(w-, alpha) }) / (2*eps)\n eps = 0.01 / ||dw||\n \"\"\"\n norm = torch.cat([w.view(-1) for w in dw]).norm()\n eps = 0.01 / norm\n\n # w+ = w + eps*dw`\n with torch.no_grad():\n #fix DataParallel\n for p, d in zip(self.net.module.weights(), dw):\n p += eps * d\n #bug fixed, 这里没有使用量化版本的loss\n #fix DataParallel\n loss = self.net.module.loss_quantized(trn_X, trn_y)\n dalpha_pos = torch.autograd.grad(loss, self.net.module.alphas()) # dalpha { L_trn(w+) }\n\n # w- = w - eps*dw`\n with torch.no_grad():\n #fix DataParallel\n for p, d in zip(self.net.module.weights(), dw):\n p -= 2. * eps * d\n loss = self.net.module.loss_quantized(trn_X, trn_y)\n dalpha_neg = torch.autograd.grad(loss, self.net.module.alphas()) # dalpha { L_trn(w-) }\n\n # recover w\n with torch.no_grad():\n #fix DataParallel\n for p, d in zip(self.net.module.weights(), dw):\n p += eps * d\n\n hessian = [(p-n) / 2.*eps for p, n in zip(dalpha_pos, dalpha_neg)]\n return hessian\n","repo_name":"innovatedmonster/pt.darts-0.2","sub_path":"architect2.py","file_name":"architect2.py","file_ext":"py","file_size_in_byte":6643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"29836991204","text":"# _*_ coding=utf-8 _*_\n\n\n# 插入排序,时间复杂度O(n²)\ndef insert_sort(arr):\n \"\"\"\n 插入排序;以朴克牌为例,从小到大排序。摸到的牌current与手里的每张牌进行对比,\n 手里的牌大于current,则手里的牌往后移;手里的最后一张牌小于current,current最大,结束循环。\n :param arr:\n :return:\n \"\"\"\n for i in range(1, len(arr)): # 摸到的牌的index\n # 摸到的牌\n current = arr[i]\n # 手里最后一张牌的index\n pre_index = i - 1\n while pre_index >= 0 and arr[pre_index] > current:\n arr[pre_index + 1] = arr[pre_index]\n # 继续和前一张牌进行比较\n pre_index -= 1\n # 手里的最后一张牌小于current,current最大\n arr[pre_index + 1] = current\n return arr\n\n\nnum = [4, 5, 3, 7, 6, 9, 8, 10]\nprint(insert_sort(num))\n","repo_name":"IsaacNewLee/InsertSort","sub_path":"insert_sort.py","file_name":"insert_sort.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"25143731891","text":"# Exercise 9: Calculate the sum and average of the digits present in a string\nstr1 = \"PYnative29@#8496\"\n\ntotal = 0\ncount = 0\ndef getInt(x):\n global total, count\n try:\n total += int(x)\n count += 1 \n except:\n return\n[getInt(a) for a in str1]\nprint(\"Sum is:\", total, \"Average is\", total/count)\n\n# Exercise 10: Write a program to count occurrences of all characters within a string\nstr1 = \"Apple\"\noccurrences = {}\ndef count(char):\n if not char in occurrences:\n occurrences[char] = 0\n occurrences[char] += 1\n[count(a) for a in str1]\nprint(occurrences)\n\n# Exercise 11: Reverse a given string\nstr1 = \"PYnative\"\nlist1 = list(str1)\nlist1.reverse()\nprint(\"\".join(list1))\n\n# Exercise 13: Split a string on hyphens\n\nstr1 = \"Emma-is-a-data-scientist\"\n[print(x) for x in str1.split(\"-\")]\n\n# Exercise 16: Removal all characters from a string except integers\nstr1 = 'I am 25 years and 10 months old'\n\noutput = \"\"\n\ndef isInt(x):\n global output\n try:\n int(x)\n output = output + x\n except:\n return\n\n[isInt(a) for a in str1]\n\nprint(output)","repo_name":"benson-z/FOOP-H","sub_path":"Code/stringpractice.py","file_name":"stringpractice.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"6641053875","text":"def getTestResourcesTS(resourcesTS,minTasks):\n testResTS = []\n \n for i in range(0,len(resourcesTS)):\n curRes = resourcesTS[i].resource\n minT = 0\n hasNext = 0\n \n if len(resourcesTS[i].prevNewResEvents) >= minTasks:\n minT = 1\n \n if resourcesTS[i].hasNext > 0:\n hasNext = 1\n \n if minT > 0 and hasNext > 0:\n testResTS.append(resourcesTS[i]) \n \n return testResTS\n \n","repo_name":"a-pika/ActivityRecommender","sub_path":"evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"36021190741","text":"# -*- coding: utf-8 -*-\n\"\"\"\nInterface of NiftyNet application\n\"\"\"\n\nimport tensorflow as tf\nfrom six import with_metaclass\n\nfrom niftynet.layer.base_layer import TrainableLayer\nfrom niftynet.utilities import util_common\n\n\nclass SingletonApplication(type):\n _instances = None\n\n def __call__(cls, *args, **kwargs):\n if cls._instances is None:\n cls._instances = \\\n super(SingletonApplication, cls).__call__(*args, **kwargs)\n # else:\n # raise RuntimeError('application instance already started.')\n return cls._instances\n\n\nclass BaseApplication(with_metaclass(SingletonApplication, object)):\n \"\"\"\n BaseApplication represents an interface.\n Each application type_str should support to use\n the standard training and inference driver\n \"\"\"\n\n # defines name of the customised configuration file section\n # the section collects all application specific user parameters\n REQUIRED_CONFIG_SECTION = None\n\n # boolean flag\n is_training = True\n # TF placeholders for switching network on the fly\n is_validation = None\n\n # input of the network\n readers = None\n sampler = None\n\n # the network\n net = None\n\n # training the network\n optimiser = None\n gradient_op = None\n\n # interpret network output\n output_decoder = None\n print(\"---------------------IN BASE APPLICATION\")\n\n def check_initialisations(self):\n if self.readers is None:\n raise NotImplementedError('reader should be initialised')\n if self.sampler is None:\n raise NotImplementedError('sampler should be initialised')\n if self.net is None:\n raise NotImplementedError('net should be initialised')\n if not isinstance(self.net, TrainableLayer):\n raise ValueError('self.net should be an instance'\n ' of niftynet.layer.TrainableLayer')\n if self.optimiser is None and self.is_training:\n raise NotImplementedError('optimiser should be initialised')\n if self.gradient_op is None and self.is_training:\n raise NotImplementedError('gradient_op should be initialised')\n if self.output_decoder is None and not self.is_training:\n raise NotImplementedError('output decoder should be initialised')\n\n def initialise_dataset_loader(\n self, data_param=None, task_param=None, data_partitioner=None):\n \"\"\"\n this function initialise self.readers\n\n :param data_param: input modality specifications\n :param task_param: contains task keywords for grouping data_param\n :param data_partitioner:\n specifies train/valid/infer splitting if needed\n :return:\n \"\"\"\n raise NotImplementedError\n\n def initialise_sampler(self):\n \"\"\"\n set samplers take self.reader as input and generates\n sequences of ImageWindow that will be fed to the networks\n This function sets self.sampler\n \"\"\"\n raise NotImplementedError\n\n def initialise_network(self):\n \"\"\"\n This function create an instance of network\n sets self.net\n :return: None\n \"\"\"\n raise NotImplementedError\n\n def connect_data_and_network(self,\n outputs_collector=None,\n gradients_collector=None):\n \"\"\"\n adding sampler output tensor and network tensors to the graph.\n :param outputs_collector:\n :param gradients_collector:\n :return:\n \"\"\"\n raise NotImplementedError\n\n def interpret_output(self, batch_output):\n \"\"\"\n implement output interpretations, e.g., save to hard drive\n cache output windows\n :param batch_output: outputs by running the tf graph\n :return: True indicates the driver should continue the loop\n False indicates the drive should stop\n \"\"\"\n raise NotImplementedError\n\n def set_network_gradient_op(self, gradients):\n \"\"\"\n create gradient op by optimiser.apply_gradients\n this function sets self.gradient_op\n\n Override this function for more complex optimisations such as\n using different optimisers for sub-networks.\n\n :param gradients: processed gradients from the gradient_collector\n :return:\n \"\"\"\n print(\"EEEEEEEEEEEEEEEntrando al set_network_gradient_op\")\n grad_list_depth = util_common.list_depth_count(gradients)\n if grad_list_depth == 3:\n # nested depth 3 means: gradients list is nested in terms of:\n # list of networks -> list of network variables\n self.gradient_op = [self.optimiser.apply_gradients(grad)\n for grad in gradients]\n elif grad_list_depth == 2:\n # nested depth 2 means:\n # gradients list is a list of variables\n print(\"GGGGGGGGGGGGGGGGGGGGradients list is a list of variables, depth 2\")\n self.gradient_op = self.optimiser.apply_gradients(gradients)\n\n else:\n raise NotImplementedError(\n 'This app supports updating a network, or a list of networks.')\n\n def stop(self):\n for sampler_set in self.get_sampler():\n for sampler in sampler_set:\n if sampler:\n sampler.close_all()\n\n def set_iteration_update(self, iteration_message):\n \"\"\"\n At each iteration `application_driver` calls\n `output = tf.session.run(variables_to_eval, feed_dict=data_dict)`\n to evaluate TF graph elements, where\n `variables_to_eval` and `data_dict` are retrieved from\n `application_iteration.IterationMessage.ops_to_run` and\n `application_iteration.IterationMessage.data_feed_dict`.\n (in addition to the variables collected by output_collector;\n see `application_driver.run_vars`)\n\n This function (is called before `tf.session.run` by the\n driver) provides an interface for accessing `variables_to_eval` and\n `data_dict` at each iteration.\n\n Override this function for more complex operations according to\n `application_iteration.IterationMessage.current_iter`.\n \"\"\"\n if iteration_message.is_training:\n iteration_message.data_feed_dict[self.is_validation] = False\n elif iteration_message.is_validation:\n iteration_message.data_feed_dict[self.is_validation] = True\n\n def get_sampler(self):\n return self.sampler\n\n def add_validation_flag(self):\n \"\"\"\n add a TF placeholder for switching between train/valid graphs\n :return:\n \"\"\"\n self.is_validation = \\\n tf.placeholder_with_default(False, [], 'is_validation')\n","repo_name":"amh28/NIF","sub_path":"niftynet/application/base_application.py","file_name":"base_application.py","file_ext":"py","file_size_in_byte":6808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"37810767212","text":"import librosa\nimport os\nimport numpy as np\nfrom librosa import display\nfrom matplotlib import pyplot as plt\n\n\ndef add_noise(signal, noise_factor):\n noise = np.random.normal(0, signal.std(), signal.size)\n noisy_signal = signal + noise * noise_factor\n return noisy_signal\n\n\n# Directory path for raw audio files\nDATA_PATH = \"../data/Audio\"\n\n# Directory path to save the converted spectrogram\nSPEC_PATH = \"../data/Spectrogram/Training\"\n\ncategories = os.listdir(DATA_PATH)\n\nnoise_factors = np.array([0.1, 0.3, 0.6, 0.9])\n\ncount = 0\nprint(\"Extracting Mel Spectrograms\")\nfor category in categories:\n audio_files_path = os.path.join(DATA_PATH, category)\n audio_files = os.listdir(audio_files_path)\n for file in audio_files:\n if file.endswith(\".wav\"):\n file_path = os.path.join(audio_files_path, file)\n mel_path = SPEC_PATH + \"/\" + category + \"/\" + file[0:-3] + \"png\"\n dir = SPEC_PATH + \"/\" + category\n os.makedirs(dir, exist_ok=True)\n # Reading the audio file\n signal, sr = librosa.load(file_path, sr=22050)\n # Shuffling the noise factors array so that we pick a different noise factor every time\n np.random.shuffle(noise_factors)\n # Adding the noise\n signal = add_noise(signal, noise_factors[0])\n # Extracting the mel spectrogram\n mel_spectrogram = librosa.feature.melspectrogram(y=signal, sr=sr, n_fft=2048, hop_length=512, n_mels=10)\n log_mel_spectrogram = librosa.power_to_db(mel_spectrogram)\n librosa.display.specshow(log_mel_spectrogram)\n plt.savefig(mel_path)\n print(count)\n","repo_name":"laveenbhatia/Using-CNN-for-Sentiment-Analysis-of-Noisy-Audio-Data","sub_path":"src/data_preprocess.py","file_name":"data_preprocess.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"40288152129","text":"import cv2 as cv\n\ncapture = cv.VideoCapture(0)\n\nfacedetection = cv.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\nwhile True:\n ret,frame = capture.read()\n faces = facedetection.detectMultiScale(frame,scaleFactor=1.10,minNeighbors=5)\n for x,y,w,h in faces:\n cv.rectangle(frame, (x,y), (x+w, y+h), (0, 0, 255),2)\n cv.imshow(\"Face_Detection\",frame)\n stop = cv.waitKey(1)\n if stop == ord(\"v\"):\n break\ncapture.release()\ncv.destroyAllWindows()\n \n","repo_name":"xvinay28x/face_detection","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"42346359990","text":"# -*-* coding:UTF-8\nimport os\nfrom pathlib import Path\n\n\nclass Plugin(Base):\n __info__ = {\n \"name\": \"一米OA getfile.jsp 任意文件读取漏洞\",\n \"description\": \"一米OA getfile.jsp文件过滤不足,导致任意文件读取漏洞。\",\n \"references\": [],\n }\n\n def url(self) -> dict:\n res = self.read_file('../public/getfile.jsp')\n if res and 'import' in res and 'isUserPrivValid' in res:\n return {\"LoopholeInfo\": self.__info__}\n\n @cli.command(description='文件读取')\n @cli.options(\"file\", help=\"读取文件\", default=\"../public/getfile.jsp\")\n def read_file(self, file):\n path, filename = os.path.split(file)\n file_stem, file_ext = Path(filename).stem, Path(filename).suffix\n r = self.request(\n method='GET',\n path=f'./public/getfile.jsp?user=1&prop=activex&filename={path}/{file_stem}&extname={file_ext}',\n timeout=15\n )\n if r.status_code == 200:\n return r.text\n","repo_name":"z-bool/Polaris","sub_path":"plugins/exploit/一米/AVD-2022-1343457.py","file_name":"AVD-2022-1343457.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"33"} +{"seq_id":"42547676896","text":"import random\nimport time\n\n\ndef sleep_random_sec():\n duration = random.uniform(2, 5)\n time.sleep(duration)\n\n\nif __name__ == '__main__':\n from collections import defaultdict\n\n d = defaultdict(int)\n for i in range(999999):\n t = int(random.uniform(2, 5))\n d[t] += 1\n for i in d.items():\n print(i)\n","repo_name":"marin-jovanovic/common","sub_path":"comm/comm_sleep.py","file_name":"comm_sleep.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"39426453762","text":"import json\r\n\r\ndata = {\r\n \"giant eagle\": {\r\n \"login\": \"\",\r\n \"password\": \"\"\r\n },\r\n \"twilio\": {\r\n \"account_sid\": \"\",\r\n \"auth_token\": \"\",\r\n \"from_phone\": \"+1\",\r\n \"to_phones\": [\"+1\", \"+1\"],\r\n \"test\": {\r\n \"account_sid\": \"\",\r\n \"auth_token \": \"\",\r\n \"test_from\": \"+15005550006\"\r\n }\r\n },\r\n \"store_comment\": \"taken from URL when reserve button is clicked - https://curbsideexpress.gianteagle.com/store/BB361095#/landing\",\r\n \"store\": \"BB361095\",\r\n \"mode_comment\": \"mode should be 'continuous' or 'single'\",\r\n \"mode\": \"continuous\",\r\n \"delay_comment\": \"delay is in seconds\",\r\n \"delay\": 1200\r\n}\r\n\r\nwith open('GiantEagle.json', 'w') as outfile:\r\n json.dump(data, outfile, indent=4)\r\n\r\nprint(json.dumps(data, indent=4))\r\n","repo_name":"MrJacques/GiantEaglePickupChecker","sub_path":"CreateJSON.py","file_name":"CreateJSON.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"71144327136","text":"#!/usr/bin/python3\ndef print_last_digit(number):\n ln = number % 10\n ln1 = (number * -1) % 10\n if number >= 0:\n print(\"{}\".format(ln), end=\"\")\n return ln\n else:\n print(\"{}\".format(ln1), end=\"\")\n return ln1\n","repo_name":"stevengm45/holbertonschool-higher_level_programming","sub_path":"0x01-python-if_else_loops_functions/9-print_last_digit.py","file_name":"9-print_last_digit.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"32451571592","text":"'''\nDescription: \nAuthor: colin gao\nDate: 2023-05-10 11:35:55\nLastEditTime: 2023-05-14 17:11:13\n'''\nfrom langchain.text_splitter import CharacterTextSplitter\nimport re\nfrom typing import List\nfrom configs.config import SENTENCE_SIZE\n\n\"\"\"\nclass ChineseTextSplitter(CharacterTextSplitter):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def split_text(self, text: str) -> List[str]:\n text = re.sub(r'([;;.!?。!?\\?])([^”’])', r\"\\1\\n\\2\", text) # 单字符断句符\n text = re.sub(r'(\\.{6})([^\"’”」』])', r\"\\1\\n\\2\", text) # 英文省略号\n text = re.sub(r'(\\…{2})([^\"’”」』])', r\"\\1\\n\\2\", text) # 中文省略号\n text = re.sub(r'([;;!?。!?\\?][\"’”」』]{0,2})([^;;!?,。!?\\?])', r'\\1\\n\\2', text)\n text = text.replace(\"\\u3000\", \"\")\n # 如果双引号前有终止符,那么双引号才是句子的终点,把分句符\\n放到双引号后,注意前面的几句都小心保留了双引号\n text = text.rstrip()\n ls = [text[i:i + SENTENCE_SIZE] for i in range(0, len(text), SENTENCE_SIZE)]\n\n return ls\n\"\"\"\n\nclass ChineseTextSplitter(CharacterTextSplitter):\n def __init__(self, pdf: bool = False, **kwargs):\n super().__init__(**kwargs)\n self.pdf = pdf\n\n def split_text(self, text: str) -> List[str]:\n if self.pdf:\n text = re.sub(r\"\\n{3,}\", \"\\n\", text)\n text = re.sub('\\s', ' ', text)\n text = text.replace(\"\\n\\n\", \"\")\n sent_sep_pattern = re.compile(\n '([﹒﹔﹖﹗.。!?][\"’”」』]{0,2}|(?=[\"‘“「『]{1,2}|$))') \n sent_list = []\n for ele in sent_sep_pattern.split(text):\n if sent_sep_pattern.match(ele) and sent_list:\n sent_list[-1] += ele\n elif ele:\n sent_list.append(ele)\n return sent_list\n","repo_name":"GaoQ1/langchain-chatbot","sub_path":"textsplitter/chinese_text_splitter.py","file_name":"chinese_text_splitter.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"33"} +{"seq_id":"69856004896","text":"import pyxel\n \n# ====== Image parameters ======\nWINDOW_H = 120\nWINDOW_W = 160\nCAT_H = 16\nCAT_W = 16\n \n# ===== Physical parameters =====\nFPS = 30 # フレームレート [f/s]\nDT = 1 / FPS # ステップ時間 [s]\nG = 9.8 # 重力加速度 [kg.m/s^2]\nK = 5 # ばね定数 [n/m]\n \nclass Vec2:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n \nclass cat:\n def __init__(self, img_id):\n self.pos = Vec2(0, 0)\n self.vec = 0\n self.vel = 0\n self.weight = 1\n self.time = 0\n self.img_cat = img_id\n \n def update(self, x, y, dx):\n self.pos.x = x\n self.pos.y = y\n self.vec = dx\n \nclass Ceiling:\n def __init__(self):\n self.pos1 = Vec2(0, 30)\n self.pos2 = Vec2(WINDOW_W, 35)\n self.color = 12 # blue\n \nclass Spring:\n def __init__(self):\n self.pos1 = Vec2(0, 0)\n self.pos2 = Vec2(0, 0)\n self.color = 12 # blue\n \n def update(self, x1, y1, x2, y2, color):\n self.pos1.x = x1\n self.pos1.y = y1\n self.pos2.x = x2\n self.pos2.y = y2\n self.color = color\n \nclass App:\n def __init__(self):\n self.IMG_ID0_X = 60\n self.IMG_ID0_Y = 65\n self.IMG_ID0 = 0\n self.IMG_ID1 = 1\n # self.IMG_ID2 = 2\n \n pyxel.init(WINDOW_W, WINDOW_H, fps = FPS, caption=\"Hello Pyxel\")\n pyxel.image(self.IMG_ID0).load(0, 0, \"assets/pyxel_logo_38x16.png\")\n pyxel.image(self.IMG_ID1).load(0, 0, \"assets/cat_16x16.png\")\n \n pyxel.mouse(True)\n \n # make instance\n self.Cats = []\n self.Springs = []\n self.ceiling = Ceiling()\n \n pyxel.run(self.update, self.draw)\n \n def update(self):\n if pyxel.btnp(pyxel.KEY_Q):\n pyxel.quit()\n \n # ====== ctrl cat ======\n if pyxel.btnp(pyxel.MOUSE_LEFT_BUTTON):\n new_cat = cat(self.IMG_ID1)\n new_cat.update(pyxel.mouse_x, pyxel.mouse_y, new_cat.vec)\n self.Cats.append(new_cat)\n \n new_spring = Spring()\n self.Springs.append(new_spring)\n \n cat_count = len(self.Cats)\n for i in range(cat_count):\n if self.Cats[i].pos.y < WINDOW_H:\n # ばね変位:x(猫のy座標 - 天井のy座標)\n x = self.Cats[i].pos.y - self.ceiling.pos2.y\n # f = m * g - k * x(重力 - 復元力)\n f = self.Cats[i].weight * G - K * x\n # a = f / m (ニュートンの運動方程式)\n alpha = f / self.Cats[i].weight\n # v += a * dt (積分:加速度 ⇒ 速度)\n self.Cats[i].vel += alpha * DT\n # y += v * dt (積分:速度 ⇒ 位置)\n self.Cats[i].pos.y += self.Cats[i].vel * DT\n # 経過時間\n self.Cats[i].time += DT\n \n # debug\n print(\"Cat No.\", i)\n print(\"v = \", self.Cats[i].vel)\n print(\"y = \", self.Cats[i].pos.y)\n print(\"f = \", f)\n \n # Cat update\n self.Cats[i].update(self.Cats[i].pos.x, \n self.Cats[i].pos.y, \n self.Cats[i].vec)\n \n # Spring update\n self.Springs[i].update(self.Cats[i].pos.x + CAT_W / 2, \n self.ceiling.pos2.y, \n self.Cats[i].pos.x + CAT_W / 2, \n self.Cats[i].pos.y,\n pyxel.frame_count % 16)\n \n else:\n del self.Cats[i]\n break\n \n def draw(self):\n pyxel.cls(0)\n pyxel.text(55, 40, \"Are you Kururu?\", pyxel.frame_count % 16)\n pyxel.blt(self.IMG_ID0_X, self.IMG_ID0_Y, self.IMG_ID0, 0, 0, 38, 16)\n \n # ======= draw cat ========\n for cats in self.Cats:\n pyxel.blt(cats.pos.x, cats.pos.y, cats.img_cat, 0, 0, CAT_W, CAT_H, 5)\n \n # ======= draw springs ========\n for springs in self.Springs:\n pyxel.line(springs.pos1.x, springs.pos1.y, \n springs.pos2.x, springs.pos2.y, \n springs.color)\n \n # ======= draw ceiling ========\n pyxel.rect(self.ceiling.pos1.x, self.ceiling.pos1.y, \n self.ceiling.pos2.x, self.ceiling.pos2.y, \n self.ceiling.color)\n \nApp()","repo_name":"azm17/trampoline","sub_path":"trampoline.py","file_name":"trampoline.py","file_ext":"py","file_size_in_byte":4491,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"38381875651","text":"from pymongo import MongoClient\nimport numpy as np\ndef connectMongo():\n '''\n connect to a target mongo database\n :return: a mongo database connection\n '''\n myclient = MongoClient(\"mongodb://124.70.205.181:27017/\")\n db = myclient['business']\n db.authenticate('nzp','nzp123456')\n return db\nclass Mongo():\n '''\n class Mongo represents a mongo conncetion which can do some dataset operations.\n '''\n def __init__(self):\n self.con = MongoClient(\"mongodb://101.132.98.20:27018/\") # link database\n self.db = self.con[\"business\"] # choose database\n self.db.authenticate('nzp','nzp123456')\n # self.collection = self.db['store_info'] # choose collection\n def query(self, table):\n # inquery a table without conditions\n collection = self.db[table]\n result = collection.find()\n return result\n def queryLimited(self, table, condition):\n # inquery a table with a condition\n collection = self.db[table]\n result = collection.find(condition)\n return result\n def delete(self, table, id):\n # delete a data record from a table according to the record id\n collection = self.db[table]\n query = {\"_id\": id}\n collection.delete_one(query)\nif __name__ == '__main__':\n mongo = Mongo()\n # mongo.delete('user_info', '6facc31c7cd111ebb62d00163e1cbf3d')\n myquery = {\"data_complete\":1}\n users = mongo.queryLimited('user_info', myquery)\n for one in users:\n print(one)\n # print(int(str(one['_id']), 16))","repo_name":"InvincibleKe/recommendation_party","sub_path":"dbConnection.py","file_name":"dbConnection.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"21674880226","text":"from flask_apscheduler import APScheduler\n\nimport config\nfrom managers.admin_access_managers.delivery_manager import DeliveryGuyManger\n\nscheduler = APScheduler()\napp = config.create_app()\n\nif __name__ == \"__main__\":\n with app.app_context():\n scheduler.init_app(app)\n scheduler.add_job(id=\"delete\",\n func=lambda: (app.app_context().push(), DeliveryGuyManger.move_delivered_packages()),\n trigger='interval', minutes=1)\n\n scheduler.start()\n app.run()\n","repo_name":"nenovKrasimir/flask_rest_api_sport_center_project","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"71103082015","text":"import pygame\nimport random\n\n# initialize all pygame modules (font, display, etc.)\npygame.init()\n\n# 10x20 grid\nSCREEN_WIDTH = 1000\nSCREEN_HEIGHT = 800\nCOLUMNS = 10\nROWS = 20\nBLOCK_SIZE = (SCREEN_HEIGHT * 4) // 95\nPLAY_WIDTH = COLUMNS * BLOCK_SIZE\nPLAY_HEIGHT = ROWS * BLOCK_SIZE\nWINDOW_COLOR = (10, 15, 20)\nPLAY_COLOR = (20, 30, 40)\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n\n# top-left xy coordinates (origin frame of reference)\ntop_left_x = (SCREEN_WIDTH // 4) - (PLAY_WIDTH // 2)\ntop_left_y = (SCREEN_HEIGHT - PLAY_HEIGHT) // 1.5\n\n# game sounds\ngame_over_sound = pygame.mixer.Sound(\"gameover.wav\")\nclear_row_sound = pygame.mixer.Sound(\"line.wav\")\n\n# tetromino schematic of orientation\nS = [['.00.', \n '00..',\n '....', \n '....'], \n ['0...', \n '00..', \n '.0..', \n '....']]\n\nZ = [['00..', \n '.00.',\n '....', \n '....'], \n ['..0.', \n '.00.', \n '.0..', \n '....']]\n\nI = [['.0..', \n '.0..', \n '.0..', \n '.0..'], \n ['....', \n '0000', \n '....', \n '....'],\n ['..0.', \n '..0.', \n '..0.', \n '..0.'], \n ['....',\n '....', \n '0000', \n '....']]\n\nO = [['00..',\n '00..',\n '....', \n '....']]\n\nJ = [['0...', \n '000.', \n '....', \n '....'],\n ['.00.', \n '.0..', \n '.0..', \n '....'],\n ['....', \n '000', \n '..0.', \n '....'],\n ['.0..', \n '.0..', \n '00..', \n '....']]\n\nL = [['..0.', \n '000.', \n '....', \n '....'],\n ['.0..', \n '.0..', \n '.00.', \n '....'],\n ['....', \n '000.', \n '0...', \n '....'],\n ['00..', \n '.0..', \n '.0..', \n '....']]\n\nT = [['.0..', \n '000.', \n '....', \n '....'],\n ['.0..', \n '.00.', \n '.0..', \n '....'],\n ['....', \n '000.', \n '.0..', \n '....'],\n ['.0..', \n '00..', \n '.0..', \n '....']]\n\n# Green S, Red Z, Cyan I, Yellow O, Blue J, Orange L, Purple T\npiece_types = [S, Z, I, O, J, L, T]\npiece_colors = [(5, 196, 107), (255, 82, 82), (0, 216, 214), (255, 165, 2), (56, 103, 214), (255, 121, 63), (136, 84, 208)]\n\n# define a tetromino object\nclass Piece(object):\n def __init__(self, column, row, piece_type):\n self.x = column\n self.y = row\n self.piece_type = piece_type\n self.color = piece_colors[piece_types.index(piece_type)]\n self.rotation = 0 # mod len(piece_type)\n\n# initialize grid lines and locked pieces in the play area\ndef create_grid(locked_positions):\n grid = [[PLAY_COLOR for _ in range(COLUMNS)] for _ in range(ROWS)]\n for y in range(ROWS):\n for x in range(COLUMNS):\n if (y, x) in locked_positions:\n block_color = locked_positions[(y, x)]\n grid[y][x] = block_color\n return grid\n\n# draw play area and grid lines \ndef draw_grid(surface, grid):\n # draw play area with all the pieces\n for y in range(ROWS):\n for x in range(COLUMNS):\n block_x = (top_left_x + (x * BLOCK_SIZE))\n block_y = (top_left_y + (y * BLOCK_SIZE))\n pygame.draw.rect(surface, grid[y][x], (block_x, block_y, BLOCK_SIZE, BLOCK_SIZE), 0)\n pygame.draw.rect(surface, WHITE, (top_left_x - 5, top_left_y - 5, PLAY_WIDTH + 11, PLAY_HEIGHT + 11), 5)\n \n # draw grid lines\n for y in range(ROWS):\n horizontal_start = (top_left_x, top_left_y + (y * BLOCK_SIZE))\n horizontal_end = (top_left_x + PLAY_WIDTH, top_left_y + (y * BLOCK_SIZE))\n pygame.draw.line(surface, BLACK, horizontal_start, horizontal_end)\n for x in range(COLUMNS):\n vertical_start = (top_left_x + (x * BLOCK_SIZE), top_left_y)\n vertical_end = (top_left_x + (x * BLOCK_SIZE), top_left_y + PLAY_HEIGHT)\n pygame.draw.line(surface, BLACK, vertical_start, vertical_end)\n\n# draw game window with text \ndef draw_window(surface, grid, current_score, high_score):\n surface.fill(WINDOW_COLOR)\n\n # Display title\n font = pygame.font.SysFont('phosphate', 100)\n title = font.render('TETRIS', 1, WHITE)\n title_x = (SCREEN_WIDTH * 0.75) - (title.get_width() / 2)\n title_y = top_left_y\n surface.blit(title, (title_x, title_y))\n\n # Display current score\n font = pygame.font.SysFont('futura', 24)\n label = font.render('Current Score: ' + str(current_score), 1, WHITE)\n label_x = (SCREEN_WIDTH * 0.75) - (label.get_width() / 2)\n label_y = (top_left_y + PLAY_HEIGHT) * 0.75 + (BLOCK_SIZE / 2)\n surface.blit(label, (label_x, label_y - (BLOCK_SIZE * 1.25)))\n\n # Display high score\n font = pygame.font.SysFont('futura', 24)\n label = font.render('High Score: ' + str(high_score), 1, WHITE)\n label_x = (SCREEN_WIDTH * 0.75) - (label.get_width() / 2)\n label_y = (top_left_y + PLAY_HEIGHT) * 0.75 + (BLOCK_SIZE * 2)\n surface.blit(label, (label_x, label_y - (BLOCK_SIZE * 1.5)))\n\n # draw grid after window set up\n draw_grid(surface, grid)\n\n# Show user the next piece\ndef draw_next_tetromino(piece, surface):\n # Display text for next tetromino\n font = pygame.font.SysFont('futura', 24)\n label = font.render('Next Tetromino', 1, WHITE)\n label_x = (SCREEN_WIDTH * 0.75) - (label.get_width() / 2)\n label_y = (top_left_y + PLAY_HEIGHT) / 2\n surface.blit(label, (label_x, label_y - (BLOCK_SIZE * 1.5)))\n\n # Display next tetromino\n piece_orientation = piece.piece_type[piece.rotation]\n for y in range(len(piece_orientation)):\n for x in range(len(piece_orientation[y])):\n if piece_orientation[y][x] == '0':\n next_piece_x = (SCREEN_WIDTH * 0.75) - (BLOCK_SIZE * 1.5) + (x * BLOCK_SIZE)\n next_piece_y = label_y + (y * BLOCK_SIZE)\n pygame.draw.rect(surface, piece.color, (next_piece_x, next_piece_y, BLOCK_SIZE, BLOCK_SIZE), 0)\n pygame.draw.rect(surface, BLACK, (next_piece_x, next_piece_y, BLOCK_SIZE, BLOCK_SIZE), 1)\n \n# generate random piece\ndef get_random_piece():\n return Piece(5, 0, random.choice(piece_types))\n\n# convert piece orientation to grid positions\ndef convert_piece_format(piece):\n positions = []\n orientation = piece.piece_type[piece.rotation]\n for delta_y in range(len(orientation)):\n for delta_x in range(len(orientation[delta_y])):\n if orientation[delta_y][delta_x] == '0':\n positions.append((piece.y + delta_y, piece.x + delta_x))\n return positions\n\n# check if piece in valid location\ndef valid_location(piece, grid):\n accepted_locations = []\n for y in range(ROWS):\n for x in range(COLUMNS):\n if grid[y][x] == PLAY_COLOR:\n accepted_locations.append((y, x))\n\n formatted_piece_locations = convert_piece_format(piece)\n for position in formatted_piece_locations:\n if position not in accepted_locations:\n if position[0] > -1:\n return False\n return True\n\n# check if game lost and display message\ndef check_failure(locked_positions, surface, score):\n for position in locked_positions:\n if position[0] < 1:\n surface.fill(WINDOW_COLOR)\n pygame.mixer.music.stop()\n pygame.mixer.Sound.play(game_over_sound)\n\n # You Lose!\n font = pygame.font.SysFont('futura', 42)\n label = font.render('You Lose!', 1, WHITE)\n label_x = (SCREEN_WIDTH - label.get_width()) / 2\n label_y = (SCREEN_HEIGHT - label.get_height()) / 2\n surface.blit(label, (label_x, label_y))\n\n # Final Score\n font = pygame.font.SysFont('futura', 24)\n label = font.render('Final Score: ' + str(score), 1, WHITE)\n label_x = (SCREEN_WIDTH - label.get_width()) / 2\n label_y = (SCREEN_HEIGHT - label.get_height()) / 2 + BLOCK_SIZE\n surface.blit(label, (label_x, label_y))\n\n pygame.display.update()\n pygame.time.delay(2000)\n pygame.event.clear()\n return True\n return False\n\n# update high score in save file\ndef update_high_score(current_score):\n high_score = get_high_score()\n with open('high_score.txt', 'w') as score_file:\n if high_score < current_score:\n score_file.write(str(current_score))\n else:\n score_file.write(str(high_score)) \n score_file.close()\n\n# lookup high score in save file\ndef get_high_score():\n with open('high_score.txt', 'r') as score_file:\n score_file.seek(0)\n chars = score_file.readlines()\n high_score = int(chars[0].strip()) \n score_file.close()\n return high_score\n\n# clear row when all pieces filled, move grid down, and return score\ndef clear_rows(locked_positions, grid):\n shift = 0\n for y in range(ROWS - 1, -1, -1):\n # remove complete rows\n if PLAY_COLOR not in grid[y]:\n shift += 1\n for x in range(COLUMNS):\n if (y, x) in locked_positions:\n del locked_positions[(y, x)]\n # shift other rows down \n elif shift > 0:\n pygame.mixer.Sound.play(clear_row_sound)\n for x in range(COLUMNS):\n if (y, x) in locked_positions:\n locked_positions[(y + shift, x)] = locked_positions.pop((y, x))\n return shift ** 2\n\n# main game loop\ndef main(surface, high_score):\n global SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, PLAY_WIDTH, PLAY_HEIGHT, top_left_x, top_left_y\n\n run = True\n locked_positions = {}\n current_piece = get_random_piece()\n next_piece = get_random_piece()\n change_piece = False\n pygame.key.set_repeat(200)\n\n pygame.mixer.music.load(\"tetris_theme.mp3\")\n pygame.mixer.music.play(-1)\n clock = pygame.time.Clock()\n fall_time = 0\n level_time = 0\n fall_speed = 0.25\n score = 0\n\n while run:\n grid = create_grid(locked_positions)\n fall_time += clock.get_rawtime()\n level_time += clock.get_rawtime()\n clock.tick()\n\n # level up - increase piece fall speed\n if level_time / 1000 > 5:\n level_time = 0\n if fall_speed > 0.14:\n fall_speed -= 0.005\n\n # move piece down until collision\n if fall_time / 1000 > fall_speed:\n fall_time = 0\n current_piece.y += 1\n if not valid_location(current_piece, grid) and current_piece.y > 0:\n current_piece.y -= 1\n change_piece = True\n\n # handle events\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n pygame.mixer.music.stop()\n\n elif event.type == pygame.VIDEORESIZE:\n SCREEN_WIDTH = event.w\n SCREEN_HEIGHT = event.h\n BLOCK_SIZE = (SCREEN_HEIGHT * 4) // 95\n PLAY_WIDTH = COLUMNS * BLOCK_SIZE\n PLAY_HEIGHT = ROWS * BLOCK_SIZE\n top_left_x = (SCREEN_WIDTH // 4) - (PLAY_WIDTH // 2)\n top_left_y = (SCREEN_HEIGHT - PLAY_HEIGHT) // 1.5\n\n old_surface = surface\n surface = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.RESIZABLE)\n surface.blit(old_surface, (0, 0))\n del old_surface\n\n elif event.type == pygame.KEYDOWN:\n # left-arrow key - move left if possible\n if event.key == pygame.K_LEFT:\n current_piece.x -= 1\n if not valid_location(current_piece, grid):\n current_piece.x += 1\n # right-arrow key - move right if possible\n elif event.key == pygame.K_RIGHT:\n current_piece.x += 1\n if not valid_location(current_piece, grid):\n current_piece.x -= 1\n # down-arrow key - move down if possible\n elif event.key == pygame.K_DOWN:\n current_piece.y += 1\n if not valid_location(current_piece, grid):\n current_piece.y -= 1\n # up-arrow key - change piece orientation if possible\n elif event.key == pygame.K_UP:\n current_piece.rotation = (current_piece.rotation + 1) % len(current_piece.piece_type)\n if not valid_location(current_piece, grid):\n current_piece.rotation = (current_piece.rotation - 1) % len(current_piece.piece_type)\n\n # put current piece in grid\n piece_locations = convert_piece_format(current_piece)\n for i in range(len(piece_locations)):\n y, x = piece_locations[i]\n if y > -1:\n grid[y][x] = current_piece.color\n \n # lock piece when it hits the ground\n if change_piece:\n for i in range(len(piece_locations)):\n locked_positions[piece_locations[i]] = current_piece.color\n current_piece = next_piece\n next_piece = get_random_piece()\n change_piece = False\n\n # clear rows if completed and add to score\n score += clear_rows(locked_positions, grid) * 10\n \n # render play\n draw_window(surface, grid, score, high_score)\n draw_next_tetromino(next_piece, surface)\n pygame.display.update()\n\n # break loop when player loses\n if check_failure(locked_positions, surface, score):\n run = False\n update_high_score(score)\n\n# main menu to start game\ndef main_menu(window):\n global SCREEN_WIDTH, SCREEN_HEIGHT\n\n run = True\n while run:\n window.fill(WINDOW_COLOR)\n # Title\n title_size = SCREEN_HEIGHT // 5\n font = pygame.font.SysFont('phosphate', title_size)\n title = font.render('TETRIS', 1, WHITE)\n title_x = (SCREEN_WIDTH - title.get_width()) / 2\n title_y = (SCREEN_HEIGHT - title.get_height()) / 2\n window.blit(title, (title_x, title_y))\n\n # Press Any Key\n label_size = SCREEN_HEIGHT // 40\n font = pygame.font.SysFont('futura', label_size)\n label = font.render('Press Any Key To Play!', 1, WHITE)\n label_x = (SCREEN_WIDTH - title.get_width()) / 2\n label_y = (SCREEN_HEIGHT - title.get_height()) / 2\n window.blit(label, (label_x, label_y))\n pygame.display.update()\n\n # Start or quit game (allow resize too)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n if event.type == pygame.KEYDOWN:\n high_score = get_high_score()\n main(window, high_score)\n if event.type == pygame.VIDEORESIZE:\n old_window = window\n SCREEN_WIDTH = event.w\n SCREEN_HEIGHT = event.h\n window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.RESIZABLE)\n window.blit(old_window, (0, 0))\n del old_window\n\n pygame.display.quit()\n\n# Initialize window and open main menu\nwindow = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.RESIZABLE)\npygame.display.set_caption('Tetris')\nmain_menu(window)","repo_name":"cnaphade/tetris","sub_path":"tetris.py","file_name":"tetris.py","file_ext":"py","file_size_in_byte":15242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"29397377778","text":"import numpy as np\nfrom mpi4py import MPI\nimport time as timmy\nfrom scipy.fftpack import fft, ifft\nimport os\nfrom input import *\n\ntext_out1 = '**Simulation is launched on %s nodes. \\nYou have %s electrons spread on %s x %s grid. \\nInitializing ewoks objects.\\n' \ntext_out2 = \"**Cleaning the output folders\\n\"\ntext_out3 = \"**All initial data is calculated. Starting the main simulation loop..\\n\"\ntext_out4 = \"** %s percent is done. output files are written.\\n\"\ntext_out5 = \"**Im done in %s minutes. Bye !\\n\"\n\nexp_src = np.vectorize( lambda x, y, t_step : np.exp(-2*np.pi*1j*((t_step-seed_delay)*dt-x)))\n\nclass toys:\n def __init__(self, ewok):\n '''gives Ewok his toys for signal and pump creation, diagnostics and messaging'''\n self.x_ij, self.y_ij = ewok.x_ij, ewok.y_ij\n\n # preparing the optical lattice potential\n if lattice_modif:\n self.stat_pump_potent = -a0*(1./2.)*1j*np.exp(-2j*np.pi*((beta+1)*self.x_ij + self.y_ij/gamma_ext)) \\\n + a0*(3./2.)*1j*np.exp(-2j*np.pi*((beta+1)*self.x_ij - self.y_ij/gamma_ext))\n else:\n self.stat_pump_potent = 2*a0*np.sin(2*np.pi*self.y_ij/gamma_ext)\\\n * np.exp(-1j*(beta+1)*self.x_ij*2*np.pi)\n\n # preparing the seed\n self.get_seed_profile()\n self.seed_rotation()\n\n # preparing the working folders, writing message and starting the timer\n if ewok.rank == 0:\n os.system('./clear.py')\n text_out = open(out_folder+'text_out.txt',mode='a')\n text_out.writelines(text_out2)\n text_out.writelines(text_out1 % (ewok.size, N_part_full,bins_x,bins_y))\n text_out.close()\n self.Tstart = timmy.time()\n\n # defining the output folders names\n self.stepwise_folder = out_folder+'stepwise_data/'\n self.phase_folder = out_folder+'phase_data/'\n self.ion_phase_folder = out_folder+'phase_ion/'\n self.dens_folder = out_folder+'dens_data/'\n self.ion_folder = out_folder+'dens_ion/'\n self.fld_folder = out_folder+'fld_data/'\n self.stat_potent_folder = out_folder+'stat_potent/'\n\n def pump_func(self,t):\n ''' temporal modulations of lattice potential '''\n pump = self.stat_pump_potent\n\n if t<=injection_time:\n pump = pump*float(t)/float(injection_time)\n\n if bonus:\n pump = pump+self.bonus_pump(t)\n\n if pump_unstable:\n pump = pump*(1.0 + delta_ampl*np.sin(delta_freq*2*np.pi*t*dt))\n\n return pump\n\n def bonus_pump(self, time):\n ''' additional wave in the lattice (not used)'''\n if time 70:\n print('No')\n exit(0)\n\ns = set()\nfor i in range(1, k + 1):\n s.add(n % i)\n\nprint('Yes' if len(s) == k else 'No')\n","repo_name":"ayoubc/competitive-programming","sub_path":"online_judges/codeforces/C/922C.py","file_name":"922C.py","file_ext":"py","file_size_in_byte":166,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"26971124300","text":"#!/usr/bin/env python3\n\nimport os\nfrom dotenv import load_dotenv\nfrom web3 import Web3\nfrom uniswap import Uniswap\n\naddress = None # or None if you're not going to make transactions\nprivate_key = None # or None if you're not going to make transactions\nversion = 3 # specify which version of Uniswap to use\n#provider = \"WEB3 PROVIDER URL\" # can also be set through the environment variable `PROVIDER`\n\neth = \"0x0000000000000000000000000000000000000000\"\nbat = \"0x0D8775F648430679A709E98d2b0Cb6250d2887EF\"\ndai = \"0x6B175474E89094C44Da98b954EedeAC495271d0F\"\nsafe = \"0x5aFE3855358E112B5647B952709E6165e1c1eEEe\"\nusdc = \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\"\nweth = \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\"\nsafeEthPoolAddress = \"0xBB0ecCb680FF8b2cbBB239b200cC6f9927b4aacB\"\n\ndef main():\n print(\"main()\")\n load_dotenv()\n uniswap = Uniswap(address=address, private_key=private_key, version=version, provider=os.environ['PROVIDER'])\n # Returns the amount of DAI you get for 1 ETH (10^18 wei)\n oneEthInUsdc = uniswap.get_price_input(eth, usdc, 1*10**18)*1e-6\n print(oneEthInUsdc)\n oneSafeInUsdc = uniswap.get_price_input(safe, eth, 1*10**18) # fails, does not find pool, uniswap ui does\n print(oneSafeInUsdc)\n\n safeEthPool = uniswap.get_pool_instance(weth,safe) # pool not found ?\n print(safeEthPool)\n\nif __name__ == \"__main__\": \n main()","repo_name":"starwalker00/uniswap-metrics","sub_path":"main_uniswapy.py","file_name":"main_uniswapy.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"28620877175","text":"from setuptools import setup, find_packages\n\n# Package meta-data.\nNAME = \"singlish_translator\"\nDESCRIPTION = \"Singlish to Sinhala conversion library\"\nURL = \"https://github.com/SupunGurusinghe/SinglishProcessor.git\"\nEMAIL = \"supunsameeran@gmail.com\"\nAUTHOR = \"Supun Gurusinghe\"\nREQUIRES_PYTHON = \">=3.7.0\"\n\n# setup function\nsetup(\n include_package_data=True,\n author=AUTHOR,\n author_email=EMAIL,\n description=DESCRIPTION,\n name=NAME,\n version='0.1.0 ',\n packages=find_packages(include=['tab_cleaner', 'tab_cleaner.*']),\n python_requires=REQUIRES_PYTHON\n)\n","repo_name":"SupunGurusinghe/SinglishProcessor","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"10679763382","text":"# ============================================\n__author__ = \"Sachin Mehta\"\n__maintainer__ = \"Sachin Mehta\"\n# ============================================\n\nimport torch\nfrom torch import nn\nfrom fairseq.delight_modules.drop_layers import RecurrentDropout\nfrom fairseq.delight_modules.dextra_unit import DExTraUnit\nimport math\n\n\nclass DExTraEmb(nn.Module):\n '''\n This class implements embeddings similar to DeFINE emebeddings introduced in\n https://arxiv.org/abs/1911.12385\n '''\n\n def __init__(self, args, map_layer, use_bias: bool = True):\n '''\n :param args: Argument list\n :param map_layer: Mapping layer (Adaptive or standard)\n :param use_bias: Use bias or not\n '''\n super(DExTraEmb, self).__init__()\n self.map_layer = map_layer\n self.input_features = args.delight_emb_map_dim\n self.embedding_dim = args.delight_emb_out_dim\n\n self.dextra_layer = DExTraUnit(\n in_features=self.input_features,\n in_proj_features=self.embedding_dim // 2,\n out_features=self.embedding_dim,\n width_multiplier=args.delight_emb_width_mult,\n dextra_depth=args.delight_emb_depth,\n dextra_dropout=args.delight_dropout,\n max_glt_groups=args.delight_emb_max_groups,\n act_type=args.act_type,\n norm_type=args.norm_type,\n use_bias=use_bias,\n is_iclr_version=args.define_iclr,\n glt_shuffle=args.glt_shuffle,\n )\n\n if args.adaptive_input:\n # added in Adaptive layer\n self.embed_scale = 1.0\n else:\n self.embed_scale = 1.0 if args.no_scale_embedding else math.sqrt(self.input_features)\n\n self.drop_layer = RecurrentDropout(p=args.delight_emb_dropout, batch_first=True)\n\n def forward(self, x):\n '''\n B --> Batch size\n T --> Time steps\n E --> Embedding dimension\n :param x: Input of shape [B x T]\n :return: Output of shape [B x T x E]\n '''\n\n assert x.dim() == 2, 'Input should be [B x T]'\n\n # [B x T] --> [B x T x E]\n x = self.map_layer(x) * self.embed_scale\n # drop the embeddings\n x = self.drop_layer(x)\n # learn DeFINE embeddings\n x = self.dextra_layer(x)\n return x\n\n def __repr__(self):\n s = '{name}(in_features={input_features}, output_features={embedding_dim})'\n s += '\\n \\t {}'.format(self.map_layer)\n s += '\\n \\t {}'.format(self.dextra_layer)\n return s.format(name=self.__class__.__name__, **self.__dict__)\n\n def compute_macs_params(self):\n emb_params = 0\n emb_macs = 0\n non_emb_macs = 0\n non_emb_params = 0\n\n from fairseq.modules.adaptive_input import AdaptiveInput\n if isinstance(self.map_layer, nn.Embedding):\n emb_params += self.map_layer.weight.numel()\n # LUT does not have any MACs\n emb_macs += 0\n elif isinstance(self.map_layer, AdaptiveInput):\n mac_params_adaptive = self.map_layer.compute_macs_params()\n\n emb_macs += mac_params_adaptive['embedding_macs']\n emb_params += mac_params_adaptive['embedding_params']\n\n non_emb_macs += mac_params_adaptive['proj_macs']\n non_emb_params += mac_params_adaptive['proj_params']\n\n macs_params_define = self.dextra_layer.compute_macs_params()\n\n non_emb_macs += macs_params_define['macs']\n non_emb_params += macs_params_define['params']\n\n # DeFINE embeddings can be cached, so non-emb MACS and PARAMS are zero\n # Uncomment below to see MACS and PARAMS during inference\n # non_emb_params = 0\n # non_emb_macs = 0\n\n return {\n 'name': self.__class__.__name__,\n 'emb_params': emb_params,\n 'emb_macs': emb_macs,\n 'non_emb_macs': non_emb_macs,\n 'non_emb_params': non_emb_params\n }\n","repo_name":"sacmehta/delight","sub_path":"fairseq/delight_modules/dextra_emb.py","file_name":"dextra_emb.py","file_ext":"py","file_size_in_byte":3970,"program_lang":"python","lang":"en","doc_type":"code","stars":451,"dataset":"github-code","pt":"33"} +{"seq_id":"38307714947","text":"import time\nimport pickle\nimport sys\nsys.path.insert(0, 'meetpy')\nsys.path.insert(0, 'meetpy/util')\nsys.path.insert(0, 'meetpy/old/scalingproject')\n\nfrom scipy import optimize\nfrom numpy import random\nfrom numpy.linalg import norm\n\nfrom erp_variability_model_fit import ERP_Variability_Model_Fit,\\\n fit_variability_model, error_mean,\\\n error_cov, error_mean_and_cov\n\n\ndef run_fitting_schemes(model_types, number_of_generators, random_seeds,\n schemes, mean_data, cov_data, max_fun_eval=100000):\n all_models = def_all_models_dict(schemes, model_types, \n number_of_generators, random_seeds)\n\n overall_start_time = time.time()\n for (model_type, n_gen, seed, scheme) in [(model_type, n_gen, seed, scheme)\n for scheme in schemes\n for model_type in model_types \n for n_gen in number_of_generators\n for seed in random_seeds]:\n random.seed(seed)\n entry = def_empty_entry_dict()\n erp_model = ERP_Variability_Model_Fit(n_sub=23, n_gen=n_gen)\n parameter_list = prepare_variability_parameter_list(erp_model, \n model_type, n_gen)\n # If parameter_list is None that means the combination of model_type\n # and number of generators shouldn't be taken into account.\n if parameter_list is None:\n continue\n parameter_list.insert(0,'amplitudes')\n parameter_list.insert(0,'locations and orientations')\n erp_model.set_random_parameters(parameter_list)\n\n description = 'Fitting scheme: ' + scheme + ', model type: ' +\\\n model_type + ', with ' + str(n_gen) +\\\n ' generator(s) and seed ' + str(seed)\n print(description + '\\n' + '=' * len(description))\n \n entry['starting_error_mean'] = error_mean(mean_data, erp_model, [], \n []) / norm(mean_data, 2)\n entry['starting_error_covariance'] = error_cov(cov_data, erp_model, \n [], []) / norm(cov_data.reshape((erp_model.n_el**2,1)), 2)\n entry['starting_error_mean_and_covariance'] =\\\n error_mean_and_cov(mean_data, cov_data, erp_model, [], [])\n print('Starting error on mean: ' + str(entry['starting_error_mean']))\n print('Starting error on covariance: ' +\\\n str(entry['starting_error_covariance']))\n print('Starting error on mean and covariance combined: ' +\\\n str(entry['starting_error_mean_and_covariance']) + '\\n')\n \n # Simplifying calling of fitting functions to make fitting scheme code\n # clearer and easier to read.\n fit_amplitudes_lambda = lambda erp_model, with_locations:\\\n fit_amplitudes(erp_model, n_gen, seed, mean_data,\n with_locations=with_locations,\n max_fun_eval=max_fun_eval)\n fit_variability_lambda = lambda erp_model, with_locations:\\\n fit_variability(erp_model, model_type, n_gen, seed, cov_data, \n with_locations=with_locations,\n max_fun_eval=max_fun_eval)\n \n if scheme == 'covariance and locations':\n entry['fits'].append(fit_variability_lambda(erp_model, True))\n elif scheme == 'amplitudes, covariance and locations':\n entry['fits'].append(fit_amplitudes_and_variability(erp_model, \n model_type, n_gen, seed, mean_data, cov_data,\n with_locations=True, max_fun_eval=max_fun_eval))\n if scheme == 'amplitudes and locations, then covariance':\n entry['fits'].append(fit_amplitudes_lambda(erp_model, True))\n entry['fits'].append(fit_variability_lambda(erp_model, False))\n if scheme == 'covariance and locations, then amplitudes':\n entry['fits'].append(fit_variability_lambda(erp_model, True))\n entry['fits'].append(fit_amplitudes_lambda(erp_model, False))\n if scheme == 'amplitudes and locations, then covariance and ' +\\\n 'locations, multiple times':\n n_repeats = 10\n for i in range(n_repeats):\n entry['fits'].append(fit_amplitudes_lambda(erp_model, True))\n entry['fits'].append(fit_variability_lambda(erp_model, True))\n\n #if entry['fits'][-1] != None:\n entry['scheme'] = scheme\n entry['erp_model'] = erp_model\n all_models[scheme][model_type][n_gen][seed] = entry\n\n entry['final_error_mean'] = error_mean(mean_data, erp_model, [], [])\\\n / norm(mean_data, 2)\n entry['final_error_covariance'] = error_cov(cov_data, erp_model, [],\n []) / norm(cov_data.reshape((erp_model.n_el**2,1)), 2)\n entry['final_error_mean_and_covariance'] =\\\n error_mean_and_cov(mean_data, cov_data, erp_model, [], [])\n print('Final error on mean: ' + str(entry['final_error_mean']))\n print('Final error on covariance: ' +\\\n str(entry['final_error_covariance']))\n print('Final error on mean and covariance combined: ' +\\\n str(entry['final_error_mean_and_covariance']) + '\\n')\n \n print('Overall time elapsed: ' + str(round(time.time() -\\\n overall_start_time,2)))\n\n return all_models\n\n\ndef def_all_models_dict(schemes, model_types, number_of_generators, \n random_seeds):\n \"\"\"\n The all_models dictionary will hold all ERP model objects after fitting\n along with information about the fitting procedures performed and the final\n results. \n \n Each ERP model object will be held in a separate entry for model type,\n number of generators and randomization seed, such that:\n \n all_models[scheme][model_type][n_gen][seed]\n \n will hold an ERP model object and other information in the dictionary \n defined by:\n\n empty_entry = def_empty_entry_dict()\n \"\"\"\n all_models = {}\n for scheme in schemes:\n all_models[scheme] = {}\n for model_type in model_types:\n all_models[scheme][model_type] = {}\n for n_gen in number_of_generators:\n all_models[scheme][model_type][n_gen] = {}\n for seed in random_seeds:\n all_models[scheme][model_type][n_gen][seed] = None\n return all_models\n\n\ndef def_empty_entry_dict():\n \"\"\"\n The empty_entry dictionary defines what information should be stored in:\n\n entry = all_models[scheme][model_type][n_gen][seed]\n\n for each model type, number of generators and random seed.\n \"\"\"\n empty_entry = {} \n empty_entry['starting_error_mean'] = None\n empty_entry['starting_error_covariance'] = None\n empty_entry['starting_error_mean_and_covariance'] = None\n empty_entry['final_error_mean'] = None\n empty_entry['final_error_covariance'] = None\n empty_entry['final_error_mean_and_covariance'] = None\n empty_entry['scheme'] = None\n empty_entry['fits'] = []\n empty_entry['erp_model'] = None\n\n return empty_entry\n\n\ndef fit_amplitudes(erp_model, n_gen, seed, mean_data, with_locations=False,\n max_fun_eval=100000):\n parameter_list = ['amplitudes']\n if with_locations is True:\n parameter_list.insert(0,'locations and orientations')\n description = 'Fit of generator locations and amplitudes to mean'\n else:\n description = 'Fit of generator amplitudes to mean'\n print(description + '\\n' + '-' * len(description))\n\n start_time = time.time()\n output = fit_variability_model(erp_model,\n parameter_list, \n fit_to='mean', fit_data=mean_data, \n method='tnc', bounds= True, \n max_fun_eval=max_fun_eval,\n disp=True)\n elapsed_time = time.time() - start_time\n print('* Elapsed time: ' + str(elapsed_time) + 's\\n')\n\n return fit_info(erp_model, description, output)\n\n\ndef fit_variability(erp_model, model_type, n_gen, seed, cov_data, \n with_locations=False, max_fun_eval=100000):\n parameter_list = prepare_variability_parameter_list(erp_model, model_type,\n n_gen)\n if with_locations is True:\n parameter_list.insert(0,'locations and orientations')\n description = 'Fit of generator locations and variability to ' +\\\n 'covariance'\n else:\n description = 'Fit of variability to covariance'\n print(description + '\\n' + '-' * len(description))\n \n start_time = time.time()\n output = fit_variability_model(erp_model, parameter_list,\n fit_to='covariance', \n fit_data=cov_data, \n method='tnc', bounds= True,\n max_fun_eval=max_fun_eval, \n disp=True)\n elapsed_time = time.time() - start_time\n print('* Elapsed time: ' + str(elapsed_time) + 's\\n')\n\n return fit_info(erp_model, description, output)\n\n\ndef fit_amplitudes_and_variability(erp_model, model_type, n_gen, seed, \n mean_data, cov_data, with_locations=False, \n max_fun_eval=100000):\n parameter_list = prepare_variability_parameter_list(erp_model, model_type,\n n_gen)\n parameter_list.insert(0,'amplitudes')\n \n if with_locations is True:\n parameter_list.insert(0,'locations and orientations')\n description = 'Fit of generator locations, amplitudes and ' +\\\n 'variability to mean and covariance'\n else:\n description = 'Fit of generator amplitudes and variability to ' +\\\n 'mean and covariance'\n print(description + '\\n' + '-' * len(description))\n \n start_time = time.time()\n output = fit_variability_model(erp_model, parameter_list,\n fit_to='mean and covariance', \n fit_data=[mean_data, cov_data], \n method='tnc', bounds= True, \n max_fun_eval=max_fun_eval, disp=True)\n elapsed_time = time.time() - start_time\n print('* Elapsed time: ' + str(elapsed_time) + 's\\n')\n\n return fit_info(erp_model, description, output)\n\n\ndef prepare_variability_parameter_list(erp_model, model_type, n_gen):\n variability_electrodes='none' \n variability_generators='none' \n variability_connections='none'\n \n if model_type == 'cELVM':\n parameter_list = ['electrode variance']\n variability_electrodes = 'constant' \n elif model_type == 'cGLVM':\n parameter_list = ['generator variance']\n variability_generators = 'constant'\n elif model_type == 'iGLVM':\n if n_gen < 2:\n return None\n parameter_list = ['generator variance']\n variability_generators='individual' \n elif model_type == 'iGiCLVM':\n if n_gen < 2:\n return None\n parameter_list = ['generator variance', \n 'generator covariance']\n variability_generators='individual' \n variability_connections='individual'\n elif model_type == 'iGiCcELVM':\n if n_gen < 2:\n return None\n parameter_list = ['generator variance', \n 'generator covariance', \n 'electrode variance']\n variability_electrodes='constant'\n variability_generators='individual'\n variability_connections='individual'\n\n erp_model.set_variability_type(variability_electrodes,\n variability_generators,\n variability_connections)\n \n return parameter_list\n\n\ndef fit_info(erp_model, description, output):\n \"\"\"\n Common information that should be saved for all fits performed. It can then\n be accessed from:\n\n all_models[scheme][model_type][n_gen][seed]['fits'][i_fit]\n\n where i_fit is the index of the fit corresponding to the order in which \n fits were performed.\n \"\"\"\n fit_info = {}\n fit_info['erp_model'] = erp_model\n fit_info['fit_description'] = description\n fit_info['starting_error'] = output[1]\n fit_info['fit_iterations'] = output[0][1]\n fit_info['fit_result'] = output[0][2]\n fit_info['fit_message'] = optimize.tnc.RCSTRINGS[output[0][2]]\n fit_info['final_error'] = output[2]\n \n return fit_info\n","repo_name":"rgoj/phd_code","sub_path":"util/run_fitting_schemes.py","file_name":"run_fitting_schemes.py","file_ext":"py","file_size_in_byte":12956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"71060722336","text":"# truncate: xoa het noi dung của file\n# write : ghi noi dung gi do vao file\n\nfileName = input(\"Nhập tên file: \")\n\nfile = open(fileName,'a+')\n# w mở file để ghi thay thế, r là mở file để đọc, a thì sẽ cho phép ghi đè\n# nếu dừng w+,r+, a+ có nghĩa cho phép dùng vừa đọc vừa ghi\n\nprint(\"Xóa nội dung của file: \", fileName)\n# Xóa trắng file\n# file.truncate()\n\nprint(\"Ghi noi dung của file\\n\")\n\nline1 = input(\"Line 1:\" )\nline2 = input(\"Line 2: \")\nline3 = input(\"Line 3: \")\n\nprint(\"I'm going to write these to the file\")\n\nfile.write(line1 + \"\\n\")\nfile.write(line2 + \"\\n\")\nfile.write(line3 + \"\\n\")\n\nprint(\"Ghi thành công\")\nfile.close()","repo_name":"duyhoangptit/LearnPython","sub_path":"writeFile.py","file_name":"writeFile.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"24788506723","text":"import os\nfrom constants import ENCODING, KEY_SIZE, CHAR_SIZE\n\ndef compress(input_file, output_file):\n t = Trie()\n with open(input_file, 'r') as file:\n t.create(file.read())\n \n compressed_result = t.output\n\n with open(output_file, 'wb') as file:\n file.write(compressed_result)\n\nclass Trie:\n def __init__(self):\n self.index = 1\n self.root = {'': {'indexes':[0], 'children':{}}}\n self.output = bytearray(0)\n\n def create(self, text):\n word = \"\"\n inserted = False\n father_node = None\n for c in text:\n aux = word + c\n father_node, inserted = self.__insert(aux, self.root[''])\n if not inserted:\n word = aux #continue processing until a new segment is inserted\n else: #add tuple to output\n word = \"\"\n self.index = self.index + 1\n self.__format_output(father_node, c)\n if not inserted and father_node: #if last isn't inserted, only add the index to the output\n self.__format_output(father_node)\n\n def __insert(self, word, node):\n dictionary = node['children']\n if dictionary.get(word): #if the word is already included, return index\n return dictionary[word]['indexes'][-1], False\n for key in dictionary:\n if word.startswith(key):\n if dictionary[key]['children']: #if there are children, insert key as a child\n return self.__insert(word[len(key):len(word)], dictionary[key])\n else: #if there aren't children, compact node\n father_node = self.__compact_node(dictionary, key, word)\n return father_node, True\n else: #check if should break any nodes\n i = len(key) - 1\n while i > 0:\n if word == key[0:i]: #if word is included in a key, return corresponding index\n return dictionary[key]['indexes'][i], False\n if word.startswith(key[0:i]): #if the word starts with a partial key, break the node\n father_node = self.__break_node(dictionary, key, i, word)\n return father_node, True\n i = i - 1\n\n #insert prefix if it doesn't exist\n dictionary[word] = {'indexes':[self.index], 'children':{}}\n return node['indexes'][-1], True\n\n def __compact_node(self, dictionary, key, word):\n indexes = dictionary[key]['indexes']\n father_node = indexes[-1] #save father node\n indexes.append(self.index)\n dictionary.pop(key)\n dictionary[word] = {'indexes':indexes, 'children':{}}\n return father_node\n\n def __break_node(self, dictionary, key, breaking_index, word):\n #remove original node\n children = dictionary[key]['children']\n indexes = dictionary[key]['indexes']\n dictionary.pop(key)\n \n #create node for original sufix\n original_sufix = key[breaking_index:len(key)]\n original_sufix_indexes = indexes[breaking_index:len(key)]\n original_sufix_node = self.__create_node(original_sufix_indexes, children)\n\n #create node for new sufix\n new_sufix = word[breaking_index:len(word)]\n new_sufix_node = self.__create_node([self.index], {})\n\n #create new prefix node\n prefix = key[0:breaking_index]\n prefix_indexes = indexes[0:breaking_index]\n new_children = {new_sufix: new_sufix_node, original_sufix: original_sufix_node}\n dictionary[prefix] = self.__create_node(prefix_indexes, new_children)\n\n #return father node\n return prefix_indexes[-1]\n\n def __create_node(self, indexes, children):\n return {'indexes': indexes, 'children': children}\n\n def __format_output(self, number, c = ''):\n encoded_number = number.to_bytes(length=KEY_SIZE, byteorder='big')\n encoded_char = self.__encode_char(c)\n self.output = b''.join([self.output, encoded_number, encoded_char])\n\n def __encode_char(self, char):\n encoded_char = char.encode(ENCODING)\n #if encoded char is smaller than char size, add padding\n if encoded_char and len(encoded_char) < CHAR_SIZE:\n encoded_char = b''.join([bytearray(CHAR_SIZE - len(encoded_char)), encoded_char])\n #if encoded char is bigger than char size, return error\n elif encoded_char and len(encoded_char) > CHAR_SIZE:\n print(\"Encoding \", char, \" not supported\")\n os._exit(1)\n return encoded_char\n","repo_name":"paula-mr/data-compression-compact-trie","sub_path":"compress.py","file_name":"compress.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"12441038099","text":"from rest_framework.decorators import api_view\n\nfrom rest_framework.response import Response\nfrom base.models import Client\nfrom .serializers import ClientSerializer\nfrom base.api import serializers\n\n\n@api_view(['GET'])\ndef getRoutes(request):\n routes = [\n 'GET /api',\n 'GET /api/clients',\n 'GET /api/clients/:id'\n ]\n return Response(routes)\n\n\n@api_view(['GET'])\ndef getClients(request):\n clients = Client.objects.all()\n serializer = ClientSerializer(clients, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef getClient(request, pk):\n client = Client.objects.get(id=pk)\n serializer = ClientSerializer(client, many=False)\n return Response(serializer.data)","repo_name":"lq62224/Web_App_Project","sub_path":"base/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"19344315335","text":"import dbdreader\nfrom collections import OrderedDict\nimport profiles.profiles\nfrom numpy import ones, array\nfrom time import ctime\nimport ndf\n\nclass Slocum(object):\n def __init__(self,filenames,core_parameters=None,extra_parameters={}):\n ''' extra_parameters can be a dictionary with items:\n \n (name_of_parameter, (dbd_parameter_name, unit_after_scaling, scaling_factor))\n '''\n self.filenames=filenames\n self.header=[]\n self.initialise(core_parameters,extra_parameters)\n\n def initialise(self,core_parameters,extra_parameters):\n parameters=OrderedDict()\n if core_parameters:\n for k,v in core_parameters.items():\n parameters[k]=v\n else:\n parameters[\"time\"]=(None,\"s\",1.)\n parameters[\"conductivity\"]=(\"sci_water_cond\",\"mS/cm\",10.)\n parameters[\"temperature\"]=(\"sci_water_temp\",'C',1.)\n parameters[\"pressure\"]=(\"sci_water_pressure\",\"dbar\",10)\n parameters[\"pitch\"]=(\"m_pitch\",\"rad\",1.)\n parameters[\"roll\"]=(\"m_roll\",\"rad\",1.)\n parameters[\"speed\"]=(\"m_speed\",\"m/s\",1.)\n parameters[\"profile_number\"]=(None,\"-\",1)\n for k,v in extra_parameters.items():\n parameters[k]=v\n self.parameters=parameters\n\n def add_metadata(self,field,mesg):\n self.header.append((field,mesg))\n\n def convert(self,of=None):\n pass\n\n def __check_for_ctd_timestamp(self,dbd):\n r=False\n if 'sci_ctd41cp_timestamp' in dbd.parameterNames['sci']:\n t=dbd.get(\"sci_ctd41cp_timestamp\")\n if len(t[1]) and max(t[1])>1e9:\n r=True\n return r\n\n def __mark_profiles(self,data):\n d=dict(time=data[\"time\"],pressure=data[\"pressure\"])\n p=profiles.profiles.ProfileSplitter(data=d)\n p.split_profiles()\n n_profiles=p.len()\n tmp=ones(data[\"time\"].shape,int)*(-1)\n for i in range(n_profiles):\n tmp[p.i_down[i]]=i*2\n tmp[p.i_up[i]]=i*2+1\n data[\"profile_number\"]=tmp\n\n def get_data(self):\n dbd=dbdreader.MultiDBD(filenames=self.filenames, include_paired=True)\n has_ctd_time=self.__check_for_ctd_timestamp(dbd)\n parameterlist=[v[0] for k,v in self.parameters.items() if v[0] and k!=\"sci_water_pressure\"]\n if has_ctd_time:\n parameterlist.append(\"sci_ctd41cp_timestamp\")\n x=dbd.get_sync(\"sci_water_pressure\",parameterlist)\n data=dict()\n if has_ctd_time:\n x=x.compress(x[-1]>1e8,axis=1) # remove ctd times equal to\n # 0 (and also unrealistic\n # CTD values)\n data[\"time\"]=x[-1]\n parameterlist.remove(\"sci_ctd41cp_timestamp\") # not needed anymore\n else:\n data[\"time\"]=x[0]\n data[\"pressure\"]=x[1]\n parameterlist=[k for k,v in self.parameters.items() if v[0] and k!=\"sci_water_pressure\"]\n for i,p in enumerate(parameterlist):\n data[p]=x[i+2]\n dbd.close()\n # filter the data\n #LPF=profiles.filters.LagFilter(1.0,1.73)\n #data[\"conductivity\"]=LPF.filter(data[\"time\"],data[\"conductivity\"])\n #LPF=profiles.filters.LagFilter(1.0,1.37)\n #data[\"temperature\"]=LPF.filter(data[\"time\"],data[\"temperature\"])\n # add the indices for profile identification\n self.__mark_profiles(data)\n return data\n\nclass SlocumAscii(Slocum):\n hash=\"#\"\n def __init__(self,filenames,core_parameters={},extra_parameters={}):\n ''' extra_parameters can be a dictionary with items:\n \n (name_of_parameter, (dbd_parameter_name, unit_after_scaling, scaling_factor))\n '''\n Slocum.__init__(self,filenames,core_parameters=core_parameters,extra_parameters=extra_parameters)\n\n def convert(self,of=\"output.asc\",data=None):\n fd=open(of,'w')\n data=data or self.get_data()\n self.add_metadata(\"Number of profiles\",max(data[\"profile_number\"])+1)\n self.add_metadata(\"Creation time\",ctime())\n self.__write_header(fd)\n self.__write_body(fd,data)\n fd.close()\n\n def __write_header(self,fd):\n for hdr in self.header:\n s=\"%s: %s\"%hdr\n fd.write(\"%s %s\\n\"%(self.hash,s))\n fd.write(\"%s \"%(self.hash))\n for p in list(self.parameters.keys())[:-1]:\n fd.write(\"%15s\"%(p))\n fd.write(\"%15s\\n\"%(list(self.parameters.keys())[-1]))\n fd.write(\"%s \"%(self.hash))\n for p in list(self.parameters.values())[:-1]:\n fd.write(\"%15s\"%(p[1]))\n fd.write(\"%15s\\n\"%(list(self.parameters.values())[-1][1]))\n\n def __write_body(self,fd,data):\n # write the data to file\n for j in range(len(data[\"time\"])):\n if data[\"profile_number\"][j]==-1:\n continue\n for p in self.parameters:\n if p==\"time\":\n fmt=\"%15.8f\"\n elif p==\"profile_number\":\n fmt=\"%15d\"\n else:\n fmt=\"%15.8f\"\n fd.write(fmt%(data[p][j]*self.parameters[p][2]))\n fd.write(\"\\n\")\n\nclass SlocumNDF(Slocum):\n\n def __init__(self,filenames,core_parameters={},extra_parameters={}):\n Slocum.__init__(self,filenames,core_parameters,extra_parameters)\n\n def convert(self,of=\"output.ndf\"):\n data=self.get_data()\n self.add_metadata(\"Number of profiles\",max(data[\"profile_number\"])+1)\n self.add_metadata(\"Creation time\",ctime())\n self.__write_ndf(data,of)\n\n def __write_ndf(self,data,of):\n ndf_data=ndf.NDF()\n # adding the data\n parameters_wo_time=dict([(k,v) for k,v in self.parameters.items() if k!='time'])\n for k,v in parameters_wo_time.items():\n # v[2] is the scaling factor\n x=v[2]*data[k]*1.0\n ndf_data.add_parameter(k,v[1],(data[\"time\"],x),str(v[0]))\n # adding meta data\n for k,v in self.header:\n if k=='Creation time':\n continue # to avoid duplicates...\n if k=='Number of profiles':\n # this should be global parameter\n ndf_data.add_global_parameter(k,int(v))\n else:\n ndf_data.add_metadata(k,v)\n ndf_data.save(of)\n\nclass Ascii2ndf(object):\n def __init__(self,filename):\n self.filename=filename\n self.initialise_ndf()\n\n def initialise_ndf(self):\n self.ndf=ndf.NDF()\n\n def header_to_metadata(self,line):\n line=line.replace(SlocumAscii.hash,\"\").strip()\n if \":\" in line:\n i=line.index(\":\")\n field,mesg=line[:i],line[i+1:]\n self.ndf.add_metadata(field,mesg)\n \n def add_parameters(self,parameter_info):\n names,units=parameter_info\n names=names.split()\n units=units.split()\n for name,unit in zip(names,units):\n if name==\"time\":\n continue\n self.ndf.add_parameter(name,unit,(0,0))\n self.names=names\n\n def read_header(self):\n fp=open(self.filename,'r')\n parameter_info=[]\n while True:\n line=fp.readline()\n if line.startswith(SlocumAscii.hash):\n self.header_to_metadata(line)\n if not \":\" in line:\n tmp=line.replace(SlocumAscii.hash,\"\").strip()\n parameter_info.append(tmp)\n else:\n break\n fp.close()\n self.add_parameters(parameter_info)\n\n def read_body(self):\n fp=open(self.filename,'r')\n data=dict([(k,[]) for k in self.names])\n while True:\n line=fp.readline()\n if not line:\n break\n if line.startswith(SlocumAscii.hash):\n continue\n # we got a data line\n fields=line.split()\n for k,v in zip(self.names,fields):\n data[k].append(float(v))\n fp.close()\n parameters=[n for n in self.names if n!=\"time\"]\n t=array(data[\"time\"])\n for n in parameters:\n self.ndf[n]=(t,array(data[n]))\n\n def save(self,of=\"output.ndf\"):\n self.ndf.save(of)\n\n \nif __name__==\"__main__\":\n if 0:\n import glob\n fns=glob.glob(\"/home/lucas/gliderdata/coconet/hd/sebastian-2013-132-02-08?.[ed]bd\")\n s=SlocumAscii(fns)\n s.add_metadata(\"Originator\",\"me\")\n s.convert()\n if 0:\n a=Ascii2ndf('output.asc')\n a.read_header()\n a.read_body()\n a.save()\n if 1:\n import glob\n fns=glob.glob(\"/home/lucas/gliderdata/coconet/hd/sebastian-2013-132-02-08?.[ed]bd\")\n s=SlocumNDF(fns)\n s.add_metadata(\"Originator\",\"me\")\n s.convert()\n","repo_name":"smerckel/glider_profiles","sub_path":"dataconverters.py","file_name":"dataconverters.py","file_ext":"py","file_size_in_byte":8837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"25668744664","text":"# importing Flask and other modules\nimport json\nimport os\nimport pandas as pd\nimport pickle\nfrom google.cloud import storage\nfrom flask import Flask, request, render_template\n\n# Flask constructor\napp = Flask(__name__)\n\n\n# A decorator used to tell the application\n# which URL is associated function\n@app.route('/checkbodyfat', methods=[\"GET\", \"POST\"])\ndef check_bodyfat():\n if request.method == \"POST\":\n prediction_input = [\n {\n \"Age\": int(request.form.get(\"Age\")),\n \"Neck\": int(request.form.get(\"Neck\")),\n \"Knee\": int(request.form.get(\"Knee\")),\n \"Ankle\": int(request.form.get(\"Ankle\")),\n \"Biceps\": int(request.form.get(\"Biceps\")),\n \"Forearm\": float(request.form.get(\"Forearm\")),\n \"Wrist\": float(request.form.get(\"Wrist\")),\n \"Weight\": float(request.form.get(\"Weight\")),\n \"Height\": float(request.form.get(\"Height\")),\n \"Abdomen\": float(request.form.get(\"Abdomen\")),\n \"Chest\": float(request.form.get(\"Chest\")),\n \"Hip\": float(request.form.get(\"Hip\")),\n \"Thigh\": int(request.form.get(\"Thigh\"))\n }\n ]\n print(prediction_input)\n # Importing model from the pipeline bucket\n storage_client = storage.Client(project='de2022-362617')\n\n bucket = storage_client.bucket('bodyfat_model')\n blob = bucket.blob('best_model.pkl')\n filename = '/tmp/local_best_model.pkl'\n blob.download_to_filename(filename)\n blob_t = bucket.blob('transformer.pkl')\n filename_t = '/tmp/transformer.pkl'\n blob_t.download_to_filename(filename_t)\n\n model = pickle.load(open(filename, 'rb'))\n transformer = pickle.load(open(filename_t, 'rb'))\n\n X = pd.DataFrame.from_dict(prediction_input)\n\n X['Bmi'] = 703 * X['Weight'] / (X['Height'] * X['Height'])\n X['ACratio'] = X['Abdomen'] / X['Chest']\n X['HTratio'] = X['Hip'] / X['Thigh']\n X.drop(['Weight', 'Height', 'Abdomen', 'Chest', 'Hip', 'Thigh'], axis=1, inplace=True)\n\n # Transformer\n X = transformer.transform(X)\n density = model.predict(X)\n fat = ((4.95 / density[0]) - 4.5) * 100\n return {'Density': density[0], 'Bodyfat': fat}\n return render_template(\n \"user_form.html\") # this method is called of HTTP method is GET, e.g., when browsing the link\n\n\nif __name__ == '__main__':\n # app.run(host='0.0.0.0', port=5001)\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"Lucasvereggen/Data-Engineering","sub_path":"pipeline-ui/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"2806881283","text":"\n\n\"\"\"\nWhy do we need dynamic programming? What's the difference of dynamic programming and previous talked search problme?\nAns:\n\n在很多问题中直接求解会相当困难。我们可以采取分解问题的方法,将复杂问题分解成多个的子问题,这些子问题通常是可以求解的,进而我们可以求解该复杂问题。\n搜索问题:找下一步最优\n动态规划:将找到的每一步的最优都存起来了\n\nWhy do we still need dynamic programming? Why not we train a machine learning to fit a function which could get the right answer based on inputs?\n在一些问题中,使用机器学习的方法,由于需要大量的数据,不方便直接求解。使用动态规划来解决可能会更加简单、快捷\n\nCan you catch up at least 3 problems which could solved by Dynamic Programming?\nAns: 编辑距离、硬币找零、背包问题\n\nCan you catch up at least 3 problems wich could sloved by Edit Distance?\nAns: 最小编辑距离、模糊匹配、拼写检查、求最长公共子序列\n\nPlease summarize the three main features of Dynamic Programming, and make a concise explain for each feature.\nAns:\n问题的具有子问题结构\n子问题重复性\n对于子问题的解析\n\nWhat's the disadvantages of Dynamic Programming? (You may need search by yourself in Internet)\nDisadvantages:\n\n没有统一的标准模型;\n数值方法求解时存在维数灾,消耗空间大,当所给出范围很大时,堆栈中很可能并不能满足所需要的空间大小,\n\"\"\"\n\nimport math\nimport random\nimport matplotlib.pylab as plt\n\nlatitudes = [random.randint(-100, 100) for _ in range(20)]\nlongitude = [random.randint(-100, 100) for _ in range(20)]\n# plt.scatter(latitudes, longitude)\n\n# 给定一个初始点 $P$, 已经 $k$个车辆,如何从该点出发,经这 k 个车辆经过所以的点全部一次,而且所走过的路程最短?\n# 例如:\nchosen_p = (5, 10)\nplt.scatter(latitudes, longitude)\nplt.scatter([chosen_p[0]], [chosen_p[1]], color='r')\nplt.show()\n\ndef get_distance(x,y):\n return math.sqrt((x[0]-y[0])**2 + (x[1] -y[1])**2)\n# print(distance(chosen_p,(100,100)))\n\npoints = [(i,j)for i,j in zip(latitudes,longitude)]\nprint(points)\n\nsum = 0\nfor i,v in enumerate(points[:-1]):\n sum += get_distance(v,points[i+1])\nprint(sum)\nsum += get_distance(chosen_p,points[0])\nprint(sum)\n\ndis_solution = {}\ndef route_distance(p,points):\n\n if p in p_set and len(p_set) == 1:return 0\n if len(p_set) == 0:return 0\n\n candidates = [get_distance(p,e) + route_distance(e,points.remove(e)) for e in points]\n\n min_distance, point = min(candidates, key=lambda x: x[0])\n\n dis_solution[(p, points)] = point\n\n return min_distance\n\nprint(chosen_p,points)\n\n\n\n","repo_name":"jiwawa112/NLP","sub_path":"assignment_04.py","file_name":"assignment_04.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"31415087599","text":"import logging\n\n\nclass Formatter(logging.Formatter):\n\n f_color = {'black': 30, 'red': 31, 'green': 32, 'yellow': 33,\n 'blue': 34, 'purple': 35, 'cyan': 36, 'white': 37, 'gray': 38}\n b_color = {'black': 40, 'red': 41, 'green': 42, 'yellow': 43,\n 'blue': 44, 'purple': 45, 'cyan': 46, 'white': 47, 'gray': 48}\n mode = {\"mormal\": 0, 'bold': 1, 'dark': 2, 'underline': 4,\n 'blink': 5, 'reverse': 7, 'concealed': 8}\n reset = '\\x1b[0m'\n fmt_debug = \"[%(levelname)s %(threadName)s %(asctime)s %(funcName)s(%(lineno)d)] %(message)s\"\n\n def __init__(self, *args, **kw):\n super(Formatter, self).__init__(*args, **kw)\n self.fmt = \"[%(levelname)s %(asctime)s] %(message)s\"\n self._formats = {\n logging.DEBUG: {\n \"fmt\": self.fmt,\n \"color\": self._color(0, 36) # cyan\n },\n logging.INFO: {\n \"fmt\": self.fmt,\n \"color\": self._color(0, 32) # green\n },\n logging.WARNING: {\n \"fmt\": self.fmt,\n \"color\": self._color(0, 33) # yellow\n },\n logging.ERROR: {\n \"fmt\": self.fmt,\n \"color\": self._color(0, 31) # red\n },\n logging.CRITICAL: {\n \"fmt\": self.fmt,\n \"color\": self._color(0, 35) # purple\n },\n }\n\n def _color(self, mode=0, fore=30):\n return '\\x1b[%sm\\x1b[%sm' % (mode, fore)\n\n def format(self, record):\n fmt = self._formats.get(record.levelno)\n log_fmt = fmt[\"color\"] + fmt[\"fmt\"] + self.reset\n formatter = logging.Formatter(log_fmt)\n return formatter.format(record)\n","repo_name":"yodeng/bpan","sub_path":"src/_log.py","file_name":"_log.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"33"} +{"seq_id":"39013996145","text":"from collections import defaultdict, Counter, deque\n\ndef runCase():\n a, b = map(int, input().split())\n print(a * b // 2)\nif __name__ == '__main__':\n # tests = int(input())\n tests = 1\n for _ in range(tests):\n runCase()","repo_name":"bedre7/competitive-programming","sub_path":"Codeforces/Contest-35/B_Domino_piling.py","file_name":"B_Domino_piling.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"40721995505","text":"#!/usr/bin/env python3\n#read current value of the camera and move in the desired direction\n#read the odometry data and use that as the inital position when the mode is shift \n\n\nimport time\nfrom math import *\n\nimport rospy\nimport _thread as thread\nfrom tf.transformations import quaternion_from_euler\nfrom tf.transformations import euler_from_quaternion\n\n\nimport mavros\nfrom mavros import setpoint as SP\nfrom mavros.utils import *\nfrom geometry_msgs.msg import PoseStamped\n\nimport numpy as np\n\n###Value of pose\n\ntarget=PoseStamped()\n\n####Value received by the T camera \nfrom nav_msgs.msg import Odometry\n\n\n# Params\nproximity = 0.1 # metres\n\n# Variable\nsetpoints=np.array([0,0,0,0])\n\n\nFirstTarget = True\notx, oty, otz, oth = (0.0,0.0,0.0,0.0)\ntx, ty, tz, th = (0.0,0.0,0.0,0.0)\ncx, cy, cz, ch = (0.0,0.0,0.0,0.0)\nhx, hy, hz=(0.0,0.0,0.0)\n\nreached = True\nmoving = False\n\ndef posUpdate(msg):\n global reached\n global state\n global hx,hy,hz\n global proximity\n global otx, oty, otz\n\n hx = msg.pose.position.x\n hy = msg.pose.position.y\n hz = msg.pose.position.z\n dist = sqrt(pow(hx-otx, 2) + pow(hy-oty, 2) + pow(hz-otz, 2))\n # reached = (dist <= proximity)\n # reached = True\n\ndef follow_point():\n rospy.init_node('set_local_setpoint', anonymous=True)\n mavros.set_namespace() # initialize mavros module with default namespace\n sub = rospy.Subscriber(mavros.get_topic('local_position', 'pose'), SP.PoseStamped, posUpdate, queue_size=1)\n \n pub = SP.get_pub_position_local(queue_size=1)\n rospy.Subscriber('target_pose',PoseStamped,target_callback,queue_size=1)\n rate=rospy.Rate(10)#delay \n while not rospy.is_shutdown():\n pub.publish(Command())\n # print(angles)\n rate.sleep() \n\n \n\ndef target_callback(aruco):\n global target\n global setpoints\n target=aruco\n target_x=target.pose.position.x\n target_y=target.pose.position.y\n target_z=target.pose.position.z\n ##The orientation for the target is [roll,pitch,yaw,yaw] in eulers\n target_yaw=target.pose.orientation.z\n setpoints=[target_x,target_y,target_z,target_yaw]\n # print(setpoints)\n\n\ndef Command():\n global hx,hy,hz\n #print(hx,hy,hz)\n global setpoints\n msg = SP.PoseStamped(\n header=SP.Header(\n frame_id=\"base_footprint\", # no matter, plugin don't use TF\n stamp=rospy.Time.now()), # stamp should update\n )\n ##camera position (0.08,0.0,0.11)\n msg.pose.position.x = -hx-(setpoints[1])\n msg.pose.position.y = hy-(setpoints[0]-0.08)\n # print(hx,setpoints[0],msg.pose.position.x)\n # msg.pose.position.z = setpoints[2]\n msg.pose.position.z=1.5\n # yaw_degrees = setpoints[3] # North\n yaw_degrees = 90 # North\n yaw = radians(yaw_degrees)\n quaternion = quaternion_from_euler(0, 0, yaw)\n print(hx,hy,msg.pose.position.x,msg.pose.position.y)\n msg.pose.orientation = SP.Quaternion(*quaternion)\n return msg\n\nif __name__=='__main__':\n try: \n follow_point()\n except rospy.ROSInternalException:\n pass\n","repo_name":"rjros/offboard_control","sub_path":"offboard/scripts/offb_node_setpoints.py","file_name":"offb_node_setpoints.py","file_ext":"py","file_size_in_byte":3052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"71741440413","text":"#!/usr/bin/env python3\n\nimport sys\nimport os\nimport serial\nimport time\nimport argparse\n\ndef parse_args(args):\n args = args[1:] # args[0] is the called path\n\n parser = argparse.ArgumentParser(description=\"Pinky CPU programmer.\")\n\n parser.add_argument(\"input\", type=str, help=\"A file path to the single assembly file to program with.\")\n parser.add_argument(\"-B\", \"--binary\", action=\"store_true\", help=\"If the input is not an assemble file but an assembled binary.\")\n parser.add_argument(\"-p\", \"--port\", type=str, help=\"Serial port to send the binary to.\", default=\"/dev/ttyUSB1\")\n parser.add_argument(\"-b\", \"--baud\", type=int, help=\"The baud rate of the FPGA.\", default=115200)\n\n args = parser.parse_args(args)\n\n # Check if input file exists and is valid\n assert os.path.isfile(args.input), f\"File not found: '{os.path.realpath(args.input)}'\"\n\n return args\n\ndef main(args):\n args = parse_args(args)\n\n if args.binary:\n with open(args.input, 'rb') as f:\n bytes_to_send = f.read()\n else:\n bytes_to_send = pyas.assemble(args.input)\n\n bytes_to_send += (0).to_bytes(4, byteorder='big') # append 4 * 0x00 at the end, which is the \"END\" signal to the bootrom\n\n with serial.Serial(args.port, args.baud) as ser:\n for byte in bytes_to_send:\n ser.write(bytes([byte]))\n time.sleep(0.0002) # without sleep sending would collapse because Rx on FPGA can't handle it\n\n print('FPGA successfully programmed!')\n\nif __name__ == \"__main__\":\n try:\n import pyas\n except:\n raise ImportError(\"PYAS assembler is not installed on this system. Before using the Pinky programmer, please install PYAS assembler from: https://github.com/gaborpelesz/from-the-transistors/tree/main/assembler\")\n\n main(sys.argv)\n","repo_name":"gaborpelesz/from-the-transistors","sub_path":"cpu/program_fpga.py","file_name":"program_fpga.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"71871470175","text":"from pathlib import Path\nfrom typing import Type, TypeVar, Sequence\n\nfrom pydantic import BaseModel\nfrom slist import Slist\n\nGenericBaseModel = TypeVar(\"GenericBaseModel\", bound=BaseModel)\n\n\ndef caught_base_model_parse(\n basemodel: Type[GenericBaseModel], line: str\n) -> GenericBaseModel:\n try:\n return basemodel.parse_raw(line)\n except Exception as e:\n print(f\"Error parsing line: {line}\")\n raise e\n\n\ndef read_jsonl_file_into_basemodel(\n path: Path, basemodel: Type[GenericBaseModel]\n) -> Slist[GenericBaseModel]:\n with open(path, \"r\") as f:\n return Slist(\n caught_base_model_parse(basemodel=basemodel, line=line)\n for line in f.readlines()\n # filter for users\n )\n\n\ndef write_jsonl_file_from_basemodel(\n path: Path, basemodels: Sequence[BaseModel]\n) -> None:\n with open(path, \"w\") as f:\n for basemodel in basemodels:\n f.write(basemodel.json() + \"\\n\")\n","repo_name":"thejaminator/prompt_reward_rl","sub_path":"api/json_operations.py","file_name":"json_operations.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"28842678347","text":"import json\nimport time\nfrom pgvector.sqlalchemy import Vector\nfrom sentence_transformers import SentenceTransformer\nfrom sqlalchemy import create_engine, insert, select, text, Integer, String, Text\nfrom sqlalchemy.dialects.postgresql import JSONB\nfrom sqlalchemy.orm import declarative_base, mapped_column, Session\nfrom scipy import spatial\n\n# engine = create_engine('postgresql://postgres:postgres@localhost:5432/postgres')\nengine = create_engine('postgresql://postgres:postgres@db/postgres')\nwith engine.connect() as conn:\n conn.execute(text('CREATE EXTENSION IF NOT EXISTS vector'))\n conn.commit()\n\nBase = declarative_base()\n\n\nclass Document(Base):\n __tablename__ = 'document'\n\n id = mapped_column(Integer, primary_key=True)\n title = mapped_column(Text)\n data = mapped_column(JSONB)\n embedding = mapped_column(Vector(384))\nBase.metadata.drop_all(engine)\nBase.metadata.create_all(engine)\nmodel = SentenceTransformer('all-MiniLM-L6-v2')\n\nfile = open(\"/app/data/products.ndjson\", \"r\")\nsession = Session(engine)\n\ni = 0\nlimit = 20000\nbatch = []\nsentences = []\nfor line in file.readlines():\n item = json.loads(line)\n # batch embedding\n batch.append(item)\n sentences.append(f\"title: {item['title']} description: {item['description']}\")\n if len(batch) == limit:\n start = time.time()\n # print(\"Encoding batch #{}\".format(i))\n embeddings = model.encode(sentences)\n documents = [dict(title=batch[i][\"title\"], data=batch[i], embedding=embedding) for i, embedding in enumerate(embeddings)]\n result = session.execute(insert(Document), documents)\n # print(\"Committing batch\")\n session.commit()\n i += 1\n batch = []\n sentences = []\n end = time.time()\n print(\"Batch #{} ({} documents) took {} seconds\".format(i, limit * i, end - start))\n\n# model = SentenceTransformer('all-MiniLM-L6-v2')\n# embeddings = model.encode(sentences)\n# # print(embeddings)\n\n# documents = [dict(content=sentences[i], embedding=embedding) for i, embedding in enumerate(embeddings)]\n\n# session = Session(engine)\n# result = session.execute(insert(Document), documents)\n\n# session.commit()","repo_name":"WilliamRelken/ai-testing","sub_path":"py/embed.py","file_name":"embed.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"15026211663","text":"# -*- coding:utf-8 -*-\nimport threading\nimport time\n\n\ndef plus():\n print('------子线程1开始执行--------')\n global g_num\n g_num += 50\n print(f'g_num is {g_num} ')\n print('------------子线程1结束----------------')\n\n\ndef minus():\n time.sleep(1)\n print('------子线程2开始执行--------')\n global g_num\n g_num -= 50\n print(f'g_num is {g_num} ')\n print('------------子线程2结束----------------')\n\n# 定义一个全局变量\ng_num = 100\n\nif __name__=='__main__':\n print('------主线程开始执行--------')\n print(f'g_num is {g_num} ')\n # 实例化一个线程1\n t1 = threading.Thread(target=plus)\n # 实例化线程2\n t2 = threading.Thread(target=minus)\n t1.start()\n t2.start()\n t1.join()\n t2.join()\n print('------主线程结束执行--------')","repo_name":"BruceCC/python-in-action","sub_path":"thread/msgthread1.py","file_name":"msgthread1.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"18204040293","text":"\"\"\"\nhttps://leetcode.com/problems/summary-ranges/\nYou are given a sorted unique integer array nums.\n\nReturn the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.\n\nEach range [a,b] in the list should be output as:\n\n\"a->b\" if a != b\n\"a\" if a == b\n\n\nExample 1:\n\nInput: nums = [0,1,2,4,5,7]\nOutput: [\"0->2\",\"4->5\",\"7\"]\nExplanation: The ranges are:\n[0,2] --> \"0->2\"\n[4,5] --> \"4->5\"\n[7,7] --> \"7\"\nExample 2:\n\nInput: nums = [0,2,3,4,6,8,9]\nOutput: [\"0\",\"2->4\",\"6\",\"8->9\"]\nExplanation: The ranges are:\n[0,0] --> \"0\"\n[2,4] --> \"2->4\"\n[6,6] --> \"6\"\n[8,9] --> \"8->9\"\nExample 3:\n\nInput: nums = []\nOutput: []\nExample 4:\n\nInput: nums = [-1]\nOutput: [\"-1\"]\nExample 5:\n\nInput: nums = [0]\nOutput: [\"0\"]\n\n\nConstraints:\n\n0 <= nums.length <= 20\n-231 <= nums[i] <= 231 - 1\nAll the values of nums are unique.\nnums is sorted in ascending order.\n\nRuntime: 36 ms, faster than 32.80% of Python3 online submissions for Summary Ranges.\nMemory Usage: 14 MB, less than 75.44% of Python3 online submissions for Summary Ranges.\n\n\"\"\"\nfrom typing import List\n\nfrom Common.ObjectTestingUtils import run_functional_tests\n\n\n# Runtime: 29 ms, faster than 87.42% of Python3 online submissions for Summary Ranges.\n# Memory Usage: 13.9 MB, less than 88.25% of Python3 online submissions for Summary Ranges.\nclass Solution:\n def summaryRanges(self, nums: List[int]) -> List[str]:\n result: List[str] = []\n n = len(nums)\n start = None\n\n def appendRange(start: int, j: int):\n if start == nums[j]:\n result.append(str(nums[j]))\n else:\n result.append(str(start) + \"->\" + str(nums[j]))\n\n for i in range(n):\n if start is None:\n start = nums[i]\n elif nums[i] != nums[i-1] + 1:\n appendRange(start, i-1)\n start = nums[i]\n if start is not None:\n appendRange(start, n-1)\n return result\n\n\ntests = [\n [[0,1,2,4,5,7], [\"0->2\",\"4->5\",\"7\"]],\n [[0,2,3,4,6,8,9], [\"0\",\"2->4\",\"6\",\"8->9\"]],\n [[], []],\n [[-1], [\"-1\"]],\n [[0], [\"0\"]]\n]\n\nrun_functional_tests(Solution().summaryRanges, tests)\n","repo_name":"wtain/LeetCodePython","sub_path":"DataStructures/Basic/Arrays/Ranges/SummaryRanges.py","file_name":"SummaryRanges.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"33"} +{"seq_id":"36071881276","text":"#@author:Muhammed Nisamudheen\n#@version:3.7\n#@purpose: find the roots of the equation a*x*x + b*x + c\nimport math\nstr1=input(\"enter the equation\")\nlist1=str1.split('+')\nq=list1[0]\nw=q.split('x2')\na=int(w[0])\n\nq1=list1[1]\nw1=q1.split('x')\nb=int(w1[0])\n\nc=int(list1[2])\nprint (a,b,c)\n\ndelta = b*b - 4*a*c\nprint(delta)\nk=math.sqrt(delta)\nRoot1 = (-b + k)/(2*a)\nRoot2 = (-b - k)/(2*a)\nprint(Root1)\nprint(Root2)\n","repo_name":"amniz/samples","sub_path":"Functional/func15.py","file_name":"func15.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"9352770244","text":"from platform import python_version as y\n\nfrom pyrogram import __version__ as z\nfrom pyrogram import filters\nfrom pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup\nfrom telegram import __version__ as o\nfrom telethon import __version__ as s\n\nfrom Exon import app as pbot\n\nChadano = \"https://te.legra.ph/file/4f80999cd52a25557ae57.jpg\"\n\n\n@pbot.on_message(filters.command([\"repo\", \"source\"]))\nasync def repo(_, message):\n await message.reply_photo(\n photo=Chadano,\n caption=f\"\"\"✨ **ʜᴇʏ {message.from_user.mention},**\n\n**ʀᴇᴘᴏ ᴏᴡɴᴇʀ : [𝐀ʙɪꜱʜɴᴏɪ](https://t.me/plumblossomsword)**\n**ᴘʏᴛʜᴏɴ ᴠᴇʀꜱɪᴏɴ :** `{y()}`\n**ʟɪʙʀᴀʀʏ ᴠᴇʀꜱɪᴏɴ :** `{o}`\n**ᴛᴇʟᴇᴛʜᴏɴ ᴠᴇʀꜱɪᴏɴ :** `{s}`\n**ᴘʏʀᴏɢʀᴀᴍ ᴠᴇʀꜱɪᴏɴ :** `{z}`\n**ʙᴏᴛ ᴠᴇʀꜱɪᴏɴ :** `2.69`\n\"\"\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\n \"•ᴍᴜꜱɪᴄ•\", url=\"https://github.com/Void-Great-Emperor/YukkiMusicBot\"\n ),\n InlineKeyboardButton(\n \"•ᴋᴏᴍɪ•\", url=\"https://github.com/Void-Great-Emperor/KomiShouko\"\n ),\n ]\n ]\n ),\n )\n","repo_name":"thetrueheavensequal/Rimuru-Bot","sub_path":"Exon/modules/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"34412102674","text":"from random import randint\nfrom casino_exceptions import (\n NoPlayersError,\n PlayersListError,\n AddPlayerError,\n DeletePlayerError\n)\n\n\nclass Casino:\n \"\"\"\n Class Casino. Contains attributes:\n :param: _players\n :type _player: list\n \"\"\"\n\n def __init__(self, players=None):\n \"\"\"\n Creates instance of casino\n\n Raises NoPlayersError if there are no players\n Raises PlayersListError if the players are repeating\n \"\"\"\n if players:\n self._players = players\n else:\n raise NoPlayersError\n for player in players:\n if players.count(player) > 1:\n raise PlayersListError()\n\n def throw_dices(self):\n \"\"\"\n Returns a list of four randomly picked numbers from one to six\n \"\"\"\n diceees = []\n for dice in range(4):\n diceees.append(randint(1, 6))\n self._dices = diceees\n return self._dices\n\n def pick_winner(self):\n \"\"\"\n Picks winner based on the score of the player.\n If two or more players have the same score then returns string 'Game unresolved'\n \"\"\"\n max_score = 0\n for player in self._players:\n Player.set_score(player)\n if player._score == max_score:\n winner = 'Game unresolved'\n if player._score > max_score:\n max_score = player._score\n winner = player\n return winner\n\n def add_player(self, players_to_add):\n \"\"\"\n Adds players to casino.\n If the players are repeating then raises AddPlayerError\n \"\"\"\n for player in players_to_add:\n if player in self._players:\n raise AddPlayerError()\n self._players.append(player)\n\n def delete_player(self, players_to_delete):\n \"\"\"\n Removes players from the casino.\n If the players aren't in the casino raise DeletePlayerError\n \"\"\"\n for player in players_to_delete:\n if player in self._players:\n self._players.remove(player)\n else:\n raise DeletePlayerError()\n\n\nclass Player:\n def __init__(self, name=None):\n \"\"\"\n Class Casino. Contain attributes:\n :param: _name\n \"type name: str\n :param: _dices\n \"type name: list\n :param: _score\n \"type name: int\n \"\"\"\n self._name = name\n self._dices = []\n self._score = 0\n\n def dices(self):\n \"\"\"\n Sets the value of dices to thrown dices\n \"\"\"\n self._dices = Casino.throw_dices(self)\n\n def score(self):\n \"\"\"\n Returns the score of a player based on dices\n \"\"\"\n score_from_even_odd = 0\n score_from_set = 0\n my_list = [0, 0, 0, 0, 0, 0, 0]\n for number in self._dices:\n my_list[number] += 1\n max_element = 0\n my_iterator = 0\n for element in my_list:\n if element >= max_element:\n max_element = element\n number_of_dice = my_iterator\n my_iterator += 1\n\n for number in self._dices:\n if number % 2 == 0:\n is_even = True\n else:\n is_even = False\n break\n\n for number in self._dices:\n if number % 2 == 1:\n is_odd = True\n else:\n is_odd = False\n break\n if max_element == 2:\n score_from_set = 2 * number_of_dice\n if max_element == 3:\n score_from_set = 4 * number_of_dice\n if max_element == 4:\n score_from_set = 6 * number_of_dice\n if is_even:\n score_from_even_odd = sum(self._dices) + 2\n if is_odd:\n score_from_even_odd = sum(self._dices) + 3\n return max(score_from_even_odd, score_from_set)\n\n def set_score(self):\n \"\"\"\n Sets dices if the _dices are None type\n Sets score based on the function score\n \"\"\"\n if not self._dices:\n self._dices = Player.dices(self)\n self._score = Player.score(self)\n","repo_name":"filips750/pipr","sub_path":"lab6pd/casino.py","file_name":"casino.py","file_ext":"py","file_size_in_byte":4175,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"35466066294","text":"import sys\r\ninput = sys.stdin.readline\r\nfrom collections import deque\r\n\r\nn=int(input())\r\ngraph=[list(map(int, input().strip())) for _ in range(n)]\r\nvisited=[[False for _ in range(n)] for _ in range(n)]\r\nhouse=[]\r\n\r\ndx=[-1,1,0,0]\r\ndy=[0,0,-1,1]\r\n\r\ndef bfs(x,y):\r\n queue=deque()\r\n queue.append([x,y])\r\n graph[x][y]=0\r\n cnt=1\r\n\r\n while queue:\r\n x,y=queue.popleft()\r\n for i in range(4):\r\n nx, ny= x+dx[i], y+dy[i]\r\n if nx<0 or ny<0 or nx>=n or ny>=n or graph[nx][ny]==0:\r\n continue\r\n\r\n if graph[nx][ny]==1:\r\n graph[nx][ny]=0\r\n queue.append([nx,ny])\r\n cnt+=1\r\n\r\n return cnt\r\n\r\nfor i in range(n):\r\n for j in range(n):\r\n if graph[i][j]==1:\r\n house.append(bfs(i,j))\r\n\r\nprint(len(house))\r\nhouse.sort()\r\nfor i in house:\r\n print(i)","repo_name":"ssunbear/SW-Maestro-154algorithm","sub_path":"백준/Silver/2667. 단지번호붙이기/단지번호붙이기.py","file_name":"단지번호붙이기.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"18645915835","text":"import random as rd\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n#refrencess\n# https://matplotlib.org/stable/api/animation_api.html\n# https://stackoverflow.com/questions/44594887/how-to-update-plot-title-with-matplotlib-using-animation\n# https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html\n# https://realpython.com/introduction-to-python-generators/\n# https://matplotlib.org/stable/api/axis_api.html\n\n\n#generator swaper: swapps\ndef swap(A, i, j):\n if i != j:\n A[i], A[j] = A[j], A[i]\n\n#generator that yields the changed list after\n# https://realpython.com/introduction-to-python-generators/\n\n#Bubble sort just swaps bigger to higher place in list if the one occupying that space is smaler.\ndef bubblesort(_list_):\n if len(_list_) == 1:\n return\n swapped = True\n for i in range(len(_list_) - 1):\n if not swapped:\n break\n swapped = False\n for j in range(len(_list_) - 1 - i):\n if _list_[j] > _list_[j + 1]:\n swap(_list_, j, j + 1)\n swapped = True\n yield _list_\n\n#Insertion sort goes from left to right while checking if the one behind itself is smaler or larger if it's smaler\n#it will swap places and check again.\ndef insertionsort(_list_):\n for i in range(1, len(_list_)):\n j = i\n while j > 0 and _list_[j] < _list_[j - 1]:\n swap(_list_, j, j - 1)\n j -= 1\n yield _list_\n\n# https://www.geeksforgeeks.org/python-program-for-selection-sort/\n#switches places with the corect one for it's current place.\ndef selectionsort(_list_):\n if len(_list_) == 1:\n return\n for i in range(len(_list_)):\n minVal = _list_[i]\n minIdx = i\n for j in range(i, len(_list_)):\n if _list_[j] < minVal:\n minVal = _list_[j]\n minIdx = j\n yield _list_\n swap(_list_, i, minIdx)\n yield _list_\n\n# in if __name__ == \"__main__\" means that it won't be wrongfully triggred and will trigger on it's own (future proofing)\nif __name__ == \"__main__\":\n def input_func():\n global number\n try:\n number = int(input(\"Enter number of integers: \"))\n except ValueError:\n input_func()\n \n input_func()\n \n #defines and shuffles list\n _list_ = [x + 1 for x in range(number)]\n rd.shuffle(_list_)\n\n #generators chooser\n #uses true or false instead of try except\n # https://realpython.com/introduction-to-python-generators/\n chooser = True\n while chooser == True:\n choise = input(\"Bubble or insert or selection: \")\n if \"bubble\" in choise.lower():\n generator = bubblesort(_list_)\n chooser = False\n elif \"insert\" in choise.lower():\n generator = insertionsort(_list_)\n chooser = False\n elif \"selection\" in choise.lower():\n generator = selectionsort(_list_)\n chooser = False\n\n #figure and axis.\n # https://matplotlib.org/stable/api/axis_api.html\n fig, ax = plt.subplots()\n ax.set_title(\"bar\")\n\n #start bar plot.\n # https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html\n bar_rectangle = ax.bar(range(len(_list_)), _list_, align=\"edge\")\n\n #limit's\n ax.set_xlim(0, number)\n ax.set_ylim(0, int(1.07 * number))\n\n #text\n text = ax.text(0.02, 0.95, \"\", transform=ax.transAxes)\n\n #Define update by ticking the rectangle in zip with limit of val\n tick = [0]\n def update_fig(_list_, rectangle, tick):\n for rect, val in zip(rectangle, _list_):\n rect.set_height(val)\n tick[0] += 1\n \n #animation generating frames from the generator and changes \n # https://stackoverflow.com/questions/44594887/how-to-update-plot-title-with-matplotlib-using-animation\n # https://matplotlib.org/stable/api/animation_api.html\n anim = animation.FuncAnimation(fig, func=update_fig, fargs=(bar_rectangle, tick), frames=generator, interval=1, repeat=False)\n plt.show()\n \n \n#it's possible to count how much time and how manny itterations it loops through but i don't have time for that nor the knowhow","repo_name":"1sakp/Isak-P-lsson-TE20D-Kursolle","sub_path":"Programering 1/Slutuppg/Isak.Pålsson.py","file_name":"Isak.Pålsson.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"33786301166","text":"import argparse\nimport sys\n\nfrom slackbucket.config import MetaConfig\nfrom slackbucket.bucket import Bucket\n\n\ndef main(args):\n cfgs = MetaConfig(path=args.config)\n slack = cfgs.cfgs['cs-cofc'].slack\n b = Bucket(slack, cfgs.cfgs['cs-cofc'])\n try:\n b.start()\n except KeyboardInterrupt:\n b.stop()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(prog='bucket')\n parser.add_argument('-c', '--config', default='/usr/src/app/config.yaml', help='Config.yaml location')\n args = parser.parse_args()\n main(args)\n","repo_name":"pshahid/slackbucket","sub_path":"bucket.py","file_name":"bucket.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"34941933240","text":"import requests\nimport base64\nimport json\nimport time\nfrom flask import Blueprint, request\nfrom util.utils import reply_json, captureFace, get_time_gap, get_current_time, get_weighted_value\nfrom database.Working import Working\nfrom database.Emotions import Emotions\nfrom util.SC import SC\n\nemotions = Blueprint('emotions', __name__)\n\nclass FaceRecog:\n def __init__(self):\n # client_id is AK, client_secret is SK\n host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&' + SC[\n 'baidu_face']\n response = requests.get(host)\n if (response):\n res = response.json()\n self.access_token = res['access_token']\n else:\n print(\"error\")\n\n def recog(self, path):\n with open(path, \"rb\") as f: # to binary\n base64_data = base64.b64encode(f.read()) # base64 encode\n request_url = \"https://aip.baidubce.com/rest/2.0/face/v3/detect\"\n request_body = {\n \"image\": base64_data.decode(),\n \"image_type\": \"BASE64\",\n \"face_field\": \"expression,emotion\",\n \"face_type\": \"LIVE\"\n }\n jsonData = json.dumps(request_body)\n request_url = request_url + \"?access_token=\" + self.access_token\n headers = {'content-type': 'application/json'}\n response = requests.post(request_url,\n data=jsonData,\n headers=headers)\n return response\n\n\n@emotions.route('/getEmotion', methods=['GET'])\ndef getEmotion():\n # init working stat determination\n last_face_time = Emotions.get_last_timestamp()\n current_time = get_current_time()\n face_check_gap = current_time - last_face_time\n working_stat = Working.isWorking()\n\n # a expression map that help convert what in database to what in iot platform\n map = {\n \"angry\": 1,\n \"fear\": 2,\n \"sad\": 3,\n \"neutral\": 4,\n \"surprise\": 5,\n \"happy\": 6\n }\n\n # guess the most possible user emotion\n prob = [0, 0, 0, 0, 0, 0]\n\n res = [None, None, None]\n count = 0\n for i in range(5):\n if count >= 3:\n break\n captureFace()\n faceRe = FaceRecog()\n if not res:\n continue\n res[count] = faceRe.recog(\"picture/image.jpg\").json()\n count += 1\n\n if count == 0:\n return reply_json(0)\n\n # detect multiple frames of user photo, once detect a face, hasFace +=1\n hasFace = 0\n for i in range(count):\n if res[i]['result'] != None and res[i]['result']['face_num'] > 0 and res[i]['result']['face_list'][0]['face_probability']>=0.92:\n hasFace += 1\n ex = res[i]['result']['face_list'][0]['expression']['type']\n exp = res[i]['result']['face_list'][0]['expression']['probability']\n e = res[i]['result']['face_list'][0]['emotion']['type']\n p = res[i]['result']['face_list'][0]['emotion']['probability']\n if ex == 'smile' or ex == 'laugh':\n if exp >= 0.5:\n if e != 'happy':\n e = 'happy'\n p = exp\n # print(res[i])\n if e in map:\n prob[map[e] - 1] += get_weighted_value(p)\n else:\n prob[3] += get_weighted_value(p)\n\n # find the most possible emotion_id among multiple results\n emotion = 0\n init = 0.8\n if hasFace > 0:\n for i in range(len(prob)):\n if prob[i] > init:\n init = prob[i]\n emotion = i + 1\n if emotion == 0:\n emotion = 4\n if emotion != 0:\n print(\"emotion = \" + list(map.keys())[emotion - 1] + \"\\t\" + str(max(prob)))\n\n # stop last work, since user haveleft for more than 2 mins\n if working_stat and face_check_gap > 2*60:\n begin_time = working_stat.begin_time\n\n # stop too fast, delete\n if last_face_time - begin_time < 2*60:\n Working.delete(working_stat)\n else:\n if begin_time > last_face_time:\n print('ERROR!!!!!!!!!!!!!!!!work time larger than face time !!!!!!!!!!!!!!!!!!!!!!!')\n Working.stop_working(time=(begin_time+60*20))\n else:\n Working.stop_working(time=last_face_time)\n return reply_json(2)\n\n # if no face detected, means idle\n if hasFace < 1:\n res = requests.get('https://api.thingspeak.com/update?' +\n SC['thingspeak'] + 'field5=0')\n return reply_json(3)\n\n # if user haven't start working, then start work, since at least 1 face has been detected\n if not working_stat:\n working_stat = Working.begin_working()\n\n # put the expression data into database, now last face time should be current time\n Emotions.add(Emotions(list(map.keys())[emotion - 1],time=current_time))\n res = requests.get('https://api.thingspeak.com/update?' +\n SC['thingspeak'] + 'field1=' + str(emotion) +\n '&field5=1')\n\n # init pressure evaluation\n shouldRest = False\n rate = Emotions.get_depress_rate()\n begin_time = working_stat.begin_time\n work_duration = current_time - begin_time\n\n # if more than 20% of the expression captured are negative and user have worked more than 40mins, he/she should take a rest\n if rate > 0.1 and work_duration > 60*40:\n shouldRest = True\n \n # successfully detected face - working;\n return reply_json(1,\n data={\n 'emotion': list(map.keys())[emotion - 1],\n 'begin_time': begin_time,\n 'shouldRest':shouldRest\n })\n\n\n@emotions.route('/playSong', methods=['GET'])\ndef playSong():\n from util.buzzer import play_mario\n play_mario()\n return reply_json(1)\n\n\nif __name__ == \"__main__\":\n faceRe = FaceRecog()\n faceRe.recog(\"picture/image.jpg\")\n","repo_name":"KrisCris/COMP727","sub_path":"api/api/emotions.py","file_name":"emotions.py","file_ext":"py","file_size_in_byte":6020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"32435089959","text":"\"\"\" Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês\n\ndica: Para saber quanto o funcionário ganha por hora, basta dividir o salário dele por 220 horas que é sua carga horária mensal:\n44horas semanais x 5 semanas = 220.\n\"\"\"\nsalario = float(input('Digite seu salário:'))\n\nvalor_hora = salario / 220\n\nprint(f'Você ganha R${valor_hora:.2f} por hora')\n","repo_name":"heltonteixeira92/exercises-and-some-codes","sub_path":"python-brasil/estrutura-sequencial/8_calcula_quanto_ganho_por_hora.py","file_name":"8_calcula_quanto_ganho_por_hora.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"8894883723","text":"#! usr/bin/env python3\nimport praw\nimport time\nfrom twitter import *\n\n#Twitter Access Tokens\ntoken = ''\ntoken_secret = ''\nconsumer_key= ''\nconsumer_secret= ''\n\n#Reddit Access Tokens\nreddit = praw.Reddit(client_id='', \\\n client_secret='', \\\n user_agent='', \\\n username='', \\\n password='')\n\n#Customization\nsub_name = \"NBA\"\ndelay_of_tweets = 10\n \nsubreddit = reddit.subreddit(sub_name)\nnew_subreddit = subreddit.hot(limit=25)\n\n\ntwit = Twitter(\n auth=OAuth(token, token_secret, consumer_key, consumer_secret))\n\n#loops through top 25 hot posts and posts the urls to twitter every x amount of seconds\nfor new_submission in new_subreddit:\n if len(new_submission.url) < 140:\n twit.statuses.update(status=new_submission.url)\n time.sleep(delay_of_tweets)\n else:\n title = new_submission.url[:130] + \"...\"\n twit.statuses.update(status=title)\n","repo_name":"amsearles/Twitter-bot-scrapes-reddit","sub_path":"twitter_bot_reddit.py","file_name":"twitter_bot_reddit.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"6288776852","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n#1.length of a string\nstr=input(\"Enter a string \")\nprint(\"length os the input string is\",len(str))\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n#2.character frequency\ndef char_freq(str1):\n dict={ }\n for n in str1:\n keys=dict.keys()\n if n in keys:\n dict[n]+=1\n else:\n dict[n]=1\n return dict\nprint(char_freq('google.com'))\n \n\n\n# In[ ]:\n\n\n# 3.get a single string from two two string\ndef char_mix_up(a,b):\n new_a=b[:2]+a[2:]\n new_b=a[:2]+b[2:]\n return new_a+' '+new_b\nprint(char_mix_up('abc','xyz'))\n\n\n# In[ ]:\n\n\n#4,upper case and lower case\na=input(\"Python is a user Interface landuage \")\nprint(\"Python is a user Interface language\",a.upper())\nprint(\"Python is a user Interface language\",a.lower())\n\n\n# In[ ]:\n\n\n#5.remove new line in python\nstr1='python exercise\\n'\nprint(str1)\nprint(str1.rstrip())\n\n\n# In[ ]:\n\n\n#6.to count accurrence of a substring\nstr1='corna is came from chaina'\nprint()\nprint(str1.count(\"from\"))\nprint()\n\n\n# In[ ]:\n\n\n#7.string into a list\nstr1='apple,mango,stwarberry'\nprint(f'list of items={str1.split(\",\")}')\n\n\n# In[ ]:\n\n\n#8.delete a character\na=[2,3,4,5,6]\ndel a[1:2]\nprint(a)\n\n\n# In[ ]:\n\n\n#9.print string using loop\nx=input(\"enter the string\")\nfor i in x:\n print(i)\n\n\n# In[ ]:\n\n\n#10.finding length without using len()\na=\"python\"\ncount=0\nfor i in a:\n count=count+1\nprint(count)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"sps2001/home.5","sub_path":"home.5.py","file_name":"home.5.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"34268663898","text":"from sys import exit\n\nfrom list_node import ListNode\nfrom test_framework import generic_test, test_utils\n\n\ndef reverse_sublist(L, start, finish):\n\tif start == finish:\n\t\treturn L\n\n\tfakehead = pre = ListNode(None, L)\n\tdist = finish - start\n\n\twhile (start - 1):\n\t\tpre = pre.next\n\t\tstart -= 1\n\n\tpost = pre.next\n\n\twhile dist:\n\t\tdist -= 1 \n\t\ttoSwap = post.next\n\t\tpost.next = toSwap.next\n\t\ttoSwap.next = pre.next\n\t\tpre.next = toSwap\n\n\treturn fakehead.next\n\n\nif __name__ == '__main__':\n exit(\n generic_test.generic_test_main(\"reverse_sublist.tsv\", reverse_sublist))\n","repo_name":"prepperoni/Prep","sub_path":"EPIJudge/epi_judge_python/reverse_sublist.py","file_name":"reverse_sublist.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"69985797214","text":"import sys\nimport pathlib\nimport yaml\n\nfrom papr.lib.config import Config\nfrom papr.lib.repository import Repository, DATA_PATH, META_FILE, path_for_paper_data\nfrom .v1_repository import RepositoryV1, REPO_META\n\n\ndef assert_migration_not_needed(conf: Config):\n if _migration_needed(conf):\n print(\"Migration needed.\")\n print(\"Start 'papr migrate' first.\")\n sys.exit(1)\n\n\ndef do_migration(conf: Config):\n if not _migration_needed(conf):\n print(\"Migration not needed.\")\n sys.exit(1)\n print(\"Migrating database... please wait and do not interrupt this process.\")\n _do_migration(RepositoryV1(conf), conf)\n print(\"DONE. You can now use papr.\")\n\n\ndef _migration_needed(conf: Config):\n r = Repository(conf)\n return not r.is_v2_repo()\n\n\ndef _write_file(path, filename, data):\n path.mkdir(parents=True, exist_ok=True)\n p = path.joinpath(filename)\n with open(p, \"wt\") as f:\n f.write(data)\n\n\ndef _do_migration(repo: RepositoryV1, conf: Config):\n repo_path = pathlib.Path(repo.pdf_path())\n data_path = repo_path.joinpath(DATA_PATH) # for notes, summaries and metadata\n data_path.mkdir(parents=True, exist_ok=True)\n\n v2 = Repository(conf)\n\n for paper_v1 in repo.list():\n # path = /data/p00000_title_of_paper/\n path = path_for_paper_data(paper_v1, data_path)\n if paper_v1.has_summary():\n _write_file(path, \"summary.md\", paper_v1.summary())\n paper_v2 = v2.get_paper(paper_v1.idx())\n paper_v2.set_has_summary(True)\n v2.update_paper(paper_v2)\n if paper_v1.has_notes():\n _write_file(path, \"notes.md\", paper_v1.msg())\n paper_v2 = v2.get_paper(paper_v1.idx())\n paper_v2.set_has_notes(True)\n v2.update_paper(paper_v2)\n\n # store repository version into a file /.paper/meta.yml\n meta_path = repo_path.joinpath(REPO_META).joinpath(META_FILE)\n data = {\n \"repo_version\": \"2\"\n }\n with open(meta_path, \"wt\") as f:\n yaml.dump(data, f)\n","repo_name":"daniel-e/papr","sub_path":"papr/lib/migration/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"33"} +{"seq_id":"15712062046","text":"#!/usr/bin/env python3\n# coding: utf-8 -*-\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom gpkit import Variable, Model\nfrom scipy.optimize import minimize\n\nplotsDir = 'plots/'\n\nP = 32. # Payload [byte]\nR = 31.25 # CC2420 Radio Rate [kbyte/s = Byte/ms]\nD = 8 # number of levels\nC = 5 # neighbors size (connectivity)\nN = C*D**2 # number of nodes\n\nL_pbl = 4. # preamble length [byte]\nL_hdr = 9. + L_pbl # header length [byte]\nL_ack = 9. + L_pbl # ACK length [byte]\nL_ps = 5. + L_pbl # preamble strobe length [byte]\n\nTal = 0.95 # ack listen period [ms]\nThdr = L_hdr/R # header transmission duration [ms]\nTack = L_ack/R # ACK transmission duration [ms]\nTps = L_ps/R # preamble strobe transmission duration [ms]\nTcw = 15*0.62 # Contention window size [ms]\nTcs = 2.60 # Time [ms] to turn the radio into TX and probe the channel (carrier sense)\nTdata = Thdr + P/R + Tack # data packet transmission duration [ms]\n\nTw_max = 500. # Maximum Duration of Tw in ms\nTw_min = 100. # Minimum Duration of Tw in ms\n\ndef getAlphas(Fs) -> (float, float, float):\n d = 1 # where energy is maximized (worst-case scenario)\n I = (2*d+1)/(2*d-1)\n Fi = Fs*((D**2 - d**2)/(2*d - 1))\n Fout = Fi + Fs\n Fb = (C - I)*Fout\n alpha1 = Tcs + Tal + (3/2)*Tps*((Tps + Tal)/2 + Tack + Tdata)*Fb\n alpha2 = Fout/2\n alpha3 = ((Tps+Tal)/2 + Tcs + Tal + Tack + Tdata)*Fout + ((3/2)*Tps + Tack + Tdata)*Fi + (3/4)*Tps*Fb\n return (alpha1, alpha2, alpha3)\n\ndef computeEnergy(Fs):\n alpha1, alpha2, alpha3 = getAlphas(Fs)\n def go(Tw):\n return alpha1/Tw + alpha2*Tw + alpha3\n return go\n\ndef computeDelay(Tw, Fs):\n d = D # where delay is maximized (worst-case scenario)\n beta1 = 0.5*d\n beta2 = (Tcw/2 + Tdata)*d\n return beta1*Tw + beta2\n\ndef exercise1():\n Fss = list(map(lambda x: 1.0/(x*60*1000), [1.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0]))\n Tws = list(np.linspace(Tw_min, Tw_max, num=20))\n arr = np.zeros((len(Fss),(len(Tws)), 2), dtype=float)\n for i, Fs in enumerate(Fss):\n for j, Tw in enumerate(Tws):\n arr[i,j, 0] = computeEnergy(Fs)(Tw)\n arr[i,j, 1] = computeDelay(Tw, Fs)\n # Plotting\n for i, subArr in enumerate(arr):\n fig, axs = plt.subplots(1, 4, figsize=(12, 3))\n # Fig 1\n axs[0].plot(Tws, subArr[:, 0], color='blue')\n axs[0].set_xlabel('$T_w$(ms)')\n axs[0].set_ylabel('Energy(J)')\n axs[0].set_title('Energy ~ $T_w$')\n # Fig 2\n axs[1].plot(Tws, subArr[:, 1], color='red')\n axs[1].set_xlabel('$T_w$(ms)')\n axs[1].set_ylabel('Delay(ms)')\n axs[1].set_title('Delay ~ $T_w$')\n # Fig 3\n axs[2].set_xlabel('$T_w$(ms)')\n axs[2].set_ylabel('Energy(J)')\n l1, = axs[2].plot(Tws, subArr[:, 0], color='blue', label='Energy')\n axcopy = axs[2].twinx()\n axcopy.set_ylabel('Delay(ms)')\n l2, = axcopy.plot(Tws, subArr[:, 1], color='red', label='Delay')\n plt.legend((l1, l2), (l1.get_label(), l2.get_label()), loc='upper left')\n # Fig 4\n axs[3].plot(subArr[:, 0], subArr[:, 1], color='black')\n axs[3].set_xlabel('Energy(J)')\n axs[3].set_ylabel('Delay(ms)')\n axs[3].set_title('Energy ~ Delay')\n # Plot\n fig.suptitle('XMAC: energy vs. delay', fontsize=12)\n fig.tight_layout()\n fp = plotsDir + 'exercise_1_{}.png'.format(str(i))\n fig.savefig(fp)\n print(f'(Exercise 1) {fp} written succesfully.')\n\ndef bottleneckConstraint(Fs, Tw: Variable):\n # Since the difference between ceiling and not ceiling is minimal, wlog we remove the ceiling.\n Ttx = (Tw/2)+Tack+Tdata\n I = C # If d=0 then I_d = C\n Fout1 = Fs*(D**2) # Fs*((D**2 - d**2 + 2*d - 1)/(2*d - 1)) where d = 1\n Etx1 = (Tcs + Tal + Ttx)*Fout1\n return I*Etx1 <= 1/4\n\ndef p1(Fs, Lmax) -> float:\n \"\"\"\n minimize E\n\n subject to:\n L <= L_{max}\n T_w >= T_w^{min}\n |I^0|*E_{tx}^1 <= 1/4\n\n var. Tw\n \"\"\"\n Tw = Variable('Tw')\n objective = computeEnergy(Fs)(Tw)\n constraints = [ computeDelay(Tw, Fs) <= Lmax\n , Tw >= Tw_min\n , bottleneckConstraint(Fs, Tw)\n ]\n m = Model(objective, constraints)\n # m.debug() # Some problems are not feasible\n try:\n sol = m.solve(verbosity=0)\n return round(sol['variables'][Tw], 1)\n except Exception:\n return None\n\ndef p2(Fs, Ebudget) -> float:\n \"\"\"\n minimize L\n\n subject to:\n E <= E_{budget}\n T_w >= T_w^{min}\n |I^0|*E_{tx}^1 <= 1/4\n\n var. Tw\n \"\"\"\n Tw = Variable('Tw')\n objective = computeDelay(Tw, Fs)\n constraints = [ computeEnergy(Fs)(Tw) <= Ebudget\n , Tw >= Tw_min\n , bottleneckConstraint(Fs, Tw)\n ]\n m = Model(objective, constraints)\n sol = m.solve(verbosity=0)\n # m.debug() # Some problems are not feasible\n try:\n sol = m.solve(verbosity=0)\n # Rouding to avoid numerical problems\n return round(sol['variables'][Tw], 1)\n except Exception:\n return None\n\ndef exercise2():\n Fs = 1.0/(30.0*60.0*1000.0) # arbitrary\n Lmaxs = np.linspace(500.0, 3000.0, num=20)\n Ebudgets = np.linspace(0.1, 3.0, num=20)\n Tws1 = np.fromiter(map(lambda Lmax: p1(Fs, Lmax), Lmaxs), dtype=float)\n Tws2 = np.fromiter(map(lambda Ebudget: p2(Fs, Ebudget), Ebudgets), dtype=float)\n # Plotting\n fig, (ax1, ax2) = plt.subplots(1, 2)\n # Fig 1\n ax1.plot(Lmaxs, Tws1, color='blue')\n ax1.set_xlabel('$L_{max}$(ms)')\n ax1.set_ylabel('$T_w$(ms)')\n ax1.set_title('$T_w$ optimized (w.r.t. energy)')\n # Fig 2\n ax2.plot(Ebudgets, Tws2, color='blue')\n ax2.set_xlabel('$E_{budget}$(J)')\n ax2.set_ylabel('$T_w$(ms)')\n ax2.set_title('$T_w$ optimized (w.r.t. delay)')\n # Plot\n fig.suptitle('XMAC: optimization', fontsize=12)\n fig.tight_layout()\n fp = plotsDir + 'exercise_2.png'\n fig.savefig(fp)\n print(f'(Exercise 2) {fp} written succesfully.')\n\ndef exercise3():\n Fs = 1.0/(30.0*60.0*1000.0) # arbitrary\n # Constants\n Eworst = computeEnergy(Fs)(Tw_min)\n Lworst = computeDelay(Tw_max, Fs)\n # Variables:\n # x[0] = Tw\n # x[1] = E_1\n # x[2] = L_1\n def objective(x):\n E_1 = x[1]\n L_1 = x[2]\n return - np.log(Eworst - E_1) - np.log(Lworst - L_1)\n def constraints(x):\n Tw = x[0]\n E_1 = x[1]\n L_1 = x[2]\n E = computeEnergy(Fs)(Tw)\n L = computeDelay(Tw, Fs)\n return [ Eworst - E\n , E_1 - E\n , Lworst - L\n , L_1 - L\n , Tw - Tw_min\n , bottleneckConstraint(Fs, Tw)\n ]\n x0 = np.array([300.0, 0.02, 1000.0])\n ineq_cons = { 'type' : 'ineq',\n 'fun': constraints}\n res = minimize(objective, x0, method='SLSQP', constraints=[ineq_cons], options={'ftol': 1e-9, 'disp': False})\n p = round(res['x'][0], 2)\n print(f'(Exercise 3) Tw* = {p} milliseconds w.r.t. energy/delay')\n\nif __name__==\"__main__\":\n if not os.path.exists('plots'):\n os.makedirs('plots')\n exercise1()\n exercise2()\n exercise3()\n","repo_name":"monadplus/TOML","sub_path":"project1/code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7313,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"26804454496","text":"#\n#\n#\n\n#variable naming conventions\n#1) Every class or function first letter of each word is capital\n#2) For variables do not use capital letters\n#3) If there are more than one word seperate them by _ \n#4) For clases and functions first letter of each word is capital\n#4) Reference to the current instance of the class allways should be self\n#5) Each class and function should have an explanation\n\nimport numpy as np\nimport pandas as pd\n\nclass Data_Manager:\n def __init__(self, filename, country = '', province_state = '', min_confirmed=0,min_deaths=0):\n ###Mandatory inputs\n self.filename = filename #Name of the input file\n self.country = country\t\t#Name of the country as it is displayed in the file\n self.province_state = province_state\n self.min_confirmed = min_confirmed\n self.min_deaths = min_deaths\n\n self.data = pd.read_csv(filename)\n self.data = self.data.replace(np.nan, 'NA', regex=True)\n\n def Set_Country(self, country):\n self.country = country\n\n def Set_Province_State(self, province_state):\n self.province_state = province_state\n\n def Set_Min_Confirmed(self, min_param):\n self.min_confirmed = min_param\n\n def Set_Min_Deaths(self, min_param):\n self.min_deaths = min_param\n\n def Get_Total_Confirm(self):\n if (self.country == ''):\n print('Error : Set the country using Set_Country()')\n return 0\n if (self.province_state == ''):\n print('Error : Set the province or state using Set_Country()')\n print('If there is no state set it to NA ')\n return 0\n df = self.data.loc[(self.data['Country_Region'] == self.country) & (self.data['Province_State'] == self.province_state) & (self.data['Total_confirm'] >= self.min_confirmed) & (self.data['Total_death'] >= self.min_deaths) ]\n df = df.loc[df['Total_confirm'] != 'NA']\n return np.array(df.Date.values), np.array(df.Total_confirm.values)\n\n \n def Get_New_Confirm(self):\n if (self.country == ''):\n print('Error : Set the country using Set_Country()')\n return 0\n if (self.province_state == ''):\n print('Error : Set the province or state using Set_Country()')\n print('If there is no state set it to NA ')\n return 0\n\n df = self.data.loc[(self.data['Country_Region'] == self.country) & (self.data['Province_State'] == self.province_state) & (self.data['Total_confirm'] >= self.min_confirmed) & (self.data['Total_death'] >= self.min_deaths)]\n df = df.loc[(df['new_confirm'] != 'NA')]\n #df['Date'] = pd.to_datetime(df['Date'], format=\"%m/%d/%y\")\n return np.array(df.Date.values), np.array(df.new_confirm.values)\n\n\n def Get_Total_Death(self):\n if (self.country == ''):\n print('Error : Set the country using Set_Country()')\n return 0\n if (self.province_state == ''):\n print('Error : Set the province or state using Set_Country()')\n print('If there is no state set it to NA ')\n return 0\n\n df = self.data.loc[(self.data['Country_Region'] == self.country) & (self.data['Province_State'] == self.province_state)& (self.data['Total_confirm'] >= self.min_confirmed) & (self.data['Total_death'] >= self.min_deaths)]\n df = df.loc[(df['Total_death'] != 'NA')]\n #df['Date'] = Get_Whatever_Date(df['Date'])\n return np.array(df.Date.values), np.array(df.Total_death.values)\n\n\n def Get_New_Death(self):\n if (self.country == ''):\n print('Error : Set the country using Set_Country()')\n return 0\n if (self.province_state == ''):\n print('Error : Set the province or state using Set_Country()')\n print('If there is no state set it to NA ')\n return 0\n\n df = self.data.loc[(self.data['Country_Region'] == self.country) & (self.data['Province_State'] == self.province_state) & (self.data['Total_confirm'] >= self.min_confirmed) & (self.data['Total_death'] >= self.min_deaths) ]\n df = df.loc[(df['new_death'] != 'NA')]\n #df['Date'] = Get_Whatever_Date(df['Date'])\n return np.array(df.Date.values), np.array(df.new_death.values)\n\n def Get_Population(self):\n if (self.country == ''):\n print('Error : Set the country using Set_Country()')\n return 0\n if (self.province_state == ''):\n print('Error : Set the province or state using Set_Country()')\n print('If there is no state set it to NA ')\n return 0\n\n df = self.data.loc[(self.data['Country_Region'] == self.country) & (self.data['Province_State'] == self.province_state)]\n if (len(np.array(df.PopTotal.unique())) > 1):\n print('Warning, more than one record for the total population found.')\n return np.array(df.PopTotal.unique())\n\n def Get_Pop_Density(self):\n if (self.country == ''):\n print('Error : Set the country using Set_Country()')\n return 0\n if (self.province_state == ''):\n print('Error : Set the province or state using Set_Country()')\n print('If there is no state set it to NA ')\n return 0\n \n df = self.data.loc[(self.data['Country_Region'] == self.country) & (self.data['Province_State'] == self.province_state)]\n if (len(np.array(df.PopDensity.unique())) > 1):\n print('Warning, more than one record for population density found.')\n return np.array(df.PopDensity.unique())\n\n def Get_Available_Countries(self):\n #Returns a numpy array of available countries\n return np.array(self.data.Country_Region.unique())\n\n def Get_Province_State(self):\n #Returns a numpy array of all Province/State of a listed country.\n #If a country is not set it will generate an Warning\n if self.country == '':\n print('Warning !!!!!!!!!!!!!!')\n print('Country is not defined. Function is returning Province/State for all countries')\n state = np.array(self.data.Province_State.unique())\n else :\n country_data = self.data.loc[(self.data['Country_Region'] == self.country)]\n state = np.array(country_data.Province_State.unique())\n if len(state) <= 0:\n print('Warning !!!!!!!!')\n print('No States for the selecte country')\n return state\n \n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"udaraabeysekara/ModelValidation","sub_path":"datamanager.py","file_name":"datamanager.py","file_ext":"py","file_size_in_byte":5986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"14330399950","text":"import pygame\n\n\nclass Ball():\n #storage vars\n diameter = 0\n color = (0,0,0)\n ballPos = ballX, ballY = 0, 0\n speedX = 0\n speedY = 0\n\n moveLeft = True\n moveDown = True\n\n\n #collision detection vars\n rectWidth = 0\n rectHeight = 0\n gameRect = pygame.Rect(ballX, ballY, rectWidth, rectHeight)\n\n def __init__(self):\n self.ballPos = self.ballX, self.ballY = 350, 250\n self.diameter = 10\n self.color = (255,0,0)\n self.speedX = .05\n self.speedY = .05\n\n\n self.rectWidth = 10\n self.rectHeight = 10\n\n def move_ball(self): \n #\n #if(self.moveLeft):\n #self.ballX -= self.speedX\n #else:\n #self.ballX += self.speedX\n \n if(self.moveDown):\n self.ballY += self.speedY\n else:\n self.ballY -= self.speedY\n\n #update gameRect with new var\n self.ballPos = self.ballX, self.ballY\n self.gameRect = pygame.Rect(self.ballX, self.ballY, self.rectWidth, self.rectHeight)\n \n #this funct may be unnecesary after pong, keeping just incase\n def ball_reset(self):\n self.ballPos = self.ballX, self.ballY = 350, 250\n self.gameRect = pygame.Rect(self.ballX, self.ballY, self.rectWidth, self.rectHeight)\n \n \n def setStartPos(self, x, y):\n self.ballX = x\n self.ballY = y\n\n #update gameRect, not sure if I have to actually do this\n self.gameRect = pygame.Rect(self.ballX, self.ballY, self.rectWidth, self.rectHeight)\n def setSpeed(self, speed):\n self.speedY = speed\n ","repo_name":"adw9/CPSC-4160-HardestGame","sub_path":"ball.py","file_name":"ball.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"23643553954","text":"import gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\n\n# use creds to create a client to interact with the Google Drive API\nscope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\ncreds = ServiceAccountCredentials.from_json_keyfile_name('data.json', scope)\nclient = gspread.authorize(creds)\n\n# Find a workbook by name and open the first sheet\nsheet = client.open(\"deep\").sheet1\n\n# Extract and print all of the values\nlist_of_hashes = sheet.get_all_records()\n\ninfo = sheet.get_all_values()\n\nc=len(info)+1\nrows=[]\n\nwith open('k1.csv', 'r') as csvfile:\n # creating a csv reader object\n csvreader = csv.reader(csvfile)\n fields = csvreader.next()\n for row in csvreader:\n rows.append(row)\n\nfor i in rows:\n\tsheet.update_cell(c, 1, i)\n\tc = c+1\n\n","repo_name":"geethika234/alleviate_depression","sub_path":"cloud.py","file_name":"cloud.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"19640435740","text":"class Category():\n ID_SET = set()\n ID_TO_NAME = dict()\n ID_TO_PROMPT = dict()\n ID_TO_PARENT_ID = dict()\n ID_TO_OBJ = dict()\n\n def __init__(self, name, id, parent_id, prompt):\n self.name = name\n self.id = id\n self.parent_id = parent_id\n self.prompt = prompt\n\n if id in self.ID_SET:\n raise Exception('id {} has been all ready created'.format(id))\n \n self.ID_SET.add(id)\n self.ID_TO_NAME[id] = name\n self.ID_TO_PROMPT[id] = prompt\n self.ID_TO_PARENT_ID[id] = parent_id\n self.ID_TO_OBJ[id] = self\n self.parent = self.ID_TO_OBJ[parent_id]\n\ndef make_hierachy():\n Category(name='Категория', id=0, parent_id=0, prompt='\\\"see you\\\" title, early 3D computer art')\n Category(name='Спорт', id=1, parent_id=0 , prompt='some sport, marble sculpture')\n Category(name='Игры', id=2, parent_id=0, prompt='a some computer game, made from glowing multicolored luminescent particles, digital art')\n Category(name='Концерты', id=3, parent_id=0 , prompt='a piano, digital art, op art')\n Category(name='Активный отдых', id=4, parent_id=0 , prompt='an astronaut, by Stephan Martiniere')\n Category(name='Мастер классы', id=5, parent_id=0 , prompt='the discovery of gravity, painting from the 17th century')\n Category(name='Искусство', id=6, parent_id=0 , prompt='a horse, in the topiary shape')\n\n Category(name='Футбол', id=7, parent_id=1 , prompt='A man kicks a penalty at the goal where the goalkeeper stands during a football match, high quality image, Cinematic Lighting, 85mm, Polaroid')\n Category(name='Баскетбол', id=8, parent_id=1 , prompt='Basketball player doing a slam dunk, high quality image, Cinematic Lighting, Art Deco print')\n Category(name='Легкая атлетика', id=9, parent_id=1 , prompt='Man running around the stadium, dressed in sports clothes, sneakers on his feet, high quality image, Autochrome, 85mm, Studio Lighting, Studio Lighting')\n","repo_name":"valerapon/dalle_generator","sub_path":"src/dicts.py","file_name":"dicts.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"32341327320","text":"import requests\nimport bs4\nimport json\nimport time\n\n\ndef get_torrents_of_page(login, page_num):\n doc = bs4.BeautifulSoup(login.session.get(login.url + \"&page=\" + str(page_num),\n headers=login.headers, cookies=login.cookies).text, 'html5lib')\n torrents_tag = doc.select(\"table.torrents > tbody > tr.free_bg\")\n torrents = []\n torrent_info_name = ['type', 'title', 'comment', 'upload_time', 'size', 'uploader', 'downloader', 'complete']\n for torrent_tag in torrents_tag:\n torrent_info = torrent_tag.select(\" > td\")\n tmp = {}\n for i in range(len(torrent_info_name)):\n if i == 0:\n tmp[torrent_info_name[i]] = torrent_info[i].find(\"img\")[\"alt\"]\n else:\n tmp[torrent_info_name[i]] = torrent_info[i].get_text()\n tmp['download_link'] = \"http://bt.byr.cn/\" + torrent_tag.find(attrs={\"title\": \"下载本种\"}).parent[\"href\"]\n torrents.append(tmp)\n return torrents\n\n\ndef get_torrents(login):\n torrents = []\n with open(\"config.json\") as f:\n page_num = json.load(f)[\"page_num\"]\n for i in range(page_num):\n torrents.extend(get_torrents_of_page(login, i))\n time.sleep(0.2)\n for torrent in torrents:\n torrent[\"uploader\"] = int(torrent[\"uploader\"])\n torrent[\"downloader\"] = int(torrent[\"downloader\"])\n torrent[\"comment\"] = int(torrent[\"comment\"])\n torrent[\"complete\"] = int(torrent[\"complete\"].replace(',', ''))\n size = torrent[\"size\"]\n if size[-2] == 'K':\n size = float(size[0:-2]) / (1024 * 1024)\n elif size[-2] == 'M':\n size = float(size[0:-2]) / 1024\n elif size[-2] == 'T':\n size = float(size[0:-2]) * 1024\n else:\n size = float(size[0:-2])\n torrent[\"size\"] = size\n return torrents\n","repo_name":"ruiwu-bupt/byrbt-uploader","sub_path":"get_resource.py","file_name":"get_resource.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"286733089","text":"import itertools\n\nimport networkx as nx\n\nfrom mamoge.taskplanner.location import GPSLocation, NXLayerLocation\n\n\ndef G_routemap_fully_connected(nodes):\n graph = nx.Graph()\n\n # print(\"-----------------\")\n # print(nodes)\n # print(\"0-00000000000000000\")\n for (i, n_i), (j, n_j) in itertools.combinations(nodes, 2):\n # print(\"ij\", i, j, ni, nj)\n graph.add_node(i,\n name=f'{i}',\n layer=1,\n location=GPSLocation(latitude=n_i[\"latitude\"],\n longitude=n_i[\"longitude\"],\n altitude=n_i[\"altitude\"]))\n graph.add_node(j,\n name=f'{j}',\n layer=1,\n location=GPSLocation(latitude=n_j[\"latitude\"],\n longitude=n_j[\"longitude\"],\n altitude=n_i[\"altitude\"]))\n graph.add_edge(i, j)\n\n return graph\n\n\ndef DAG_all_parallel(G_routemap, base_id, nodes):\n print(\"DAG_all_parallel\", base_id)\n digraph_tasks = nx.DiGraph()\n digraph_tasks.graph[\"crs\"] = \"epsg:4326\"\n\n task_base_id = \"START_base\"\n digraph_tasks.add_node(task_base_id,\n name=\"start\",\n layer=0,\n location=NXLayerLocation(layer_id=task_base_id,\n base_id=base_id,\n G_layer=digraph_tasks,\n G_base=G_routemap,\n name=f\"{base_id}\"))\n\n for n_id, n in nodes:\n g_ref = G_routemap.nodes[n_id]\n task_id = f\"{n_id}\"\n digraph_tasks.add_node(task_id,\n name=task_id,\n layer=1,\n location=NXLayerLocation(layer_id=task_id,\n base_id=n_id,\n G_layer=digraph_tasks,\n G_base=G_routemap,\n name=g_ref[\"name\"]))\n digraph_tasks.add_edge(task_base_id, task_id)\n\n end_id = \"END_base\"\n\n digraph_tasks.add_node(end_id,\n name=\"end\",\n layer=2,\n location=NXLayerLocation(layer_id=end_id,\n base_id=base_id,\n G_layer=digraph_tasks,\n G_base=G_routemap,\n name=f\"{base_id}\"))\n [digraph_tasks.add_edge(task_id, end_id) for task_id in list(digraph_tasks.nodes)[1:-1]]\n\n return digraph_tasks\n","repo_name":"VeBaS-UAV/mamoge-taskplanner","sub_path":"mamoge/taskplanner/dag.py","file_name":"dag.py","file_ext":"py","file_size_in_byte":2964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"29859624866","text":"\"\"\"Implementation of var-naming rule.\"\"\"\nfrom __future__ import annotations\n\nimport keyword\nimport re\nimport sys\nfrom typing import TYPE_CHECKING, Any\n\nfrom ansible.parsing.yaml.objects import AnsibleUnicode\n\nfrom ansiblelint.config import options\nfrom ansiblelint.constants import LINE_NUMBER_KEY, RC\nfrom ansiblelint.errors import MatchError\nfrom ansiblelint.file_utils import Lintable\nfrom ansiblelint.rules import AnsibleLintRule, RulesCollection\nfrom ansiblelint.runner import Runner\nfrom ansiblelint.skip_utils import get_rule_skips_from_line\nfrom ansiblelint.utils import parse_yaml_from_file\n\nif TYPE_CHECKING:\n from ansiblelint.utils import Task\n\n\nclass VariableNamingRule(AnsibleLintRule):\n \"\"\"All variables should be named using only lowercase and underscores.\"\"\"\n\n id = \"var-naming\"\n severity = \"MEDIUM\"\n tags = [\"idiom\"]\n version_added = \"v5.0.10\"\n needs_raw_task = True\n re_pattern_str = options.var_naming_pattern or \"^[a-z_][a-z0-9_]*$\"\n re_pattern = re.compile(re_pattern_str)\n\n # pylint: disable=too-many-return-statements)\n def get_var_naming_matcherror(\n self,\n ident: str,\n *,\n prefix: str = \"\",\n ) -> MatchError | None:\n \"\"\"Return a MatchError if the variable name is not valid, otherwise None.\"\"\"\n if not isinstance(ident, str): # pragma: no cover\n return MatchError(\n tag=\"var-naming[non-string]\",\n message=\"Variables names must be strings.\",\n rule=self,\n )\n\n try:\n ident.encode(\"ascii\")\n except UnicodeEncodeError:\n return MatchError(\n tag=\"var-naming[non-ascii]\",\n message=\"Variables names must be ASCII.\",\n rule=self,\n )\n\n if keyword.iskeyword(ident):\n return MatchError(\n tag=\"var-naming[no-keyword]\",\n message=\"Variables names must not be Python keywords.\",\n rule=self,\n )\n\n # We want to allow use of jinja2 templating for variable names\n if \"{{\" in ident:\n return MatchError(\n tag=\"var-naming[no-jinja]\",\n message=\"Variables names must not contain jinja2 templating.\",\n rule=self,\n )\n\n if not bool(self.re_pattern.match(ident)):\n return MatchError(\n tag=\"var-naming[pattern]\",\n message=f\"Variables names should match {self.re_pattern_str} regex.\",\n rule=self,\n )\n\n if prefix and not ident.startswith(f\"{prefix}_\"):\n return MatchError(\n tag=\"var-naming[no-role-prefix]\",\n message=\"Variables names from within roles should use role_name_ as a prefix.\",\n rule=self,\n )\n return None\n\n def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]:\n \"\"\"Return matches found for a specific playbook.\"\"\"\n results: list[MatchError] = []\n raw_results: list[MatchError] = []\n\n if not data or file.kind not in (\"tasks\", \"handlers\", \"playbook\", \"vars\"):\n return results\n # If the Play uses the 'vars' section to set variables\n our_vars = data.get(\"vars\", {})\n for key in our_vars:\n match_error = self.get_var_naming_matcherror(key)\n if match_error:\n match_error.filename = str(file.path)\n match_error.lineno = (\n key.ansible_pos[1]\n if isinstance(key, AnsibleUnicode)\n else our_vars[LINE_NUMBER_KEY]\n )\n raw_results.append(match_error)\n if raw_results:\n lines = file.content.splitlines()\n for match in raw_results:\n # lineno starts with 1, not zero\n skip_list = get_rule_skips_from_line(\n line=lines[match.lineno - 1],\n lintable=file,\n )\n if match.rule.id not in skip_list and match.tag not in skip_list:\n results.append(match)\n\n return results\n\n def matchtask(\n self,\n task: Task,\n file: Lintable | None = None,\n ) -> list[MatchError]:\n \"\"\"Return matches for task based variables.\"\"\"\n results = []\n prefix = \"\"\n filename = \"\" if file is None else str(file.path)\n if file and file.parent and file.parent.kind == \"role\":\n prefix = file.parent.path.name\n # If the task uses the 'vars' section to set variables\n our_vars = task.get(\"vars\", {})\n for key in our_vars:\n match_error = self.get_var_naming_matcherror(key, prefix=prefix)\n if match_error:\n match_error.filename = filename\n match_error.lineno = our_vars[LINE_NUMBER_KEY]\n match_error.message += f\" (vars: {key})\"\n results.append(match_error)\n\n # If the task uses the 'set_fact' module\n # breakpoint()\n ansible_module = task[\"action\"][\"__ansible_module__\"]\n if ansible_module == \"set_fact\":\n for key in filter(\n lambda x: isinstance(x, str) and not x.startswith(\"__\"),\n task[\"action\"].keys(),\n ):\n match_error = self.get_var_naming_matcherror(key, prefix=prefix)\n if match_error:\n match_error.filename = filename\n match_error.lineno = task[\"action\"][LINE_NUMBER_KEY]\n match_error.message += f\" (set_fact: {key})\"\n results.append(match_error)\n\n # If the task registers a variable\n registered_var = task.get(\"register\", None)\n if registered_var:\n match_error = self.get_var_naming_matcherror(registered_var, prefix=prefix)\n if match_error:\n match_error.message += f\" (register: {registered_var})\"\n match_error.filename = filename\n match_error.lineno = task[LINE_NUMBER_KEY]\n results.append(match_error)\n\n return results\n\n def matchyaml(self, file: Lintable) -> list[MatchError]:\n \"\"\"Return matches for variables defined in vars files.\"\"\"\n results: list[MatchError] = []\n raw_results: list[MatchError] = []\n meta_data: dict[AnsibleUnicode, Any] = {}\n filename = \"\" if file is None else str(file.path)\n\n if str(file.kind) == \"vars\" and file.data:\n meta_data = parse_yaml_from_file(str(file.path))\n for key in meta_data:\n match_error = self.get_var_naming_matcherror(key)\n if match_error:\n match_error.filename = filename\n match_error.lineno = key.ansible_pos[1]\n match_error.message += f\" (vars: {key})\"\n raw_results.append(match_error)\n if raw_results:\n lines = file.content.splitlines()\n for match in raw_results:\n # lineno starts with 1, not zero\n skip_list = get_rule_skips_from_line(\n line=lines[match.lineno - 1],\n lintable=file,\n )\n if match.rule.id not in skip_list and match.tag not in skip_list:\n results.append(match)\n else:\n results.extend(super().matchyaml(file))\n return results\n\n\n# testing code to be loaded only with pytest or when executed the rule file\nif \"pytest\" in sys.modules:\n import pytest\n\n from ansiblelint.testing import ( # pylint: disable=ungrouped-imports\n run_ansible_lint,\n )\n\n @pytest.mark.parametrize(\n (\"file\", \"expected\"),\n (\n pytest.param(\"examples/playbooks/rule-var-naming-fail.yml\", 7, id=\"0\"),\n pytest.param(\"examples/Taskfile.yml\", 0, id=\"1\"),\n ),\n )\n def test_invalid_var_name_playbook(file: str, expected: int) -> None:\n \"\"\"Test rule matches.\"\"\"\n rules = RulesCollection(options=options)\n rules.register(VariableNamingRule())\n results = Runner(Lintable(file), rules=rules).run()\n assert len(results) == expected\n for result in results:\n assert result.rule.id == VariableNamingRule.id\n # We are not checking line numbers because they can vary between\n # different versions of ruamel.yaml (and depending on presence/absence\n # of its c-extension)\n\n def test_invalid_var_name_varsfile(\n default_rules_collection: RulesCollection,\n ) -> None:\n \"\"\"Test rule matches.\"\"\"\n results = Runner(\n Lintable(\"examples/playbooks/vars/rule_var_naming_fail.yml\"),\n rules=default_rules_collection,\n ).run()\n expected_errors = (\n (\"schema[vars]\", 1),\n (\"var-naming[pattern]\", 2),\n (\"var-naming[pattern]\", 6),\n (\"var-naming[no-jinja]\", 7),\n (\"var-naming[no-keyword]\", 9),\n (\"var-naming[non-ascii]\", 10),\n )\n assert len(results) == len(expected_errors)\n for idx, result in enumerate(results):\n assert result.tag == expected_errors[idx][0]\n assert result.lineno == expected_errors[idx][1]\n\n def test_var_naming_with_pattern() -> None:\n \"\"\"Test rule matches.\"\"\"\n role_path = \"examples/roles/var_naming_pattern/tasks/main.yml\"\n conf_path = \"examples/roles/var_naming_pattern/.ansible-lint\"\n result = run_ansible_lint(\n f\"--config-file={conf_path}\",\n role_path,\n )\n assert result.returncode == RC.SUCCESS\n assert \"var-naming\" not in result.stdout\n","repo_name":"sandeepkumar1209/ansible-playbook-RHCHA","sub_path":".local/share/containers/storage/overlay/f1eda16957dd74a1bcf819ceefffd1da1917a216901e84a321d3378d23822f8c/diff/usr/local/lib/python3.11/site-packages/ansiblelint/rules/var_naming.py","file_name":"var_naming.py","file_ext":"py","file_size_in_byte":9799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"38669611407","text":"#_*_ conding:UTF-8 _*_\n#题目:判断1-200之间有多少个素数,并输出所有素数。\n#满足素数条件,只能被自身和1整除的数\nh = 0\nleap = 1\nfrom math import sqrt\nfrom sys import stdout\nfor m in range(1,201):\n k = int(sqrt(m + 1))\n for i in range(2,k + 1):\n if m % i ==0:\n leap = 0\n break\n if leap == 1:\n print('%-4d' %m )\n h +=1\n if h % 10 == 0:\n print (\"\")\n leap =1\nprint('素数是%d' %h )","repo_name":"ll996075dd/xuexi","sub_path":"day2-3.py","file_name":"day2-3.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"15359997539","text":"# Ask the user for a string.\n# and print out whether this string is a palindrome or not. \n# (A palindrome is a string that reads the same forwards and backwards.)\n\nuser_string = input('Enter String to check if it\\s palindrom or not: ')\npalind_list = ''\n\nfor i in range(len(user_string)-1,-1,-1):\n palind_list += user_string[i]\n\n\nif palind_list == user_string:\n print(f'user input is palindrome')\nelse:\n print('not palindrome')","repo_name":"YazanSneneh/reads","sub_path":"flask lessons/palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"16577367707","text":"# Melhorar o desafio anterior : mostrar a soma dos valores pares\n# a soma dos valores da terceira coluna e o maior valor da segunda linha\nmatriz = []\nsoma_pares = 0\nsoma_terceira = 0\nmaior = 0\nfor i in range(3):\n matriz.append([])\n for j in range(3):\n matriz[i].append(int(input(f\"Digite o número da posição [{i}x{j}]: \")))\nprint(10*'=-=')\nfor i in range(3):\n for j in range(3):\n print(f\"[{matriz[i][j]}]\", end='')\n if matriz[i][j] % 2 == 0:\n soma_pares += matriz[i][j]\n print()\nprint(15*'-=-')\nprint(f\"A soma de todos os números pares vale {soma_pares}!\")\nfor i in range(3):\n soma_terceira = matriz[i][2]\nprint(f\"A soma dos números da terceira coluna vale {soma_terceira}!\")\nfor j in range(3):\n if j == 0:\n maior = matriz[1][j]\n elif matriz[1][j] > maior:\n maior = matriz[1][j]\nprint(f\"O maior número da segunda linha é {maior}!\")\nprint(\"-=-= FIM DO PROGRAMA -=-=\")\n","repo_name":"luizchimenes/python_v1","sub_path":"pyt_cursoemvideo/aula18/ex88yt.py","file_name":"ex88yt.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"6081211075","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\n\nfrom ..utils.constants import UserDataPath\nfrom ..utils.user import AppUser\nfrom ..utils.message import info, critical, warning\nfrom ..utils.error import SameUserAppExists, GameError\n\n__author__ = 'fyabc'\n\n\nclass Frontend:\n def __init__(self, **kwargs):\n info('Start the frontend \"{}\"'.format(self.__class__.__name__))\n self.user = AppUser.load_or_create(kwargs.pop('user_id_or_name', None))\n self.game = None # type: 'MyHearthStone.game.core.Game'\n self.raise_exception = kwargs.pop('raise_exception', False)\n\n self._hold_lock_file = False\n\n def __repr__(self):\n return '<{}>'.format(self.__class__.__name__)\n\n def main(self) -> int:\n \"\"\"Main loop of the frontend.\n\n :return: exit status, 0 means normal exit, 1 means exit with error.\n :rtype: int\n \"\"\"\n\n try:\n self.__check_user_locked()\n self._main()\n except GameError as e:\n critical(e)\n return 1\n except Exception as e:\n from traceback import format_exc\n critical(e)\n critical(format_exc())\n if self.raise_exception:\n raise\n else:\n return 1\n finally:\n self.finalize()\n return 0\n\n def _main(self):\n raise NotImplementedError('implemented in subclasses')\n\n def create_server(self):\n pass\n\n def preprocess(self):\n pass\n\n def finalize(self):\n if self._hold_lock_file:\n info('Saving user information...')\n self.user.dump()\n info('Save use information done')\n\n try:\n os.remove(self.__lock_filename())\n except FileNotFoundError:\n warning('Try to remove user lock file but not found')\n else:\n info('User lock file removed')\n\n info('App exited\\n')\n\n def __check_user_locked(self):\n if os.path.exists(self.__lock_filename()):\n raise SameUserAppExists(self.user.user_id)\n else:\n with open(self.__lock_filename(), 'w'):\n info('Create user lock file')\n self._hold_lock_file = True\n\n def __lock_filename(self):\n return os.path.join(UserDataPath, 'lock-user-{}.lock'.format(self.user.user_id))\n","repo_name":"fyabc/MiniGames","sub_path":"HearthStone2/MyHearthStone/ui/frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"33"} +{"seq_id":"13377569843","text":"valores = [[], []]\r\nfor c in range(1, 8):\r\n num = int(input(f'Digite o {c}° valor: '))\r\n if num % 2 == 0:\r\n valores[0].append(num)\r\n valores[0].sort()\r\n elif num % 2 != 0:\r\n valores[1].append(num)\r\n valores[1].sort()\r\nprint(f'Os valores pares digitados foram {valores[0]}')\r\nprint(f'Os valores ímpares digitados foram {valores[1]}')\r\n","repo_name":"ErickGLopes/Estudos","sub_path":"Exercícios de Python/Mundo 3/Listas/ex085.py","file_name":"ex085.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"41229326728","text":"import logging\nimport threading\nimport time\nimport uuid\n\nfrom common.CommonGlobals import Stage, Status, Percentage\n\nfrom common.ConfigObject import ConfigObject\nfrom common.XcalLogger import XcalLogger\nfrom scanTaskService.Config import SCAN_RUNNER_JOB_TOPIC, TaskErrorNo, SCANNER_WORKER_TIMEOUT_LIST, AGENT_TOPIC_PREFIX, \\\n SCAN_ENGINE_TOPIC, SCANNER_WORKER_COUNT, TOPIC_PREFIX\nfrom scanTaskService.XcalExpirationWatch import ExpirationWatcher\nfrom scanTaskService.components import LoggingHandler\nfrom scanTaskService.components.AgentInfo import AgentInfoManagement, AgentInfoStatus\nfrom scanTaskService.components.JobInitiator import JobListener\nfrom scanTaskService.components.ScanController import ScanController\nfrom scanTaskService.components.XcalServices import ScanStageObject\n\n\nclass ExpiredTaskRemover(object):\n def __init__(self):\n pass\n\n def loop(self):\n LoggingHandler.ban_kafka_loggings()\n # Looping to receive data -----------------------\n while True:\n try:\n self.process()\n except KeyboardInterrupt:\n logging.warning(\"Exiting, Bye!\")\n return\n except Exception as err:\n logging.exception(err)\n one_logger = XcalLogger(\"ExpiredTaskRemover\", \"loop\")\n one_logger.error(\"ExpiredTaskRemover\", \"loop\", (\"Process failed...\", str(err)))\n time.sleep(1)\n\n def process(self):\n with XcalLogger(\"ExpiredTaskRemover\", \"process\") as remove_log:\n expired = ExpirationWatcher(remove_log).pop_expired_list()\n for one_expire_item in expired:\n # If this is a pipeline object, execute this accordingly\n remove_log.trace(\"Found a job that was timeout\",\n (\"item = \", str(one_expire_item)))\n if one_expire_item.get(\"job\") == SCAN_RUNNER_JOB_TOPIC:\n # Scanner Worker Job\n copied_item = self.get_scanner_worker_expire_task(one_expire_item, TaskErrorNo.E_QUEUEING_EXPIRED)\n elif one_expire_item.get(\"job\") == SCANNER_WORKER_TIMEOUT_LIST:\n copied_item = self.get_scanner_worker_expire_task(one_expire_item, TaskErrorNo.E_SCAN_SERVICE_STAGE_TIMEOUT)\n elif str(one_expire_item.get(\"job\")).startswith(AGENT_TOPIC_PREFIX):\n copied_item = self.get_expire_task_due_to_no_agent_do(one_expire_item)\n else:\n remove_log.error(\"ExpiredTaskRemover\", \"process\", \"Cannot report expiration, due to unknown kind of job_list is present\")\n copied_item = self.get_scanner_worker_expire_task(one_expire_item, TaskErrorNo.E_UTIL_EXPIRE_UNKNOWN_LIST_NAME)\n\n # Immediate invoke the processing ScanController, fix bug #781 #941\n remove_log.trace(\n \"Adding a pipeline for reporting the timeout\", \"scanTaskId = %s\" % copied_item.get(\"scanTaskId\"))\n # ScanController(remove_log).process_internal_job(copied_item, no_timeout=True)\n ScanController(remove_log, ConfigObject(copied_item)).sp_start()\n pass\n\n def start(self):\n with XcalLogger(\"ExpiredTaskRemover\", \"start\") as one_logger:\n one_logger.trace(\"ExpireTaskRemover.start\", \"Starting an ExpiredTaskRemover on object.id=(%d)\" % id(self))\n th = threading.Thread(target=ExpiredTaskRemover.loop, args=(self, ))\n th.setDaemon(True)\n th.setName(\"ExpiredTaskRemover-1-\" + str(uuid.uuid1()))\n th.start()\n\n def get_scanner_worker_expire_task(self, one_expire_item:dict, err:TaskErrorNo):\n copied_item = one_expire_item.get(\"config\").copy()\n common_suffix = \" scanServiceJobId = %s, timeout = %s\" % (str(one_expire_item.get(\"jobId\")),\n str(one_expire_item.get(\"expire\")))\n if copied_item.get(\"pipeline\") is None or copied_item.get(\"pipelineOffset\") is None:\n extra_info = \"No pipeline or ofst %s\" % common_suffix\n elif len(copied_item.get(\"pipeline\")) <= int(copied_item.get(\"pipelineOffset\")):\n extra_info = \"Unacceptable pipelineOffset %s\" % common_suffix\n else:\n extra_info = \"In stage %s, %s\" % \\\n (copied_item.get(\"pipeline\")[int(copied_item.get(\"pipelineOffset\"))].get(\"type\"),\n common_suffix)\n\n copied_item[\"pipeline\"] = [\n ScanStageObject(stage_type=\"uploadProgress\", info={}, start=5, complete=100, sync=0, timeout=10).as_dict()]\n copied_item[\"pipelineOffset\"] = 0\n copied_item[\"agentName\"] = \"timeout-checker\"\n copied_item[\"target\"] = \"progress\"\n copied_item[\"errorInfo\"] = err\n copied_item[\"extraInfo\"] = extra_info\n copied_item[\"timeoutMan\"] = []\n copied_item[\"origin\"] = \"scanService\"\n copied_item[\"stage\"] = Stage.SCANNING\n copied_item[\"status\"] = Status.FAILED\n copied_item[\"progress\"] = Percentage.END\n return copied_item\n\n def get_expire_reason(self, job_name):\n return AgentInfoManagement.get_agent_info_status(job_name)\n\n def get_error_info(self, job_name):\n expire_reason = self.get_expire_reason(job_name)\n if expire_reason == AgentInfoStatus.NO_AGENT:\n logging.warning(\"no active agent\")\n err = TaskErrorNo.E_NO_ACTIVE_AGENT_FOR_THIS_JOB\n elif expire_reason == AgentInfoStatus.AGENT_IS_BUSY:\n logging.warning(\"agent is busy\")\n err = TaskErrorNo.E_AGENT_IS_BUSY\n elif expire_reason == AgentInfoStatus.JOB_QUEUE_NAME_NOT_SUPPORT:\n logging.warning(\"no active agent for this job\")\n err = TaskErrorNo.E_NO_ACTIVE_AGENT_FOR_THIS_JOB\n else:\n logging.error(\"unknown, need to check the scan service logs\")\n err = TaskErrorNo.E_COMMON_UNKNOWN_ERROR\n\n return err\n\n def get_expire_task_due_to_no_agent_do(self, expire_item: dict):\n job_config = expire_item.get(\"config\").copy()\n common_suffix = \" scanServiceJobId = %s, timeout = %s\" % (str(expire_item.get(\"jobId\")),\n str(expire_item.get(\"expire\")))\n job_name = str(expire_item.get(\"job\"))\n if job_name.startswith(AGENT_TOPIC_PREFIX):\n job_name = job_name[len(AGENT_TOPIC_PREFIX):]\n if job_name.startswith(TOPIC_PREFIX):\n job_name = job_name[len(TOPIC_PREFIX):]\n\n err = self.get_error_info(job_name)\n\n # Merging TaskConfig with JobConfig\n task_config = job_config.get(\"taskConfig\", {})\n job_config = ConfigObject.merge_two_dicts(job_config, task_config)\n\n job_config[\"pipeline\"] = [\n ScanStageObject(stage_type = \"uploadProgress\", info = {}, start = 5, complete = 100, sync = 0,\n timeout = 10).as_dict()]\n job_config[\"pipelineOffset\"] = 0\n job_config[\"target\"] = \"progress\"\n job_config[\"errorInfo\"] = err\n job_config[\"extraInfo\"] = common_suffix\n job_config[\"timeoutMan\"] = []\n job_config[\"stage\"] = Stage.AGENT_START\n job_config[\"status\"] = Status.FAILED\n job_config[\"progress\"] = Percentage.END\n return job_config\n\n\nclass TimerProcessAgentInfo(object):\n @staticmethod\n def loop():\n while True:\n try:\n AgentInfoManagement.clean_timeout_agent()\n except KeyboardInterrupt:\n logging.warning(\"Exiting, Bye!\")\n return\n except Exception as err:\n logging.exception(err)\n one_logger = XcalLogger(\"TimerProcessAgentInfo\", \"loop\")\n one_logger.error(\"TimerProcessAgentInfo\", \"loop\",\n (\"Process failed...\", str(err)))\n time.sleep(5)\n\n @staticmethod\n def start():\n with XcalLogger(\"TimerProcessAgentInfo\", \"start\") as one_logger:\n one_logger.trace(\"TimerProcessAgentInfo.start\", \"Starting an TimerProcessAgentInfo\")\n th = threading.Thread(target = TimerProcessAgentInfo.loop)\n th.setDaemon(True)\n th.setName(\"Thread-TimerProcessAgentInfo\")\n th.start()\n\n\n# This class was used only for debugging & memory dumps, see git log to find histories\nclass HealthCheck(object):\n def __init__(self):\n pass\n\n def start(self):\n pass\n\n\nclass ScanServiceJobListener(object):\n workers = []\n\n def __init__(self):\n pass\n\n def process_job(self):\n # Looping to poll info from message queue\n LoggingHandler.ban_kafka_loggings()\n log = XcalLogger(\"ScanServiceJobListener\", \"process_job\")\n listener = JobListener(log)\n # controller = ScanController(XcalLogger(\"ScanServiceJobListener\", \"process_job\"),\n # type=ControllerType.DEFAULT_ASYNC)\n while True:\n try:\n lst = listener.poll_job_task(SCAN_RUNNER_JOB_TOPIC, 1)\n for message in lst:\n # controller.process_internal_job(message)\n ScanController(XcalLogger('ScanServiceJobListener', 'process_job'), ConfigObject(message)).sp_start()\n except KeyboardInterrupt:\n logging.warning(\"Exiting, Bye!\")\n return\n except Exception as err:\n logging.exception(err)\n log.error(\"ScanServiceJobListener\", \"process_job\",\n (\"kafka receive / process job failed...\", str(err)))\n # Fix zentao bug #928, avoid CPU usage being too high when above mechanism falls through.\n time.sleep(3)\n finally:\n listener.commit_job_task()\n time.sleep(0.5)\n\n # Single worker by default\n def start_workers(self, count: int = SCANNER_WORKER_COUNT):\n for one in range(count):\n th = threading.Thread(target=ScanServiceJobListener.process_job, args=(self,))\n th.setDaemon(True)\n th.setName(\"ScannerWorker-\" + str(one) + \"-\" + str(uuid.uuid1()))\n th.start()\n ScanServiceJobListener.workers.append(th)\n\n\nclass ScanEngineServiceJobListener(object):\n workers = []\n\n def __init__(self):\n pass\n\n def process_job(self):\n # Looping to receive data -----------------------\n LoggingHandler.ban_kafka_loggings()\n log = XcalLogger(\"ScanEngineServiceJobListener\", \"process_job\")\n listener = JobListener(log)\n # controller = ScanController(XcalLogger(\"ScanEngineServiceJobListener\", \"process_job\"),\n # type=ControllerType.SCAN_ENGINE)\n while True:\n try:\n lst = listener.poll_job_task(SCAN_ENGINE_TOPIC, 1)\n for message in lst:\n # controller.process_internal_job(message)\n ScanController(XcalLogger('ScanEngineServiceJobListener', 'process_job'), ConfigObject(message)).sp_start()\n except KeyboardInterrupt:\n logging.warning(\"Exiting, Bye!\")\n return\n except Exception as err:\n logging.exception(err)\n log.error(\"ScanEngineServiceJobListener\", \"process_job\",\n \"BaseException in resolving previous exception\")\n time.sleep(3)\n finally:\n listener.commit_job_task()\n time.sleep(0.5)\n\n # Single worker by default\n def start_workers(self, count: int = SCANNER_WORKER_COUNT):\n for one in range(count):\n th = threading.Thread(target=ScanEngineServiceJobListener.process_job, args=(self,))\n th.setDaemon(True)\n th.setName(\"ScanEngineWorker-\" + str(one) + \"-\" + str(uuid.uuid1()))\n th.start()\n ScanEngineServiceJobListener.workers.append(th)","repo_name":"xcalcc/scan-service","sub_path":"scanTaskService/src/scanTaskService/components/ScanServiceWorker.py","file_name":"ScanServiceWorker.py","file_ext":"py","file_size_in_byte":11995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"23911421544","text":"# https://school.programmers.co.kr/learn/courses/30/lessons/60062\n# https://tech.kakao.com/2019/10/02/kakao-blind-recruitment-2020-round1/\n# https://www.youtube.com/watch?v=yYc2KiCSIoA\n# very hard\n# brute force + permutation\n\nfrom itertools import permutations\n\n\ndef solution(n, weak, dist):\n weak_size = len(weak)\n dist_size = len(dist)\n for i in range(weak_size):\n weak.append(weak[i] + n)\n\n INF = float(\"inf\")\n min_cnt = INF\n\n for start in range(weak_size):\n for d in permutations(dist, dist_size):\n cnt = 1\n pos = start\n\n for i in range(1, weak_size):\n next_pos = start + i\n diff = weak[next_pos] - weak[pos]\n if diff > d[cnt - 1]:\n pos = next_pos\n cnt += 1\n if cnt > dist_size:\n break\n\n if cnt <= dist_size: #####\n min_cnt = min(min_cnt, cnt)\n\n if min_cnt == INF:\n return -1\n\n return min_cnt\n","repo_name":"h-spear/problem-solving-python","sub_path":"programmers/level3/exterior_wall_inspection.py","file_name":"exterior_wall_inspection.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"31684219411","text":"from __future__ import annotations\n\nfrom functools import partial\n\nimport fal\n\nfrom benchmarks.settings import BenchmarkResults, BenchmarkSettings, InputParameters\n\n\n@fal.function(\n requirements=[\n \"--pre\",\n \"torch>=2.1.0\",\n \"transformers>=4.27.1\",\n \"diffusers>=0.19.3\",\n \"git+https://github.com/Oneflow-Inc/onediff.git@0.11.3\",\n \"oneflow\",\n \"-f\",\n \"https://oneflow-pro.oss-cn-beijing.aliyuncs.com/branch/community/cu121\",\n ],\n machine_type=\"GPU\",\n)\ndef oneflow_any(\n benchmark_settings: BenchmarkSettings,\n parameters: InputParameters,\n model_name: str,\n) -> BenchmarkResults:\n import oneflow as flow\n import torch\n from diffusers import DiffusionPipeline\n from onediff.infer_compiler import oneflow_compile\n\n pipeline = DiffusionPipeline.from_pretrained(\n model_name,\n torch_dtype=torch.float16,\n use_safetensors=True,\n )\n pipeline.to(\"cuda\")\n pipeline.unet = oneflow_compile(pipeline.unet)\n\n with flow.autocast(\"cuda\"):\n infer_func = partial(\n pipeline, parameters.prompt, num_inference_steps=parameters.steps\n )\n return benchmark_settings.apply(infer_func)\n\n\nLOCAL_BENCHMARKS = [\n {\n \"name\": \"OneFlow\",\n \"category\": \"SD1.5 (End-to-end)\",\n \"function\": oneflow_any,\n \"kwargs\": {\n \"model_name\": \"runwayml/stable-diffusion-v1-5\",\n },\n },\n {\n \"name\": \"OneFlow\",\n \"category\": \"SDXL (End-to-end)\",\n \"function\": oneflow_any,\n \"kwargs\": {\n \"model_name\": \"stabilityai/stable-diffusion-xl-base-1.0\",\n },\n },\n]\n","repo_name":"fal-ai/stable-diffusion-benchmarks","sub_path":"benchmarks/benchmark_oneflow.py","file_name":"benchmark_oneflow.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"33"} +{"seq_id":"14145406050","text":"import logging\n\nlogger = logging.getLogger('solver/basic.py')\n\n\n# [{'nr': 0, 'nTags': '3', 'direction': 'H', 'tags': ['cat', 'beach', 'sun']}]\n\ndef solve(photos):\n logger.info('Not actually solving anything')\n\n hor = filter(lambda x: x[\"direction\"] == \"H\", photos)\n vert = filter(lambda x: x[\"direction\"] == \"V\", photos)\n\n sorted_hor = sorted(hor, key=lambda x: x[\"nTags\"])\n sorted_vert = sorted(vert, key=lambda x: x[\"nTags\"])\n\n slides = []\n\n logger.debug('Found some slides...')\n\n return slides\n\n\ndef getAmountOfSlides(sorted_hor, sorted_vert):\n return len(sorted_hor) + len(sorted_vert) / 2\n\n\ndef getUniqueTagsOfPhotos(photoA, photoB):\n return photoA[\"nTags\"] + photoB[\"nTags\"] - 2 * getSameTagsOfPhotos(photoA, photoB)\n\n\ndef getSameTagsOfPhotos(photoA, photoB):\n sameTags = 0\n for photoAsTag in photoA[\"tags\"]:\n for photoBsTag in photoB[\"tags\"]:\n if photoAsTag == photoBsTag:\n sameTags = sameTags + 1\n return sameTags\n\n\ndef returnSmallestSum(sums):\n smallestSum = sums[0]\n for sum in sums:\n if smallestSum > sum:\n smallestSum = sum\n return smallestSum\n","repo_name":"PaulienVa/hashcode2019","sub_path":"awesome_dir/solvers/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"74813546018","text":"import pandas as pd\nimport numpy as np\n\ndef SleepTracker (awake, sleep):\n if awake >= 17:\n awake_output = 'sleep deprived'\n else:\n awake_output = 'average amount of sleep'\n if sleep <= 7:\n sleep_output = 'sleep deprived'\n else:\n awake_output = 'average amount of sleep'\n\n output = [awake_output, sleep_output]\n\n return output\n\n\nThisIsANumber = 5\n\ndefiningSleep = {\n \"average\": \"6 to 8 hours\",\n \"below_average\": \"0 to 6 hours\",\n \"above_average\": \"9 and above hours\"\n}\n\nprint(\"What is the average amount of sleep?\" , definingSleep[\"average\"])\nprint(\"What is a bad amount of sleep?\" , definingSleep[\"below_average\"])\nprint(\"What is too much sleep\" , definingSleep[\"above_average\"])\n\nsleepTime = [\n (16, 8),\n (15, 9),\n (20, 4),\n (18, 6),\n (12, 12),\n (9, 15),\n (17, 7)\n]\n\nfor sleepTimes in sleepTime:\n print(f'Are you sleeping well enough? hours_awake: {sleepTime[0]}, hours_slept: {sleepTime[1]}')\n hours_awake = sleepTime[0]\n hours_slept = sleepTime[1]","repo_name":"daniloui001/health-analytics","sub_path":"health_analysis.py","file_name":"health_analysis.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"4993186864","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('', views.index),\n path('map/', views.mapviews),\n path('jquery/', views.jquery),\n path('map2/', views.api),\n path('dmsconverter/', views.dmsconverter, name='dmsconverter'),\n path(\"degreeconverter/\", views.degreeconverter, name='degreeconverter'),\n path(\"fotoudara/\", views.fotoudara, name='fotoudara'),\n path('saran/', views.SaranView.as_view(), name='saran'),\n path('403/', views.permission_denied_view),\n]","repo_name":"fabhiansan/webgisbc","sub_path":"index/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"6055949239","text":"import os\nfrom opt import get_opts\nimport torch\nfrom collections import defaultdict\n\nfrom torch.utils.data import DataLoader\n\nfrom tqdm import tqdm\n\n# models\nfrom models.nerf import (\n PosEmbedding,\n NeRF\n)\nfrom models.nerflet import Nerflet\nfrom models.rendering_nerflet import (\n render_rays\n)\n\nfrom datasets.sitcom3D import Sitcom3DDataset\nfrom datasets.blender import BlenderDataset\nfrom datasets.replica import ReplicaDataset\nfrom datasets.front import ThreeDFrontDataset\nimport numpy as np\n\nfrom metrics import psnr\n\nfrom utils.visualization import get_image_summary_from_vis_data, np_visualize_depth\n\nimport cv2\nfrom utils import load_ckpt\nimport imageio\nimport argparse\nfrom pathlib import Path\nimport json\nfrom omegaconf import OmegaConf\n\n\n@torch.no_grad()\ndef batched_inference(models, embeddings,\n rays, ts, predict_label, num_classes, N_samples, N_importance, use_disp,\n chunk, white_back, predict_density, use_fine_nerf, use_associated, **kwargs):\n \"\"\"Do batched inference on rays using chunk.\"\"\"\n B = rays.shape[0]\n results = defaultdict(list)\n for chunk_idx in range(0, B, chunk):\n rendered_ray_chunks = \\\n render_rays(models,\n embeddings,\n rays[chunk_idx:chunk_idx+chunk],\n ts[chunk_idx:chunk_idx+chunk] if ts is not None else None,\n predict_label,\n num_classes,\n N_samples,\n use_disp,\n N_importance,\n chunk,\n white_back,\n predict_density=predict_density,\n use_fine_nerf=use_fine_nerf,\n perturb=0,\n use_associated=use_associated,\n test_time=True,\n **kwargs)\n\n for k, v in rendered_ray_chunks.items():\n results[k] += [v.cpu()]\n\n for k, v in results.items():\n results[k] = torch.cat(v, 0)\n return results\n\n\ndef compute_iou(pred, gt, num_cls):\n iou = []\n for cls_idx in range(num_cls):\n denom = np.logical_or((pred == cls_idx), (gt == cls_idx)).astype(int).sum()\n if denom == 0:\n iou.append(1)\n else:\n numer = np.logical_and((pred == cls_idx), (gt == cls_idx)).astype(int).sum()\n iou.append(numer / denom)\n return np.mean(iou)\n\n\n\ndef render_to_path(path, dataset, idx, models, embeddings, config,\n label_colors, part_colors, write_to_path=True, select_part_idx=None):\n sample = dataset[idx]\n rays = sample['rays']\n if 'ts2' in sample:\n ts = sample['ts2']\n else:\n ts = sample['ts']\n # TODO: the arguments of this function can be simplified to only pass config\n results = batched_inference(models, embeddings, rays.cuda(), ts.cuda(),\n config.predict_label, config.num_classes,\n config.N_samples, config.N_importance, config.use_disp,\n config.chunk, dataset.white_back, config.predict_density,\n config.use_fine_nerf, config.use_associated)\n\n rows = []\n metrics = {}\n\n # GT image and predicted image\n if config.dataset_name == 'sitcom3D':\n w, h = sample['img_wh']\n elif config.dataset_name == 'blender':\n w, h = config.img_wh\n elif config.dataset_name == 'replica' or config.dataset_name == '3dfront':\n w, h = dataset.img_wh\n\n # TODO: For now only consider fine nerf, might need to support coarse only\n # GT image and predicted combined image\n ray_associations = results['static_ray_associations_fine'].cpu().numpy().reshape((h, w))\n positive_rays_mask = results['static_positive_rays_fine'].cpu().numpy().reshape((h, w))\n if config.encode_t:\n img_pred = np.clip(results['combined_rgb_map'].view(h, w, 3).cpu().numpy(), 0, 1)\n else:\n img_pred = np.clip(results['static_rgb_map_fine'].view(h, w, 3).cpu().numpy(), 0, 1)\n img_pred_ = (img_pred * 255).astype(np.uint8)\n if select_part_idx is not None:\n non_selected_part_mask = np.logical_and(ray_associations != select_part_idx, np.logical_not(positive_rays_mask))\n img_pred_[non_selected_part_mask] = 255\n rgbs = sample['rgbs']\n img_gt = rgbs.view(h, w, 3)\n psnr_ = psnr(img_gt, img_pred).item()\n print(f\"PSNR: {psnr_}\")\n metrics['psnr'] = psnr_\n img_gt_ = np.clip(img_gt.cpu().numpy(), 0, 1)\n img_gt_ = (img_gt_ * 255).astype(np.uint8)\n rows.append(np.concatenate([img_gt_, img_pred_], axis=1))\n\n # Predicted static image and predicted static depth\n img_static = np.clip(results['static_rgb_map_fine'].view(h, w, 3).cpu().numpy(), 0, 1)\n img_static_ = (img_static * 255).astype(np.uint8)\n static_depth = results['static_depth_fine'].cpu().numpy()\n depth_static = np.array(np_visualize_depth(static_depth, cmap=cv2.COLORMAP_BONE))\n depth_static = depth_static.reshape(h, w, 1)\n depth_static_ = np.repeat(depth_static, 3, axis=2)\n rows.append(np.concatenate([img_static_, depth_static_], axis=1))\n\n # gt label and pred label\n if config.predict_label:\n label_gt = sample['labels'].to(torch.long).cpu().numpy()\n label_map_gt = label_colors[label_gt].reshape((h, w, 3))\n label_map_gt = (label_map_gt * 255).astype(np.uint8)\n if config.encode_t:\n label_pred = results['combined_label']\n else:\n label_pred = results['static_label']\n label_pred = torch.argmax(label_pred, dim=1).to(torch.long).cpu().numpy()\n label_map_pred = label_colors[label_pred].reshape((h, w, 3))\n label_map_pred[~positive_rays_mask] = 0\n label_map_pred = (label_map_pred * 255).astype(np.uint8)\n iou = compute_iou(label_pred, label_gt, config.num_classes)\n metrics['iou_combined'] = iou\n print(f\"Semantic iou: {iou}\")\n rows.append(np.concatenate([label_map_gt, label_map_pred], axis=1))\n\n if config.encode_t:\n label_static_pred = torch.argmax(results['static_label'], dim=1).to(torch.long).cpu().numpy()\n label_map_static_pred = label_colors[label_static_pred].reshape((h, w, 3))\n label_map_static_pred = (label_map_static_pred * 255).astype(np.uint8)\n metrics['iou_static'] = compute_iou(label_static_pred, label_gt, config.num_classes)\n\n label_transient_pred = torch.argmax(results['transient_label'], dim=1).to(torch.long).cpu().numpy()\n label_map_transient_pred = label_colors[label_transient_pred].reshape((h, w, 3))\n label_map_transient_pred = (label_map_transient_pred * 255).astype(np.uint8)\n rows.append(np.concatenate([label_map_static_pred, label_map_transient_pred], axis=1))\n\n ray_association_map = part_colors[ray_associations]\n ray_association_map[~positive_rays_mask] = 0\n ray_association_map = (ray_association_map * 255).astype(np.uint8)\n obj_mask = results['static_mask_fine'].cpu().numpy()\n obj_mask = obj_mask[..., np.newaxis] * np.array([[1, 1, 1]])\n obj_mask = obj_mask.reshape((h, w, 3))\n obj_mask = (obj_mask * 255).astype(np.uint8)\n rows.append(np.concatenate([ray_association_map, obj_mask], axis=1))\n\n res_img = np.concatenate(rows, axis=0)\n if write_to_path:\n imageio.imwrite(path, res_img)\n\n return metrics, res_img\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--exp_dir', type=str)\n parser.add_argument('--output_dir', type=str, default='results/rendering')\n parser.add_argument('--use_ckpt', type=str)\n parser.add_argument('--select_part_idx', type=int)\n parser.add_argument('--sweep_parts', action='store_true', default=False)\n parser.add_argument('--num_parts', type=int, default=-1)\n parser.add_argument('--num_images', type=int, default=-1)\n parser.add_argument('--split', type=str, default='val')\n parser.add_argument(\"opts\", nargs=argparse.REMAINDER)\n args = parser.parse_args()\n\n exp_dir = Path(args.exp_dir)\n output_dir = exp_dir / args.output_dir\n output_dir.mkdir(parents=True, exist_ok=True)\n\n config_path = exp_dir / 'config.json'\n with open(config_path, 'r') as f:\n file_config = json.load(f)\n file_config = OmegaConf.create(file_config)\n cli_config = OmegaConf.from_dotlist(args.opts)\n config = OmegaConf.merge(file_config, cli_config)\n\n kwargs = {}\n if config.dataset_name == 'sitcom3D':\n kwargs.update({'environment_dir': config.environment_dir,\n 'near_far_version': config.near_far_version})\n # kwargs['img_downscale'] = config.img_downscale\n kwargs['val_num'] = 5\n kwargs['use_cache'] = config.use_cache\n dataset = Sitcom3DDataset(split=args.split, img_downscale=config.img_downscale, near=config.near, **kwargs)\n elif config.dataset_name == 'blender':\n dataset = BlenderDataset(root_dir=config.environment_dir,\n img_wh=config.img_wh, split=args.split)\n elif config.dataset_name == 'replica':\n dataset = ReplicaDataset(root_dir=config.environment_dir,\n img_downscale=config.img_downscale, split=args.split,\n things_only=config.things_only if 'things_only' in config else False)\n elif config.dataset_name == '3dfront':\n dataset = ThreeDFrontDataset(root_dir=config.environment_dir,\n img_downscale=config.img_downscale, split=args.split,\n near=config.near, far=config.far)\n\n embedding_xyz = PosEmbedding(config.N_emb_xyz - 1, config.N_emb_xyz)\n embedding_dir = PosEmbedding(config.N_emb_dir - 1, config.N_emb_dir)\n embeddings = {'xyz': embedding_xyz, 'dir': embedding_dir}\n if config.encode_a:\n embedding_a = torch.nn.Embedding(config.N_vocab, config.N_a).cuda()\n load_ckpt(embedding_a, args.use_ckpt, model_name='embedding_a')\n embeddings['a'] = embedding_a\n if config.encode_t:\n embedding_t = torch.nn.Embedding(config.N_vocab, config.N_tau).cuda()\n load_ckpt(embedding_t, args.use_ckpt, model_name='embedding_t')\n embeddings['t'] = embedding_t\n\n disable_ellipsoid = config.disable_ellipsoid if 'disable_ellipsoid' in config else False\n disable_tf = config.disable_tf if 'disable_tf' in config else False\n bbox = dataset.bbox if hasattr(dataset, 'bbox') else None\n sharpness = config.sharpness if 'sharpness' in config else 100\n nerflet = Nerflet(D=config.num_hidden_layers, W=config.dim_hidden_layers, skips=config.skip_layers,\n N_emb_xyz=config.N_emb_xyz, N_emb_dir=config.N_emb_dir,\n encode_a=config.encode_a, encode_t=config.encode_t, predict_label=config.predict_label,\n num_classes=config.num_classes, M=config.num_parts,\n disable_ellipsoid=disable_ellipsoid,\n scale_min=config.scale_min, scale_max=config.scale_max,\n use_spread_out_bias=config.use_spread_out_bias, bbox=bbox,\n label_only=config.label_only, disable_tf=disable_tf,\n sharpness=sharpness, predict_density=config.predict_density).cuda()\n load_ckpt(nerflet, args.use_ckpt, model_name='nerflet')\n models = {'nerflet': nerflet}\n\n psnrs = []\n np.random.seed(19)\n label_colors = np.random.rand(config.num_classes, 3)\n part_colors = np.random.rand(config.num_parts, 3)\n iou_combined = []\n iou_static = []\n\n for i in tqdm(range(len(dataset))):\n if args.num_images != -1 and i >= args.num_images:\n continue\n if args.sweep_parts:\n for j in range(config.num_parts):\n if args.num_parts != -1 and j >= args.num_parts:\n continue\n print(f\"Rendering part {j}\")\n path = output_dir / f\"frame_{i:03d}\"\n path.mkdir(exist_ok=True)\n path = path / f\"part_{j}.png\"\n render_to_path(path, dataset=dataset, idx=i, models=models, embeddings=embeddings,\n config=config, label_colors=label_colors, part_colors=part_colors,\n select_part_idx=j)\n elif args.select_part_idx is not None:\n path = output_dir / f\"{i:03d}\"\n path.mkdir(exist_ok=True)\n path = path / f\"{args.select_part_idx}.png\"\n render_to_path(path, dataset=dataset, idx=i, models=models, embeddings=embeddings,\n config=config, label_colors=label_colors, part_colors=part_colors,\n select_part_idx=args.select_part_idx)\n else:\n path = output_dir / f\"{i:03d}.png\"\n metrics, _ = render_to_path(path, dataset=dataset, idx=i, models=models, embeddings=embeddings,\n config=config, label_colors=label_colors, part_colors=part_colors)\n psnrs.append(metrics['psnr'])\n if 'iou_combined' in metrics:\n iou_combined.append(metrics['iou_combined'])\n if 'iou_static' in metrics:\n iou_static.append(metrics['iou_static'])\n\n if config.predict_label:\n print('Mean IoU combined', np.mean(iou_combined))\n print('Mean IoU static', np.mean(iou_static))\n\n if psnrs:\n mean_psnr = np.mean(psnrs)\n print(f'Mean PSNR : {mean_psnr:.2f}')","repo_name":"onestarYX/human_obj_scene","sub_path":"eval_nerfletw.py","file_name":"eval_nerfletw.py","file_ext":"py","file_size_in_byte":13599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"4794925668","text":"import sqlite3\nimport streamlit as st\nimport pandas as pd\n\nconn = sqlite3.connect('test_database')\nc = conn.cursor()\ndf = pd.io.sql.read_sql(\"\"\"select * from prediction\"\"\", conn)\n\nst.title(\"Информация о тестовой выборке\", anchor=None)\nbutton1 = st.button('Показать количество фродовых трансакций')\nif st.session_state.get('button') != True:\n st.session_state['button'] = button1 \nif st.session_state['button'] == True:\n with st.form(key='my_form'):\n option = st.selectbox(\"Выберите период\", [\"неделя\", \"месяц\", \"3 месяца\", \"6 месяцев\"])\n submit_button = st.form_submit_button(label=f'Submit')\n period_dict = {\"неделя\":7, \"месяц\":30, \"3 месяца\":80, \"6 месяцев\":180}\n df_fraud_week = df[(df.step > (df.step.max() - period_dict[option])) & (df.fraud == 1)]\n st.write(len(df_fraud_week))\n \nif st.button(\"Показать последние 10 трансакций, требующие проверки\"):\n if len(df[df.fraud_basic == 1]) >= 10:\n st.write(df[df.fraud_basic == 1].tail(10))\n else: st.write(\"В датафрейме меньше, чем 10 трансакций, требующих проверки\")","repo_name":"Natawren/DA_sber","sub_path":"final/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"21161122510","text":"import sys\nsys.stdin = open('input.txt')\n\nn = int(sys.stdin.readline())\npaper = [''.join(list(map(str, sys.stdin.readline().split()))) for _ in range(n)]\n\ncnt_white = 0\ncnt_blue = 0\n\ndef color(arr, n):\n global cnt_white\n global cnt_blue\n white = True\n blue = True\n for i in range(n):\n for j in range(n):\n if arr[i][j] == '1':\n white = False\n if arr[i][j] == '0':\n blue = False\n if white == True:\n cnt_white += 1\n elif blue == True:\n cnt_blue += 1\n else:\n cutting(arr, n)\n\ndef cutting(arr, n):\n di = [0, n//2, 0, n//2, n//2, n, n//2, n]\n dj = [0, n//2, n//2, n, 0, n//2, n//2, n]\n\n for k in range(4):\n new_paper = []\n for i in range(di[k*2], di[k*2+1]):\n temp = ''\n for j in range(dj[k*2], dj[k*2+1]):\n temp += arr[i][j]\n new_paper.append(temp)\n\n color(new_paper, n//2)\n\ncolor(paper, n)\n\nprint(cnt_white)\nprint(cnt_blue)","repo_name":"chadireoroonu/TIL","sub_path":"02_algorithm/03057/2630_color_paper/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"28103816012","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse, Http404\nfrom Blog.models import Post\n\n\n# Create your views here.\n\n\ndef index(request):\n return HttpResponse(\"index\")\n\n\ndef post_list(request):\n posts = Post.published.all()\n context = {\n \"posts\": posts\n }\n return render(request, \"blog/list.html\", context)\n\n\ndef post_detail(request, id):\n\n post = get_object_or_404(Post, id=id, status=Post.Status.PUBLISHED)\n context = {\n \"post\": post,\n }\n return render(request, \"blog/detail.html\", context)\n","repo_name":"ARYAN-NIKNEZHAD/Blog","sub_path":"Blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"34"} +{"seq_id":"11888724792","text":"#詞頻分析\nimport os\n\npath = \"C:\\\\Users\\\\TibeMe_user\\\\Desktop\\\\Project\\\\article\\\\TSLA\" #資料夾目錄\nfiles= os.listdir(path) #得到資料夾下的所有檔名稱\n\ndef gettext(file):\n txt = open(file, \"r\", errors='ignore').read()\n txt = txt.lower()\n for ch in '!\"#$&()*+,-./:;<=>?@[\\\\]_{|}~':\n txt = txt.replace(ch, \"\")\n return txt\n\ncounts = {}\nfor file in files: #遍歷資料夾\n if not os.path.isdir(file): #判斷是否是資料夾,不是資料夾才打開\n f = path + \"\\\\\" + file #檔案名稱\n txt = gettext(f)\n words = txt.split()\n\n for word in words:\n counts[word] = counts.get(word, 0) + 1\n\nitems = list(counts.items())\nitems.sort(key=lambda x:x[1], reverse=True)\n#輸出前十字詞\nfor i in range(100):\n word, count = items[i]\n print(\"{0:<10}{1:>5}\".format(word, count))","repo_name":"yijhenjhen/pythonProject","sub_path":"WordFrequencyAnalysis.py","file_name":"WordFrequencyAnalysis.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"4895217060","text":"#!/usr/bin/env python3\n\nimport sys\nimport os\nimport time\nfrom os import listdir\nfrom os.path import isfile, join, getsize\nfrom optparse import OptionParser\nimport subprocess\nfrom sys import stdout, stderr\n\n__basePath = os.path.dirname(sys.argv[0])\n__execFolder = \"solvers\"\n__tmpFolder = \"tmp\"\n__tboxFolder = \"tbox\"\n__aboxFolder = \"abox\"\n__resultFilename = \"results.txt\"\n__relevPredsFilename = \"relevPreds.txt\"\n__dlv = \"dlv\"\n__dlvSK = \"dlv\"\n__dlvEx = \"dlvEx\"\n__owl2dpm = \"owl2dpm.jar\"\n__tstore2facts = \"tstore2facts.jar\"\n__skolemizeScript = \"skolemize.py\"\n__dlvRelevPreds = \"dlvRelevPreds\"\n\ndef errorMessage(msg):\n sys.stderr.write(\"Error: \"+msg.__str__()+\"\\n\")\n sys.exit()\n\ndef manageOptions():\n usage = \"usage: %prog [options] [filenames] (if no options are given it behaves like DLV)\"\n parser = OptionParser(usage=usage)\n parser.add_option(\"--mode\",action=\"store\",type=\"string\",dest=\"mode\",\n help=\"set execution mode (a value from {'obqa','clear-workspace','asp','load-results'}\")\n parser.add_option(\"--import\",action=\"store\",type=\"string\",dest=\"inputFormalism\",\n help=\"specify an input formalism between 'owl' (OWL2) and 'dpm' (Datalog+/-)\")\n parser.add_option(\"--run\",action=\"store\",type=\"string\",dest=\"run\",\n help=\"\"\"choose a strategy (a value from {'pchase','datarewclip','skdlv'} and evaluate the \n input query after converting the input knowledge base, if needed (valid only in 'obqa' mode)\"\"\")\n parser.add_option(\"--tbox\",action=\"store\",type=\"string\",dest=\"tbox\",\n help=\"set the tbox folder name (a valid path to be given)\")\n parser.add_option(\"--abox\",action=\"store\",type=\"string\",dest=\"abox\",\n help=\"set the abox folder name (a valid path to be given)\")\n parser.add_option(\"--kb\",action=\"store\",type=\"string\",dest=\"kb\",\n help=\"set the kb folder name (a valid path to be given)\")\n parser.add_option(\"--query\",action=\"store\",type=\"string\",dest=\"query\",\n help=\"set the query file name (a valid path to be given)\")\n parser.add_option(\"--cautious\",action=\"store_true\",default=False,dest=\"cautious\",\n help=\"run DLV under the cautious assumption (valid only in 'asp' mode)\")\n parser.add_option(\"--brave\",action=\"store_true\",default=False,dest=\"brave\",\n help=\"run DLV under the brave assumption (valid only in 'asp' mode)\")\n return parser.parse_args()\n\ndef getBenchFolder(benchFolder):\n folderPath = os.path.abspath(benchFolder)\n localFolderName = os.path.abspath(os.path.join(folderPath, os.pardir)).__str__().replace(\"/\",\"_\")\n localFolderPath = os.path.join(__basePath,__tmpFolder,localFolderName)\n return localFolderPath\n\ndef manageBenchFolders(inputFolderName,outputFolderName):\n localFolderPath = getBenchFolder(inputFolderName)\n if os.path.exists(os.path.join(localFolderPath,outputFolderName)):\n subprocess.call([\"rm\",\"-r\",os.path.join(localFolderPath,outputFolderName)])\n if not os.path.exists(os.path.join(__basePath,__tmpFolder)):\n subprocess.call([\"mkdir\",os.path.join(__basePath,__tmpFolder)])\n if not os.path.exists(localFolderPath):\n subprocess.call([\"mkdir\",localFolderPath])\n subprocess.call([\"mkdir\",os.path.join(localFolderPath,outputFolderName)])\n return os.path.join(localFolderPath,outputFolderName)\n\ndef processTBox(inputFolder,formalism):\n if not os.path.isdir(inputFolder):\n errorMessage(inputFolder.__str__()+\" is not a valid folder\")\n outputFolder = manageBenchFolders(inputFolder,__tboxFolder)\n inputPath = os.path.abspath(inputFolder) \n execPath = os.path.join(__execFolder,__owl2dpm)\n for file in os.listdir(inputPath):\n srcFile = os.path.join(inputPath,file)\n trgFile = os.path.join(outputFolder,file.__str__().replace(\".owl\",\"_owl\")+\".rul\")\n subprocess.call([\"java\",\"-jar\",execPath,srcFile,trgFile])\n return outputFolder\n\ndef processABox(inputFolder,formalism):\n if not os.path.isdir(inputFolder):\n errorMessage(inputFolder.__str__()+\" is not a valid folder\")\n outputFolder = manageBenchFolders(inputFolder,__aboxFolder) \n inputPath = os.path.abspath(inputFolder)\n execPath = os.path.join(__execFolder,__tstore2facts)\n subprocess.call([\"java\",\"-Xmx8192m\",\"-DentityExpansionLimit=100000000\",\"-jar\",execPath,inputPath,outputFolder])\n return outputFolder\n\ndef checkRunningFolder(inputFolder,outputFolder):\n localFolderPath = getBenchFolder(inputFolder)\n if os.path.exists(os.path.join(localFolderPath,outputFolder)):\n return os.path.join(localFolderPath,outputFolder)\n if not os.path.exists(os.path.join(__basePath,__tmpFolder)):\n subprocess.call([\"mkdir\",os.path.join(__basePath,__tmpFolder)])\n if not os.path.exists(localFolderPath):\n subprocess.call([\"mkdir\",localFolderPath])\n subprocess.call([\"mkdir\",os.path.join(localFolderPath,outputFolder)])\n for file in os.listdir(inputFolder):\n subprocess.call([\"cp\",os.path.join(inputFolder,file),os.path.join(localFolderPath,outputFolder,file)])\n return os.path.join(localFolderPath,outputFolder)\n\ndef obqa(approach,rulFolder,dataFolder,queryFile):\n if approach == \"pchase\":\n execPath = os.path.join(__execFolder,__dlvEx)\n rulFiles = [os.path.join(rulFolder,fpath) for fpath in os.listdir(rulFolder)]\n dataFiles = [os.path.join(dataFolder,fpath) for fpath in os.listdir(dataFolder)]\n inputDLVEx = [execPath]+rulFiles+dataFiles+[queryFile]+[\"-cautious\",\"-silent\",\"-nofinitecheck\",\"-ODMS+\"]\n with open(os.path.join(__basePath,__resultFilename),'w+') as resultFile:\n subprocess.call(inputDLVEx,stdout=resultFile)\n elif approach == \"skdlv\":\n rulFiles = [os.path.join(rulFolder,fpath) for fpath in os.listdir(rulFolder)]\n #skolemize the input ontology\n skPath = os.path.join(__execFolder,__skolemizeScript)\n skRulFiles = []\n for file in rulFiles:\n skFile = file.__str__()+\"__sk__\"\n subprocess.call([skPath,file,skFile])\n skRulFiles.append(skFile)\n #compute relevant predicates\n dlvRelevPredsPath = os.path.join(__execFolder,__dlvRelevPreds)\n with open(os.path.join(__basePath,__tmpFolder,__relevPredsFilename),'w+') as relevPredsFile:\n subprocess.call([dlvRelevPredsPath]+rulFiles+[queryFile]+[\"-cautious\",\"-silent\",\"-nofinitecheck\"],stderr=relevPredsFile)\n with open(os.path.join(__basePath,__tmpFolder,__relevPredsFilename)) as relevPredsFile:\n relevPredsList = [line.strip(\"\\n\") for line in relevPredsFile]\n #filter out any data file not relevant for the query at hand\n dataFiles = [os.path.join(dataFolder,fpath) for fpath in os.listdir(dataFolder) if fpath[:-5] in relevPredsList]\n #skolemize the input query: TODO!!!\n dlvSKPath = os.path.join(__execFolder,__dlvSK)\n inputDLVSK = [dlvSKPath]+skRulFiles+dataFiles+[queryFile]+[\"-cautious\",\"-silent\",\"-nofinitecheck\",\"-ODMS+\"]\n with open(os.path.join(__basePath,__resultFilename),'w+') as resultFile:\n subprocess.call(inputDLVSK,stdout=resultFile)\n #delete temporary files\n subprocess.call([\"rm\",os.path.join(__basePath,__tmpFolder,__relevPredsFilename)])\n for skFile in skRulFiles:\n subprocess.call([\"rm\",skFile])\n else:\n errorMessage(\"Approach not supported yet\")\n \n\nif __name__ == '__main__': \n (option,args) = manageOptions()\n optionList = [o for o in sys.argv[1:] if o.__str__().startswith(\"-\")]\n \n if len(optionList) == 0: #no options, hence run DLV\n print(\"Running... \",end='')\n runningStart = time.time()\n execPath = os.path.join(__basePath,__execFolder,__dlv)\n params = [execPath] + ['-silent'] + sys.argv[1:]\n subprocess.call(params)\n runningEnd = time.time()\n print(\"Completed in \"+str('%.3f'%(runningEnd-runningStart))+\" secs\")\n sys.exit()\n \n if option.mode == None:\n errorMessage(\"execution mode not set\")\n if len(args) > 0:\n errorMessage(\"commands not found ({})\".format(args))\n \n print(\"Started...\")\n #######___OBQA mode___#######\n if option.mode == \"obqa\": \n if option.cautious != False or option.brave != False:\n errorMessage(\"reasoning policy (brave or cautious) can be specified only in 'asp' mode\")\n if option.inputFormalism == None and option.run == None:\n errorMessage(\"neither 'import' nor 'run' command specified in 'obqa' mode\")\n \n rulFolder=None\n dataFolder=None\n \n print(\"Input pre-processing... \",end='')\n importStart = time.time()\n if option.inputFormalism != None:\n if option.inputFormalism != \"owl\" and option.inputFormalism != \"dpm\":\n errorMessage(\"input formalism not known\")\n if option.inputFormalism == \"owl\" and (option.tbox == None or option.abox == None):\n errorMessage(\"no input folders (tbox or abox)\")\n if option.inputFormalism == \"owl\" and option.kb != None:\n errorMessage(\"--kb option cannot be specified when input is in OWL (use --tbox and --abox options)\")\n if option.inputFormalism == \"dpm\" and option.kb != None and (option.tbox != None or option.abox != None):\n errorMessage(\"--kb option cannot be specified together with --tbox or --abox options\")\n \n #manage input knowledge base\n if option.tbox != None:\n rulFolder = processTBox(option.tbox,option.inputFormalism)\n if option.abox != None:\n dataFolder = processABox(option.abox,option.inputFormalism)\n if option.kb != None:\n processKB(option.kb)\n importEnd = time.time()\n print(\"Completed in \"+str('%.3f'%(importEnd-importStart))+\" secs\")\n else:\n print(\"Not required\")\n \n print(\"Running... \",end='')\n runningStart = time.time()\n if option.run != None:\n if option.run != \"pchase\" and option.run != \"datarewclip\" and option.run != \"skdlv\":\n errorMessage(\"approach not known\")\n if (option.tbox == None or option.abox == None) and option.kb == None:\n errorMessage(\"no input folders (tbox, abox or kb)\")\n if option.kb != None and (option.tbox != None or option.abox != None):\n errorMessage(\"kb and abox/tbox folders names cannot be specified together\")\n if option.query == None:\n errorMessage(\"no input query\")\n \n if rulFolder == None:\n rulFolder = checkRunningFolder(option.tbox,__tboxFolder)\n if dataFolder == None:\n dataFolder = checkRunningFolder(option.abox,__aboxFolder)\n obqa(option.run,rulFolder,dataFolder,option.query)\n runningEnd = time.time()\n print(\"Completed in \"+str('%.3f'%(runningEnd-runningStart))+\" secs\")\n else:\n print(\"Not required\")\n \n #######___CLEAR_WORKSPACE mode___#######\n elif option.mode == \"clear-workspace\":\n runningStart = time.time()\n tmpFolderPath = os.path.join(__basePath,__tmpFolder)\n if os.path.exists(tmpFolderPath):\n subprocess.call([\"rm\",\"-r\",tmpFolderPath])\n runningEnd = time.time()\n print(\"Completed in \"+str('%.3f'%(runningEnd-runningStart))+\" secs\")\n\n #######___ASP_mode___#######\n elif option.mode == \"asp\":\n print(\"Running... \",end='')\n runningStart = time.time()\n if option.brave == None and option.cautious == None:\n errorMessage(\"no reasoning strategy (neither brave nor cautious\")\n if option.brave == True and option.cautious == True:\n errorMessage(\"multiple reasoning strategies\")\n if (option.inputFormalism != None or option.abox != None or option.tbox != None or \n option.kb != None or option.run != None or option.query != None):\n errorMessage(\"options not valid\")\n \n if option.brave == True:\n asp(args,\"brave\")\n elif option.cautious == True:\n asp(args,\"cautious\")\n runningEnd = time.time()\n print(\"Completed in \"+str('%.3f'%(runningEnd-runningStart))+\" secs\") \n \n #######___LOAD_RESULTS_mode___#######\n elif option.mode == \"load-results\":\n runningStart = time.time()\n resultPath = os.path.join(__basePath,__resultFilename)\n os.system(\"gedit \"+resultPath)\n runningEnd = time.time()\n print(\"Completed in \"+str('%.3f'%(runningEnd-runningStart))+\" secs\")\n sys.exit()\n else:\n errorMessage(\"execution mode not known\")\n \n","repo_name":"veltri/ScriptSamsung","sub_path":"owldlv.py","file_name":"owldlv.py","file_ext":"py","file_size_in_byte":12895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"7942212343","text":"import boto3\nimport json\nimport logging\n\nfrom base64 import b64decode\nfrom hashlib import md5\nfrom os import getenv\n\nfrom utils.notification_utils import parse_update_message\n\nLOGGER = logging.getLogger(__name__)\nLOGGER.setLevel(logging.INFO)\n\n\ndef get_kinesis():\n return boto3.client('kinesis')\n\n\ndef handler(event, context):\n body = event[\"body\"]\n LOGGER.info(\"Input Event Body: {}\".format(body))\n\n if event[\"isBase64Encoded\"]:\n body = b64decode(body)\n body_json = json.loads(body)\n\n transformed_msg = parse_update_message(body_json)\n\n data = json.dumps(transformed_msg).encode('utf-8')\n\n m = md5()\n m.update(data)\n pk = m.digest()\n\n kinesis_stream_name = getenv('STREAM_NAME')\n\n get_kinesis().put_record(\n StreamName=kinesis_stream_name,\n Data=data,\n PartitionKey=str(pk)\n )\n return {\"statusCode\": 204}\n","repo_name":"aws-samples/aws-proton-sample-lambda-data-processing-service","sub_path":"callback.py","file_name":"callback.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"34"} +{"seq_id":"33110704940","text":"\ndef inorder(n, last):\n global cnt\n if n <= last:\n inorder(n * 2, last)\n tree[n] = cnt\n cnt += 1\n inorder(n * 2 + 1, last)\n \n\n\nfor test_case in range(int(input())):\n N = int(input())\n tree = [0] * (N + 1)\n cnt=1\n inorder(1, N)\n print('#{} {} {}'.format(test_case+1, tree[1], tree[N // 2]))\n\n ","repo_name":"mjson1954/WIC","sub_path":"8. Tree/2_answer.py","file_name":"2_answer.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"43601610919","text":"# pyright: reportMissingTypeStubs=false\n# pyright: reportPrivateUsage=false\n# pyright: reportUnknownMemberType=false\nimport nltk\nimport ssl\nfrom typing import Literal\n\nfrom .abstract import AbstractCorpus\nfrom .bnc import BNCCorpus\nfrom .wiki import WikiCorpus\n\n# https://stackoverflow.com/questions/38916452/nltk-download-ssl-certificate-verify-failed\ntry:\n _create_unverified_https_context = ssl._create_unverified_context\nexcept AttributeError:\n pass\nelse:\n ssl._create_default_https_context = _create_unverified_https_context\n\nnltk.download(\"punkt\", quiet=True)\nnltk.download(\"averaged_perceptron_tagger\", quiet=True)\nnltk.download(\"universal_tagset\", quiet=True)\nnltk.download(\"wordnet\", quiet=True)\n\n\nCorpusName = Literal[\"BNC\", \"Simple English Wikipedia\"]\n\n\ndef get_corpus(corpus_name: CorpusName, seed: int, sample_size: float) -> AbstractCorpus:\n if corpus_name == \"BNC\":\n return BNCCorpus(seed=seed, sample_size=sample_size)\n elif corpus_name == \"Simple English Wikipedia\":\n return WikiCorpus(seed=seed, sample_size=sample_size)\n else:\n raise NotImplementedError\n","repo_name":"tslwn/function_words","sub_path":"corpora/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"36534450954","text":"\nclass Matrix():\n def __init__(self):\n self.array = []\n\n\n def __str__(self):\n answer = \"\"\n for i in range(len(self.array)):\n for j in range(len(self.array[0])):\n answer += str(self.array[i][j]) + \" \"\n answer += \"\\n\"\n return answer\n\n def add(self, other):\n if self.row != other.row or self.col != other.col:\n print(\"Matrix size is different!\")\n return None\n else:\n answerMatrix = Matrix()\n answer = []\n for i in range(self.row):\n tmp = []\n for j in range(self.col):\n tmp.append(self.array[i][j]+other.array[i][j])\n answer.append(tmp)\n answerMatrix.array = answer\n answerMatrix.row = len(answer)\n answerMatrix.col = len(answer[0])\n return answerMatrix\n\n def mult(self,other):\n if self.col != other.row:\n print(\"Matrix size is inappropriate\")\n return None\n else:\n answerMatrix = Matrix()\n answer = []\n for i in range(self.row):\n tmp = []\n for j in range(other.col):\n tmp.append(0)\n for k in range(self.col):\n tmp[-1] += self.array[i][k] * other.array[k][j]\n answer.append(tmp)\n answerMatrix.array = answer\n answerMatrix.row = len(answer)\n answerMatrix.col = len(answer[0])\n return answerMatrix\n\n def transpose(self):\n answerMatrix = Matrix()\n answer = []\n for i in range(self.col):\n tmp = []\n for j in range(self.row):\n tmp.append(0)\n answer.append(tmp)\n\n for i in range(self.row):\n for j in range(self.col):\n answer[j][i] = self.array[i][j]\n answerMatrix.array = answer\n answerMatrix.row = len(answer)\n answerMatrix.col = len(answer[0])\n return answerMatrix\n\n def isSymmetric(self):\n if self.row != self.col:\n print(\"The matrix is not square matrix, it cannot be symmetric\")\n return False\n else:\n for i in range(self.row):\n for j in range(i,self.col):\n if self.array[i][j] != self.array[j][i]: return False\n return True\n\n def isSame(self, other):\n if self.row != other.row or self.col != other.col:\n print(\"The dimension of the matrix is different\")\n return False\n else:\n for i in range(self.row):\n for j in range(self.col):\n if self.array[i][j] != other.array[i][j]: return False\n return True\n\n def power(self,n):\n if n == 1:\n return self\n else: return self.mult(self.power(n-1))\n\n\nclass NewMatrix(Matrix):\n def __init__(self, filename):\n self.array = []\n file = open(filename, 'r')\n self.row = 0\n for l in file:\n tmp = l.strip().split()\n self.col = len(tmp)\n for i in range(self.col):\n tmp[i] = int(tmp[i])\n self.array.append(tmp)\n self.row += 1\n\nclass IdentityMatrix(Matrix):\n def __init__(self, n):\n self.array=[]\n for i in range(n):\n tmp = []\n for j in range(n):\n if i == j:\n tmp.append(1)\n else:\n tmp.append(0)\n self.array.append(tmp)\n\n############################################\n# Part III\n### Problem 1\n##### (1)\nfa = \"a.txt\"\nfb = \"b.txt\"\n\na = NewMatrix(fa)\nb = NewMatrix(fb)\nprint(\"A = \\n\" + str(a))\nprint(\"B = \\n\" + str(b))\nprint(\"A + B = \\n\" + str(a.add(b)))\n\n##### (2)\nfa = \"c.txt\"\nfb = \"d.txt\"\n\na = NewMatrix(fa)\nb = NewMatrix(fb)\nprint(\"A = \\n\" + str(a))\nprint(\"B = \\n\" + str(b))\nprint(\"A*B = \\n\" + str(a.mult(b)))\n\n### Problem 2\nfa = \"e.txt\"\nfb = \"f.txt\"\n\na = NewMatrix(fa)\nb = NewMatrix(fb)\nprint(\"A = \\n\" + str(a))\nprint(\"B = \\n\" + str(b))\nprint(\"A*B = \\n\" + str(a.mult(b)))\n\nprint(\"I = \\n\" + str(IdentityMatrix(3)))\nprint(IdentityMatrix(3).array == a.mult(b).array)\nprint()\n\n### Problem 3\nfa = \"e.txt\"\n\na = NewMatrix(fa)\nprint(\"A = \\n\" + str(a))\nprint(\"A^10 = \\n\" + str(a.power(10)))","repo_name":"rokrokss/KAIST-Classes","sub_path":"CS206_Data_Structure/Project1/Proj1.py","file_name":"Proj1.py","file_ext":"py","file_size_in_byte":4347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"19425190146","text":"\nfrom pycocoevalcap.tokenizer.ptbtokenizer import PTBTokenizer\nfrom pycocoevalcap.bleu.bleu import Bleu\nfrom pycocoevalcap.meteor.meteor import Meteor\nfrom pycocoevalcap.rouge.rouge import Rouge\nfrom pycocoevalcap.cider.cider import Cider\n\nclass COCOEvalCap:\n def __init__(self,images,gts,res):\n self.evalImgs = []\n self.eval = {}\n self.imgToEval = {}\n self.params = {'image_id': images}\n self.gts = gts\n self.res = res\n\n def evaluate(self):\n imgIds = self.params['image_id']\n gts = self.gts\n res = self.res\n\n # =================================================\n # Set up scorers\n # =================================================\n tokenizer = PTBTokenizer()\n gts = tokenizer.tokenize(gts)\n res = tokenizer.tokenize(res)\n\n # =================================================\n # Set up scorers\n # =================================================\n scorers = [\n (Bleu(4), [\"Bleu_1\", \"Bleu_2\", \"Bleu_3\", \"Bleu_4\"]),\n (Meteor(),\"METEOR\"),\n (Cider(), \"CIDEr\")\n ]\n\n # =================================================\n # Compute scores\n # =================================================\n eval = {}\n for scorer, method in scorers:\n score, scores = scorer.compute_score(gts, res)\n if type(method) == list:\n for sc, scs, m in zip(score, scores, method):\n self.setEval(sc, m)\n self.setImgToEvalImgs(scs, imgIds, m)\n else:\n self.setEval(score, method)\n self.setImgToEvalImgs(scores, imgIds, method)\n self.setEvalImgs()\n\n def setEval(self, score, method):\n self.eval[method] = score\n\n def setImgToEvalImgs(self, scores, imgIds, method):\n for imgId, score in zip(imgIds, scores):\n if not imgId in self.imgToEval:\n self.imgToEval[imgId] = {}\n self.imgToEval[imgId][\"image_id\"] = imgId\n self.imgToEval[imgId][method] = score\n\n def setEvalImgs(self):\n self.evalImgs = [eval for imgId, eval in self.imgToEval.items()]\n","repo_name":"SathwikTejaswi/Neural-Image-Captioning","sub_path":"utils/pycocoeval.py","file_name":"pycocoeval.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"34"} +{"seq_id":"15064127221","text":"def solution(sizes):\n max_a, max_b = 0, 0\n\n for i in range(len(sizes)):\n # a는 두변중 긴변들만, b는 두변중 작은 변들만 모아놓는다고 생각\n a = max(sizes[i][0], sizes[i][1])\n b = min(sizes[i][0], sizes[i][1])\n\n max_a = max(max_a, a)\n max_b = max(max_b, b)\n\n return max_a*max_b\n\n\nprint(solution([[60, 50], [30, 70], [60, 30], [80, 40]]))\nprint(solution([[10, 7], [12, 3], [8, 15], [14, 7], [5, 15]]))","repo_name":"zoog15/BOJ","sub_path":"2. Programmers_Lv1/최소직사각형.py","file_name":"최소직사각형.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"28556688402","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 15 12:31:07 2020\n\n@author: qwang\n\"\"\"\n\nfrom transformers import TransfoXLConfig, TransfoXLPreTrainedModel, TransfoXLTokenizer, TransfoXLModel\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\n\ntokenizer = TransfoXLTokenizer.from_pretrained('transfo-xl-wt103')\ntext = \"Hello, my dog is cute\"\n\n# tokenizer.encode => tokenizer.convert_tokens_to_ids(tokenizer.tokenize(text))\ntokens = tokenizer.tokenize(text, add_special_tokens=True, add_space_before_punct_symbol=True)\ntoken_ids = tokenizer.convert_tokens_to_ids(tokens)\n\nmodel = TransfoXLModel.from_pretrained('transfo-xl-wt103')\n\noutputs = model(torch.tensor(token_ids).unsqueeze(0))\nlast_hidden_states, mems = outputs[:2]\n\n\n#%%\nclass TransfoXLLSTM(TransfoXLPreTrainedModel):\n \n def __init__(self, config: TransfoXLConfig):\n super().__init__(config)\n \n self.transformer = TransfoXLModel(config)\n \n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n \n self.lstm = nn.LSTM(input_size = config.hidden_size, hidden_size = config.hidden_size,\n num_layers = 1, dropout = 0, \n batch_first = True, bidirectional = False)\n \n self.fc = nn.Linear(config.hidden_size*3, config.num_labels)\n self.fc_bn = nn.BatchNorm1d(config.num_labels)\n\n self.init_weights()\n\n \n\n def forward(self, input_ids=None, mems=None, head_mask=None, inputs_embeds=None, labels=None):\n \"\"\" \n Input:\n doc: [batch_size, ??, ?, ??] [batch_size, seq_len, 3, max_chunk_len] \n Returns:\n out: [batch_size, output_dim] \n\n \"\"\"\n\n transfo_outputs = self.transformer(input_ids, mems=mems, \n head_mask=head_mask, \n inputs_embeds=inputs_embeds)\n \n\n\n last_hidden_states = transfo_outputs[0] # [batch_size, seq_len, hidden_size]\n \n dp = self.dropout(last_hidden_states) # [batch_size, seq_len, hidden_size]\n # output: [batch_size, seq_len, n_directions*hidden_size], output features from last layer for each t\n # h_n: [n_layers*n_directions, batch_size, hidden_size], hidden state for t=seq_len\n # c_n: [n_layers*n_directions, batch_size, hidden_size], cell state fir t=seq_len\n output, (h_n, c_n) = self.lstm(dp)\n \n # Concat pooling\n h_n = h_n.squeeze(0) # [batch_size, hidden_size]\n h_max = torch.max(output, dim=1).values # [batch_size, hidden_size]\n h_mean = torch.mean(output, dim=1) # [batch_size, hidden_size]\n out = torch.cat((h_n, h_max, h_mean), dim=1) # [batch_size, hidden_size*3]\n \n out = self.fc(out) # [batch_size, num_labels] \n out = self.fc_bn(out)\n out = F.softmax(out, dim=1) # [batch_size, num_labels]\n\n return out \n\n","repo_name":"qianyingw/rob-kiwi","sub_path":"transfo/model_txl.py","file_name":"model_txl.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"34"} +{"seq_id":"23248750685","text":"\nimport torch\nimport numpy as np\nfrom botorch.utils.multi_objective.box_decompositions import NondominatedPartitioning\nfrom botorch.optim import optimize_acqf_discrete\nfrom botorch.acquisition.multi_objective.monte_carlo import qExpectedHypervolumeImprovement\nfrom botorch.sampling.samplers import SobolQMCNormalSampler\nimport pareto\nfrom scipy.stats import norm\n\n\ndef acq_multiobjective_EHVI(model, train_y, test_x, ref_points):\n partitioning = NondominatedPartitioning(\n ref_point=ref_points,\n Y=torch.tensor(train_y))\n\n sampler = SobolQMCNormalSampler(num_samples=512, collapse_batch_dims=False)\n\n EHVI = qExpectedHypervolumeImprovement(\n model=model,\n ref_point=ref_points, # use known reference point\n partitioning=partitioning,\n sampler=sampler,\n )\n\n acq = optimize_acqf_discrete(\n acq_function=EHVI,\n choices=test_x,\n q=1,\n unique=True\n )[0][0].detach().numpy().tolist()\n\n return acq\n\n\ndef acq_multiobjective_MOUCB(model, train_y, test_x, v=1, delta=.1,\n greedy=False):\n\n # UCB paramters.\n t = np.shape(train_y)[0] # t: number of iterations.\n d = np.shape(test_x)[1] # d: number of dimensions.\n\n try:\n kappa = np.sqrt(v * (2 * np.log((t**(d/2. + 2))*(np.pi**2)/(3. * delta))))\n except:\n d = 10\n kappa = np.sqrt(v * (2 * np.log((t ** (d / 2. + 2)) * (np.pi ** 2) / (3. * delta))))\n\n if greedy is True:\n kappa = 0\n\n # Build pareto train.\n pareto_train_y = pareto.eps_sort(tables=train_y, maximize_all=True)\n pareto_train_y = np.reshape(pareto_train_y, (-1, model.num_outputs))\n\n # Predict in all models.\n means = model.posterior(test_x).mean.detach().numpy()\n variances = model.posterior(test_x).variance.detach().numpy()\n\n dmaximin = []\n for i in range(0, len(means)):\n diff_pareto_to_test = (means[i] + kappa * variances[i]) - pareto_train_y\n dmin_i = np.min(diff_pareto_to_test, axis=0)\n if greedy is False:\n dmin_i[dmin_i < 0] = 0\n dmaximin_i = np.max(dmin_i)\n dmaximin.append(dmaximin_i)\n\n best_sample = test_x[np.argmax(dmaximin)].detach().numpy().tolist()\n return best_sample\n\n# def acq_multiobjective_MESMO(model, test_x):\n#\n# def dummy_sample_pareto_frontiers(model):\n# m = model.models[0] if isinstance(model, ModelListGP) else model\n# return torch.rand(\n# 3,\n# 4,\n# model.num_outputs,\n# dtype=m.train_inputs[0].dtype,\n# device=m.train_inputs[0].device,\n# )\n# #\n# # def sample_pareto_front(model):\n# # import pareto\n# # n_samples = 10\n# # n_objectives = np.shape(test_x)[1]\n# #\n# # def function_to_optimize(x):\n# # x_torch = to_torch(x)\n# # test_y = model.posterior(x_torch).mean.detach().numpy()\n# # return test_y\n# #\n# #\n# # for sample in range(0, n_samples):\n# # # 1. Select a random test_x.\n# # # 2. Optimize the random test_x, obtain pareto.\n# # # 3.\n# #\n# # pareto_points = pareto.eps_sort(tables=test_y,\n# # maximize_all=True)\n# # pareto_points = np.reshape(pareto_points, (-1, n_objectives))\n# #\n#\n#\n# # pareto_front = is_non_dominated(Y=to_torch(train_y))\n# MESMO = qMultiObjectiveMaxValueEntropy(\n# model=model,\n# sample_pareto_frontiers=dummy_sample_pareto_frontiers,\n# num_fantasies=16\n# )\n# acq = optimize_acqf_discrete(\n# acq_function=MESMO,\n# choices=test_x,\n# q=1,\n# unique=True\n# )[0][0].detach().numpy().tolist()\n# return acq\n\n\ndef acq_EI(y_best, predictions, uncertainty, objective='max'):\n \"\"\"Return expected improvement acq. function.\n Parameters\n ----------\n y_best : float\n Condition\n predictions : list\n Predicted means.\n uncertainty : list\n Uncertainties associated with the predictions.\n objective: str\n Choices are 'min' or 'max' for minimization and maximization respectively.\n \"\"\"\n if objective == 'max':\n z = (predictions - y_best) / (uncertainty)\n return (predictions - y_best) * norm.cdf(z) + \\\n uncertainty * norm.pdf(\n z)\n\n if objective == 'min':\n z = (-predictions + y_best) / (uncertainty)\n return -((predictions - y_best) * norm.cdf(z) -\n uncertainty * norm.pdf(z))","repo_name":"TheCoffeeSquad/git_edbo_fork","sub_path":"edbo/plus/acquisition.py","file_name":"acquisition.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"31155873869","text":"import unittest\nimport logging\nimport random\nimport math\nimport chip.mac\nimport chip.phy\nimport chip.mlme as mlme\n\nclass TestGetSet( unittest.TestCase):\n def setUp( self):\n logging.basicConfig( format = '%(asctime)s %(message)s', \\\n filename = 'test_get_set.log', \\\n filrmode = 'w+', \\\n level = logging.DEBUG)\n self.phy = chip.phy.OQPSKPhy( chip.phy.band.MHz_780)\n self.dut = chip.mac.Mac( self.phy)\n\n def set_param( self, param, lower, upper):\n val = random.randint( lower - 100, math.ceil( 1.5 * upper))\n set_result = self.dut.command( mlme.set.request( param, val))\n self.assertTrue( isinstance( set_result, mlme.set.confirm))\n # perform MLME-GET as well\n get_result = self.dut.command( mlme.get.request( param))\n self.assertTrue( isinstance( get_result, mlme.get.confirm))\n \n if lower <= val <= upper:\n self.assertEqual( set_result.status, chip.mac.status.SUCCESS)\n self.assertEqual( set_result.status, get_result.status)\n else:\n self.assertEqual( set_result.status, chip.mac.status.INVALID_PARAMETER)\n self.assertEqual( self.dut.pib[get_result.PIBAttribute][0],\n get_result.PIBAttributeValue)\n\n result = self.dut.command( mlme.get.request( param))\n self.assertTrue( isinstance( result, mlme.get.confirm))\n \n def test_reset( self):\n result = self.dut.command( mlme.reset.request( True))\n self.assertTrue( isinstance( result, mlme.reset.confirm))\n self.assertEqual( result.status, chip.mac.status.SUCCESS)\n\n def test_get_set_wrong_attr( self):\n result = self.dut.command( mlme.set.request( \"macWrongAttr\", True))\n self.assertTrue( isinstance( result, mlme.set.confirm))\n self.assertEqual( result.status, chip.mac.status.UNSUPPORTED_ATTRIBUTE)\n self.assertEqual( result.PIBAttribute, \"macWrongAttr\") \n result = self.dut.command( mlme.get.request( \"macWrongAttr\"))\n self.assertTrue( isinstance( result, mlme.get.confirm))\n self.assertEqual( result.status, chip.mac.status.UNSUPPORTED_ATTRIBUTE)\n self.assertEqual( result.PIBAttribute, \"macWrongAttr\") \n \n def test_read_only( self):\n for param in [\"macExtendedAddress\",\n \"macCoordExtendedAddress\",\n \"macMaxFrameTotalWaitTime\",\n \"macLIFSPeriod\",\n \"macSIFSPeriod\",\n \"macRangingSupported\",\n \"macTimestampSupported\"]:\n set_result = self.dut.command( mlme.set.request( param, True))\n self.assertTrue( isinstance( set_result, mlme.set.confirm))\n self.assertEqual( set_result.status, chip.mac.status.READ_ONLY)\n # perform MLME-GET as well\n get_result = self.dut.command( mlme.get.request( param))\n self.assertTrue( isinstance( get_result, mlme.get.confirm))\n self.assertEqual( self.dut.pib[get_result.PIBAttribute][0],\n get_result.PIBAttributeValue)\n\n\n def test_set_get( self):\n self.set_param( \"macBattLifeExt\", False, True)\n self.set_param( \"macBattLifeExtPeriods\", 6, 41)\n self.set_param( \"macBeaconPayload\",\n 0, 2 ** ( 8 * self.dut.pib['macBeaconPayloadLength'][0]))\n self.set_param( \"macBeaconPayloadLength\",\n 0, chip.mac.constants.aMaxBeaconPayloadLength)\n self.set_param( \"macBeaconOrder\", 0, 15)\n self.set_param( \"macBeaconTxTime\",\n int( '0x000000', 16), int( '0xffffff', 16))\n self.set_param( \"macBSN\",\n int( '0x00', 16), int( '0xff', 16))\n self.set_param( \"macCoordShortAddress\",\n int( '0x0000', 16), int( '0xffff', 16))\n self.set_param( \"macBSN\",\n int( '0x00', 16), int( '0xff', 16))\n self.set_param( \"macGTSPermit\", False, True)\n self.set_param( \"macMaxBE\" , 3, 8)\n self.set_param( \"macMaxCSMABackoffs\", 0, 5)\n self.set_param( \"macMaxFrameRetries\", 0, 7)\n self.set_param( \"macMinBE\", 0, self.dut.pib['macMaxBE'][0])\n self.set_param( \"macPANId\",\n int( '0x0000', 16), int( '0xffff', 16))\n self.set_param( \"macPromiscuousMode\", False, True)\n self.set_param( \"macResponseWaitTime\", 2, 64)\n self.set_param( \"macRxOnWhenIdle\", False, True)\n self.set_param( \"macSecurityEnabled\", False, True)\n self.set_param( \"macShortAddress\",\n int( '0x0000', 16), int( '0xffff', 16))\n self.set_param( \"macSuperframeOrder\", 0, 15)\n # FIXME: calculate range\n # self.set_param( \"macSyncSymbolOffset\", , )\n self.set_param( \"macTransactionPersistenceTime\",\n int( '0x0000', 16), int( '0xffff', 16))\n self.set_param( \"macTxControlActiveDuration\", 0, 100000)\n self.set_param( \"macTxControlPauseDuration\", 0, 100000)\n self.set_param( \"macTxTotalDuration\",\n int( '0x00000000', 16), int( '0xffffffff', 16))\n \n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"jkopanski/802.15.4","sub_path":"tests/test_get_set.py","file_name":"test_get_set.py","file_ext":"py","file_size_in_byte":5335,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"34"} +{"seq_id":"12674368752","text":"\"\"\"\nCreated on Apr 20, 2016\n\n@author: zimmer\n@brief: prototype script that handles config parsing etc.\n\n\"\"\"\nfrom ConfigParser import SafeConfigParser\nfrom os import environ, getenv\nfrom random import choice\nfrom os.path import dirname, abspath, join as oPjoin\n#import sys\nfrom DmpWorkflow import version as DAMPE_VERSION\n#from DmpWorkflow.utils.tools import exceptionHandler\n\nDAMPE_WORKFLOW_ROOT = dirname(dirname(abspath(__file__)))\n\n__myDefaults = {\n \"DAMPE_SW_DIR\": \".\",\n \"installation\": \"server\",\n \"setup\": \"Production\",\n \"ExternalsScript\": \"${DAMPE_SW_DIR}/setup/setup.sh\",\n \"use_debugger\": \"true\",\n \"use_reloader\": \"true\",\n \"use_profiler\": \"false\",\n \"workdir\": \".\",\n \"url\": \"\",\n \"traceback\": \"true\",\n \"task_types\": \"Generation,Digitization,Reconstruction,User,Other\".split(\",\"),\n \"task_major_statii\": \"New,Running,Failed,Terminated,Done,Submitted,Suspended\".split(\",\"),\n \"HPCsystem\": \"lsf\",\n \"HPCrequirements\": \"\",\n \"HPCextra\": \"\",\n \"HPCqueue\": \"\",\n \"HPCname\": \"default\",\n \"HPCcputime\": \"24:00\",\n \"HPCmemory\": \"1000.\",\n \"HPCusername\": \"dampeprod\",\n \"HPCclustername\" : \"None\",\n \"EXEC_DIR_ROOT\": \"/tmp\",\n \"ratio_mem\": \"1.0\",\n \"ratio_cpu\": \"1.0\",\n \"logfile\": \"/tmp/flask.log\",\n \"loglevel\": \"INFO\"\n}\n\ncfg = SafeConfigParser(defaults=__myDefaults)\n\ncfg.read(oPjoin(DAMPE_WORKFLOW_ROOT, \"config/settings.cfg\"))\n\nassert cfg.get(\"global\", \"installation\") in ['server', 'client'], \"installation must be server or client!\"\nDAMPE_BUILD = cfg.get(\"global\",\"installation\")\nenviron[\"DAMPE_BUILD\"] = DAMPE_BUILD\nenviron[\"DAMPE_SW_DIR\"] = cfg.get(\"site\", \"DAMPE_SW_DIR\")\nenviron[\"DAMPE_WORKFLOW_ROOT\"] = DAMPE_WORKFLOW_ROOT\n\n# environ[\"DAMPE_URL\"] = cfg.get(\"server\",\"url\")\n# print \"setting up externals\"\n# source_bash(cfg.get(\"site\", \"ExternalsScript\"))\n\ndbg = cfg.getboolean(\"global\", \"traceback\")\n#sys.excepthook = exceptionHandler\n\nDAMPE_WORKFLOW_URL = getenv(\"DAMPE_WORKFLOW_SERVER_URL\",cfg.get(\"server\", \"url\"))\n\n# for clients: support multiple servers.\nif DAMPE_BUILD == \"client\" and \",\" in DAMPE_WORKFLOW_URL:\n DAMPE_WORKFLOW_URL = choice(DAMPE_WORKFLOW_URL.split(\",\")) \n # some cleanup in syntax to get rid of extra whitespaces.\n while \" \" in DAMPE_WORKFLOW_URL:\n DAMPE_WORKFLOW_URL = DAMPE_WORKFLOW_URL.replace(\" \",\"\")\n\nDAMPE_WORKFLOW_DIR = cfg.get(\"site\", \"workdir\")\nEXEC_DIR_ROOT = cfg.get(\"site\", \"EXEC_DIR_ROOT\")\nenviron[\"DWF_SW_VERSION\"] = DAMPE_VERSION\nif DAMPE_BUILD == \"client\":\n environ[\"BATCH_SYSTEM\"] = cfg.get(\"site\", \"HPCsystem\")\n environ[\"BATCH_REQUIREMENTS\"] = cfg.get(\"site\", \"HPCrequirements\")\n environ[\"BATCH_EXTRA\"] = cfg.get(\"site\", \"HPCextra\")\n environ[\"BATCH_QUEUE\"] = cfg.get(\"site\", \"HPCqueue\")\n environ[\"BATCH_NAME\"] = cfg.get(\"site\", \"HPCname\")\nenviron[\"EXEC_DIR_ROOT\"] = EXEC_DIR_ROOT\n\nBATCH_DEFAULTS = {key: getenv(\"BATCH_%s\" % key.upper()) for key in ['system', 'requirements', 'extra', 'queue','name']}\nBATCH_DEFAULTS['image'] = cfg.get(\"site\",\"HPCimage\")\nBATCH_DEFAULTS['numcores']=cfg.get(\"site\",\"HPCnumcores\")\nBATCH_DEFAULTS['memory'] = cfg.get(\"site\", \"HPCmemory\")\nBATCH_DEFAULTS['cputime'] = cfg.get(\"site\", \"HPCcputime\")\nBATCH_DEFAULTS['name'] = cfg.get(\"site\", \"name\")\n\n# JobDB specifics\nMAJOR_STATII = tuple(\n [unicode(t) for t in cfg.get(\"JobDB\", \"task_major_statii\").split(\",\")] + [\"Unknown\"]) # adding unknown\nFINAL_STATII = tuple([unicode(t) for t in cfg.get(\"JobDB\", \"task_final_statii\").split(\",\")])\nTYPES = tuple([unicode(t) for t in cfg.get(\"JobDB\", \"task_types\").split(\",\")]+['Pilot'])\nSITES = tuple([unicode(t) for t in cfg.get(\"JobDB\", \"batch_sites\").split(\",\")])\n\n# verify that the site configuration is okay.\nif DAMPE_BUILD == \"client\":\n assert BATCH_DEFAULTS['name'] in cfg.get(\"JobDB\", \"batch_sites\"), \"Batch site %s not in DB\" % BATCH_DEFAULTS['name']\n assert BATCH_DEFAULTS['system'] in [\"lsf\", \"sge\", \"pbs\", \"condor\",\"slurm\",\"slurm-cscs\"], \"HPCSystem %s not supported.\" % BATCH_DEFAULTS[\"system\"]\n\nDAMPE_LOGFILE = cfg.get(\"global\", \"logfile\")\nDAMPE_LOGLEVEL= cfg.get(\"global\", \"loglevel\")","repo_name":"DAMPEEU/DmpWorkflow","sub_path":"DmpWorkflow/config/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":4065,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"34"} +{"seq_id":"24782152907","text":"# -*- coding: utf-8 -*-\n\nfrom .basic import CROSS, NON_ZERO, MAD\nfrom .ma import SMA\nfrom ..core.indicator_signal import register_signal_indicator\n\n# Commodity Channel Index, by Donald Lambert, 1980s\n# --------------------------------------------\ndef CCI(close, high, low, length = 14, c = None):\n c = float(c) if c and c > 0 else 0.015\n tp = (high + low + close) / 3.0\n mtp = SMA(tp, length)\n mad_tp = MAD(tp, length)\n cci = (tp - mtp) / NON_ZERO(mad_tp * c)\n return cci\n\ndef signal_cci(df, inplace=False, length=14):\n cci = CCI(df.close, df.high, df.low, length=length)\n if inplace:\n df['cci'], df['cci_upper'], df['cci_lower'] = cci, 100, -100\n cross_up = CROSS(cci, 100)\n cross_md = CROSS(cci, 0)\n cross_dn = CROSS(cci, -100)\n buy_signal = (cross_up > 0) | (cross_md > 0) | (cross_dn > 0)\n sell_signal = (cross_up < 0) | (cross_md < 0) | (cross_dn < 0)\n return buy_signal.astype(int) - sell_signal.astype(int)\n\nregister_signal_indicator('cci', signal_cci, ['cci', 'cci_upper', 'cci_lower'], 'CCI', 'obos')\n","repo_name":"floatinghotpot/hiquant","sub_path":"hiquant/indicator/cci.py","file_name":"cci.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"34"} +{"seq_id":"15551458344","text":"\nimport numpy as np\nfrom scipy.misc import derivative\ndef grdescent(func,w0,stepsize,maxiter,tolerance=1e-02):\n# INPUT:\n# func function to minimize\n# w_trained = initial weight vector\n# stepsize = initial gradient descent stepsize\n# tolerance = if norm(gradient)= loss:\n stepsize = stepsize * 1.01\n # print(stepsize)\n else:\n stepsize = stepsize * 0.5\n w = w - stepsize * gradient\n last_step_loss = loss # ????\n\n\n return w\n\n# from ridge import ridge\n# f = lambda w : ridge(w,xTr,yTr,1)\n# w_trained = grdescent (f,np.zeros((xTr.shape[0],1)),1e-06,1000)","repo_name":"Elfa-lu/WashU_SP2020.CSE517A_Machine-Learning","sub_path":"project1/grdscent.py","file_name":"grdscent.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"34"} +{"seq_id":"73434373537","text":"from inicio.models import Producto\nfrom django.shortcuts import render, redirect\nfrom inicio.form import BuscarProductoFormulario, CrearProductoFormulario\nfrom django.views.generic.edit import UpdateView, DeleteView\nfrom django.views.generic.detail import DetailView\nfrom django.urls import reverse_lazy\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom datetime import date\n\ndef inicio(request):\n return render(request, 'inicio/inicio.html')\n\ndef productos(request):\n return render(request, 'inicio/productos.html')\n\ndef acerca_de(request):\n return render(request, 'inicio/acerca_de.html')\n\n@login_required\ndef crear_producto(request):\n\n if request.method == 'POST':\n formulario = CrearProductoFormulario(request.POST, request.FILES)\n if formulario.is_valid():\n info = formulario.cleaned_data\n producto = Producto(\n nombre=info['nombre'],\n modelo=info['modelo'],\n precio=info['precio'],\n descripcion=info['descripcion'],\n numero_telefono=info['numero_telefono'],\n email_vendedor=request.user.email,\n imagen=info['imagen'],\n fecha_creacion=date.today(),\n usuario_vendedor=request.user.username\n )\n producto.save()\n return redirect('inicio:listar_productos')\n else:\n return render(request, 'inicio/crear_producto.html', {'formulario': formulario})\n\n formulario = CrearProductoFormulario()\n return render(request, 'inicio/crear_producto.html', {'formulario': formulario})\n\ndef listar_productos(request):\n formulario = BuscarProductoFormulario(request.GET)\n listado_de_productos = \"\"\n if formulario.is_valid():\n nombre_a_buscar = formulario.cleaned_data['nombre']\n listado_de_productos = Producto.objects.filter(nombre__icontains=nombre_a_buscar)\n \n formulario = BuscarProductoFormulario()\n return render(request, 'inicio/listar_productos.html', {'formulario': formulario, 'productos': listado_de_productos, 'busqueda': nombre_a_buscar})\n\n\nclass ModificarProducto(LoginRequiredMixin, UpdateView):\n model = Producto\n template_name = 'inicio/modificar_producto.html'\n fields = ['nombre', 'modelo', 'precio', 'numero_telefono', 'imagen', 'descripcion']\n success_url = reverse_lazy('inicio:listar_productos')\n \nclass EliminarProducto(LoginRequiredMixin, DeleteView):\n model = Producto\n template_name = 'inicio/eliminar_producto.html'\n success_url = reverse_lazy('inicio:listar_productos')\n\nclass MostrarProducto(DetailView):\n model = Producto\n template_name = 'inicio/mostrar_producto.html'\n\n","repo_name":"Florvasi25/Entrega-Final-Python-Django","sub_path":"inicio/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"20855869382","text":"\"\"\"Test the JSONRPC implementation to communicate with the GUI process.\"\"\"\n\nfrom time import sleep\nimport unittest\n\nimport pytest\nfrom mock import MagicMock, call, Mock\nfrom jars import StorageMetrics\n\nimport cc\nfrom cc import synctask\nfrom cc.ipc_gui import EventBatcher, ipc_gui_exception_decorator, on_task_acked\nfrom cc.synctask import SyncTask\n\n\ndef test_exception_decorator():\n \"\"\"tests that the exception wrapper works\"\"\"\n # assert that usual operation does not throw\n assert decorated_divide(10, 2) == 5\n\n # calling exception method\n assert decorated_divide(1, 0) is None\n\n\n@ipc_gui_exception_decorator\ndef decorated_divide(divisor, divider):\n \"\"\"example function that throws exception\"\"\"\n return divisor / divider\n\n\ndef test_batched_processing():\n \"\"\"tests the batch processing\"\"\"\n period = 1\n mock = MagicMock()\n mock.dummy_method.return_value = None\n batcher = EventBatcher(mock.dummy_method, period)\n batcher.process_event_batched('1')\n batcher.process_event_batched('2')\n batcher.process_event_batched('3')\n batcher.process_event_batched('4')\n batcher.process_event_batched('5')\n assert len(mock.dummy_method.mock_calls) == 0\n sleep(2)\n assert len(mock.dummy_method.mock_calls) == 1\n assert mock.dummy_method.mock_calls[0] == call(['1', '2', '3', '4', '5'])\n assert len(batcher.event_items) == 0\n batcher.process_event_batched('6')\n batcher.process_event_batched('7')\n batcher.process_event_batched('8')\n batcher.process_event_batched('9')\n batcher.process_event_batched('10')\n assert len(mock.dummy_method.mock_calls) == 1\n sleep(2)\n assert len(mock.dummy_method.mock_calls) == 2\n assert mock.dummy_method.mock_calls[1] == call(['6', '7', '8', '9', '10'])\n assert len(batcher.event_items) == 0\n\n\ndef test_batched_processing_single():\n \"\"\"tests the batch processing single event functionality\"\"\"\n period = 1\n mock = MagicMock()\n mock.dummy_method.return_value = None\n batcher = EventBatcher(mock.dummy_method, period, False)\n batcher.process_event_batched('1')\n batcher.process_event_batched('2')\n batcher.process_event_batched('3')\n batcher.process_event_batched('4')\n batcher.process_event_batched('5')\n assert len(mock.dummy_method.mock_calls) == 0\n sleep(2)\n assert len(mock.dummy_method.mock_calls) == 1\n assert mock.dummy_method.mock_calls[0] == call('5')\n assert len(batcher.event_items) == 0\n batcher.process_event_batched('6')\n batcher.process_event_batched('7')\n batcher.process_event_batched('8')\n batcher.process_event_batched('9')\n batcher.process_event_batched('10')\n assert len(mock.dummy_method.mock_calls) == 1\n sleep(2)\n assert len(mock.dummy_method.mock_calls) == 2\n assert mock.dummy_method.mock_calls[1] == call('10')\n assert len(batcher.event_items) == 0\n\n\ndef test_show_notification():\n \"\"\"tests the functionality of showing notifications\"\"\"\n # creating mock ipc object\n rpc_mock = MagicMock()\n cc.ipc_gui.rpc_object = rpc_mock\n\n title = 'title'\n description = 'description'\n path_to_image = ['path', 'to', 'image.png']\n path_to_action = ['path', 'to', 'action']\n cc.ipc_gui.displayNotification(\n title, description, path_to_image, path_to_action)\n\n args = {'title': title, 'description': description, 'imagePath': path_to_image,\n 'actionPath': path_to_action}\n\n sleep(3)\n\n # checking call\n rpc_mock.assert_called_once()\n _, kwargs = rpc_mock.call_args\n assert kwargs['method'] == 'displayNotification'\n\n # checking arguments\n arguments = kwargs['args'][0][0]\n assert arguments == args\n\n\ndef test_icon_path_creation():\n \"\"\"tests the creation of icons for synced elements in the gui\"\"\"\n icon_path = cc.ipc_gui.create_icon_name(['path', 'to', 'some', 'image.png'],\n 'dropbox')\n assert icon_path == icon_path == cc.ipc_gui.FILE_TYPE_IMAGE + \"_\" + \\\n cc.ipc_gui.DROPBOX_CSP_ICON + \\\n '.svg'\n\n icon_path = cc.ipc_gui.create_icon_name(['path', 'to', 'some', 'excel.xls'],\n 'gdrive')\n\n assert icon_path == icon_path == cc.ipc_gui.FILE_TYPE_XLS + \"_\" + \\\n cc.ipc_gui.GOOGLE_DRIVE_CSP_ICON \\\n + '.svg'\n\n icon_path = cc.ipc_gui.create_icon_name(\n ['path', 'to', 'some', 'word.doc'], 'gdrive')\n assert icon_path == icon_path == cc.ipc_gui.FILE_TYPE_DOC + \"_\" + \\\n cc.ipc_gui.GOOGLE_DRIVE_CSP_ICON \\\n + '.svg'\n\n icon_path = cc.ipc_gui.create_icon_name(['path', 'to', 'some', 'adobe.pdf'],\n 'onedrive')\n assert icon_path == icon_path == cc.ipc_gui.FILE_TYPE_PDF + \"_\" + \\\n cc.ipc_gui.ONEDRIVE_CSP_ICON + \\\n '.svg'\n\n icon_path = cc.ipc_gui.create_icon_name(['path', 'to', 'some',\n 'unknown.chricreatesextensions'], 'onedrive')\n assert icon_path == icon_path == cc.ipc_gui.FILE_TYPE_GENERAL + \"_\" + \\\n cc.ipc_gui.ONEDRIVE_CSP_ICON + \\\n '.svg'\n\n\ndef download_task(path):\n \"\"\"Factory for download task.\"\"\"\n return synctask.DownloadSyncTask(path=path,\n source_storage_id=None,\n source_version_id=None,\n target_path=[elm.upper() for elm in path])\n\n\ndef upload_task(path):\n \"\"\"Factory for upload task.\"\"\"\n return synctask.UploadSyncTask(path=path,\n target_storage_id=None,\n source_version_id=None,\n target_path=[elm.upper() for elm in path])\n\n\ndef delete_task(path):\n \"\"\"Factory for upload task.\"\"\"\n return synctask.DeleteSyncTask(path=path,\n target_storage_id=None,\n original_version_id=None,\n target_path=[elm.upper() for elm in path])\n\n\ndef create_dir_sync_task(path):\n \"\"\"Factory for upload tasks.\"\"\"\n return synctask.CreateDirSyncTask(path=path,\n source_storage_id=None,\n target_storage_id=None,\n source_version_id=None,\n target_path=[elm.upper() for elm in path])\n\n\n@pytest.mark.parametrize('task_factory', [upload_task,\n download_task,\n delete_task,\n create_dir_sync_task],\n ids=['upload', 'download', 'delete', 'create'])\ndef test_on_task_acked(mocker, task_factory):\n \"\"\"Test that various tasks are processed correctly when passed to on_task_acked.\"\"\"\n path = ['test.path.txt']\n task = task_factory(path)\n\n mock_item_batcher = mocker.patch('cc.ipc_gui.update_item_batcher')\n\n task.link = Mock()\n task.state = SyncTask.SUCCESSFUL\n task.link.metrics = StorageMetrics('blaid', 0)\n task.link.metrics.display_name = 'Holalala'\n task.state = SyncTask.SUCCESSFUL\n\n # time.strftime is used in on_task_acked\n freeze_time = '12:12'\n mocker.patch('cc.ipc_gui.strftime', return_value=freeze_time)\n\n # create_icon_name requires the csp_id.\n mocker.patch('cc.ipc_gui.create_icon_name', return_value='icon_name')\n\n # Make the call\n on_task_acked(task)\n\n expected_item = {'path': ['Holalala'] + [elm.upper() for elm in task.path],\n 'iconName': unittest.mock.ANY,\n 'operationType': task.DISPLAY_NAME,\n 'time': '12:12'}\n\n mock_item_batcher.process_event_batched.assert_called_once_with(expected_item)\n\n\n@pytest.mark.parametrize('task_factory', [upload_task,\n download_task,\n delete_task,\n create_dir_sync_task])\n@pytest.mark.parametrize('state', [SyncTask.UNEXECUTED,\n SyncTask.CURRENTLY_NOT_POSSIBLE,\n SyncTask.NOT_AVAILABLE,\n SyncTask.INVALID_OPERATION,\n SyncTask.INVALID_AUTHENTICATION,\n SyncTask.VERSION_ID_MISMATCH,\n SyncTask.CANCELLED,\n SyncTask.BLOCKED,\n SyncTask.ENCRYPTION_ACTIVATION_REQUIRED])\ndef test_on_task_acked_not_successful(task_factory, state, mocker):\n \"\"\"Test that various tasks are processed correctly when passed to on_task_acked.\"\"\"\n path = ['test.path.txt']\n task = task_factory(path)\n task.state = state\n\n task.link = Mock()\n task.link.metrics = StorageMetrics('blaid', 0)\n task.link.metrics.display_name = 'Holalala'\n\n mock_item_batcher = mocker.patch('cc.ipc_gui.update_item_batcher')\n\n # create_icon_name requires the csp_id.\n mocker.patch('cc.ipc_gui.create_icon_name', return_value='icon_name')\n\n # Make the call\n on_task_acked(task)\n\n assert not mock_item_batcher.process_event_batched.called\n\n\ndef compare_task(path):\n \"\"\"Factory for compare tasks.\"\"\"\n return synctask.CompareSyncTask(path, [])\n\n\ndef fetch_file_tree_task(path):\n \"\"\"Factory for fetch tree tasks.\"\"\"\n return synctask.FetchFileTreeTask(path)\n\n\ndef sync_task(path):\n \"\"\"Factory for sync tasks.\"\"\"\n return synctask.SyncTask(path)\n\n\ndef move_task(path):\n \"\"\"Factory for move tasks.\"\"\"\n return synctask.MoveSyncTask(path,\n source_version_id=None,\n source_storage_id=None, source_path=None, target_path=None)\n\n\n@pytest.mark.parametrize('task_factory', [compare_task,\n fetch_file_tree_task,\n sync_task,\n move_task],\n ids=['upload', 'download', 'delete', 'create'])\ndef test_ignore_on_task_ack(mocker, task_factory):\n \"\"\"The Gui should ignore the following tasks:\n * CompareSyncTasks\n * FetchFileTreeTask\n * SyncTask\n * CopySyncTask\n * MoveSyncTask\n \"\"\"\n path = ['test.path.txt']\n # task = synctask.CancelSyncTask(path)\n task = task_factory(path)\n\n task.link = Mock()\n task.link.metrics = StorageMetrics('blaid', 0)\n task.link.metrics.display_name = 'Holalala'\n\n task.display_in_ui = False\n mock_item_batcher = mocker.patch('cc.ipc_gui.update_item_batcher')\n on_task_acked(task)\n assert not mock_item_batcher.process_event_batched.called\n","repo_name":"crosscloudio/client","sub_path":"Core/tests/test_ipc_gui.py","file_name":"test_ipc_gui.py","file_ext":"py","file_size_in_byte":10747,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"34"} +{"seq_id":"25697444324","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.cross_validation import train_test_split\nimport utils\nimport glob, os\nimport pca.dataanalyzer as da\n\n\n# visulaize the important characteristics of the dataset\nimport matplotlib.pyplot as plt\n\ndata_len = 1460\nseed = 0\n# dirs = [\"C:/Users/salik/Documents/Data/LinuxChrome/{}/\".format(num_headers),\n# \"C:/Users/salik/Documents/Data/WindowsFirefox/{}/\".format(num_headers),\n# \"C:/Users/salik/Documents/Data/WindowsChrome/{}/\".format(num_headers),\n# \"C:/Users/salik/Documents/Data/WindowsSalik/{}/\".format(num_headers),\n# \"C:/Users/salik/Documents/Data/WindowsAndreas/{}/\".format(num_headers)]\ndirs = [\"E:/Data/h5/https/\", \"E:/Data/h5/netflix/\"]\n\n# step 1: get the data\ndataframes = []\nnum_examples = 0\nfor dir in dirs:\n for fullname in glob.iglob(dir + '*.h5'):\n filename = os.path.basename(fullname)\n df = utils.load_h5(dir, filename)\n dataframes.append(df)\n num_examples = len(df.values)\n # create one large dataframe\ndata = pd.concat(dataframes)\ndata.sample(frac=1, random_state=seed).reset_index(drop=True)\nnum_rows = data.shape[0]\ncolumns = data.columns\nprint(columns)\n\n# step 2: get x and convert it to numpy array\nx = da.getbytes(data, data_len)\n\n# step 3: get class labels y and then encode it into number\n# get class label data\ny = data['label'].values\n# encode the class label\nclass_labels = np.unique(y)\nlabel_encoder = LabelEncoder()\ny = label_encoder.fit_transform(y)\n# step 4: split the data into training set and test set\ntest_percentage = 0.5\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=test_percentage, random_state=seed)\nplot_savename = \"histogram_payload\"\n\nfrom matplotlib import rcParams\n# Make room for xlabel which is otherwise cut off\nrcParams.update({'figure.autolayout': True})\n# Heatmap plot how plot the sample points among 5 classes\nfor idx, cl in enumerate(np.unique(y_test)):\n plt.figure()\n print(\"Starting class: \" + class_labels[cl] +\" With len:\" + str(len(x_test[y_test == cl])))\n positioncounts = np.zeros(shape=(256, data_len))\n for x in x_test[y_test == cl]:\n for i, v in enumerate(x):\n positioncounts[int(v), i] += 1\n plt.imshow(positioncounts, cmap=\"YlGnBu\", interpolation='nearest')\n plt.title('Heatmap of : {}'.format(class_labels[cl]))\n plt.colorbar()\n plt.tight_layout()\n# plt.savefig('{0}{1}.png'.format(plot_savename, int(perplexity)), dpi=300)\nplt.show()","repo_name":"SalikLP/classification-of-encrypted-traffic","sub_path":"visualization/heatmap.py","file_name":"heatmap.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"34"} +{"seq_id":"71882293219","text":"from bs4 import BeautifulSoup\nimport requests\nimport time\nimport datetime\nfrom urllib import parse\n\n\ndef html_selector(url, selector, filter=lambda x: x.text):\n return list(map(filter, BeautifulSoup(requests.get(url).text, \"html.parser\").select(selector)))\n\n\ndef get_url_query(url):\n return dict(parse.parse_qsl(parse.urlparse(url).query))\n\n\ndef set_url(url, **kwargs): # query should be dict\n if kwargs.get(\"query\"):\n kwargs[\"query\"] = parse.urlencode(kwargs[\"query\"], doseq=True)\n return parse.urlunparse(parse.urlparse(url)._replace(**kwargs))\n\n\ndef replace_url(url, **kwargs):\n if kwargs.get(\"query\"):\n for key, value in get_url_query(url).items():\n kwargs[\"query\"][key] = value\n return set_url(url, **kwargs)\n\n\ndef dict_key_filter(data: dict, filter):\n filtered_dict = {}\n for arg in filter:\n filtered_dict[arg] = data.get(arg)\n return filtered_dict\n\n\nclass ProgressBar:\n def __init__(self, length, division=50, fill=\"=\"):\n self.count = 0\n self.length = length\n self.division = division\n self.fill = str(fill)\n self.start = time.time()\n\n def next(self):\n self.count += 1\n bar = int(self.count / self.length * self.division)\n percent = int(self.count / self.length * 100)\n self.end = time.time()\n average_time = (self.end - self.start) / self.count\n eta = datetime.timedelta(seconds=int(average_time * (self.length - self.count)))\n print(\n f\"process: [{self.fill*bar}{' '*(self.division-bar)}] | {percent:3d}% | {self.count}/{self.length} | eta: {eta}\",\n end=\"\\r\",\n )\n if self.count == self.length:\n print(f\"\\ntook {datetime.timedelta(seconds=self.end - self.start)}\")\n","repo_name":"lemontree1729/coding-academy","sub_path":"forfun/youtubeAPI/crawling.py","file_name":"crawling.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"25522823014","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\n\n# CSV 파일 읽기\ndf = pd.read_csv('place_reviews_seperated.csv')\n\n# '장소' column 삭제\ndf = df.drop(columns=['장소'])\n\n# '리뷰'와 '별점' column의 이름 변경\ndf = df.rename(columns={'리뷰': 'document', '별점': 'label'})\n\n# 'document'와 'label' column의 순서 변경\ndf = df[['document', 'label']]\n\n# 겹치지 않는 랜덤 숫자 생성하여 'id' column 생성\ndf['id'] = np.random.choice(range(1, df.shape[0] + 1), size=df.shape[0], replace=False)\n\n# 'id', 'document', 'label' column의 순서 변경\ndf = df[['id', 'document', 'label']]\n\n# 데이터를 train set과 test set으로 나눔 (98% training set, 2% test set)\ndf_train, df_test = train_test_split(df, test_size=0.02)\n\n# Train set과 test set을 txt 파일로 저장\ndf_train.to_csv('place_train.txt', sep='\\t', index=False)\ndf_test.to_csv('place_test.txt', sep='\\t', index=False)\n","repo_name":"jaeyeol816/Starring_Reviews_KR","sub_path":"Train/transform_csv_to_txt.py","file_name":"transform_csv_to_txt.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"34"} +{"seq_id":"10572876195","text":"n, k = map(int, input().split())\nan = list(map(int, input().split()))\n\nimport numpy as np\n\nt= min(k, 45)\nbn = np.zeros((t,n), dtype=int)\n\nfor k in range(t):\n if k==0:\n for i in range(n):\n for j in range(max(i - an[i], 0), min(n, i + an[i] + 1)):\n bn[k][j] += 1\n else:\n for i in range(n):\n for j in range(max(i - bn[k - 1][i], 0), min(n, i + bn[k - 1][i] + 1)):\n bn[k][j] += 1\n\nprint(*bn[t-1])","repo_name":"Shota3yo/ABC_C","sub_path":"Lamps.py","file_name":"Lamps.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"11628685051","text":"#\n# @lc app=leetcode id=1838 lang=python3\n#\n# [1838] Frequency of the Most Frequent Element\n#\n\n# @lc code=start\n\n#we can solve the question by finding the maximum element in that array and then substractinh with each element that are less than it and then we can we the idea that how many more we are require to get the same as maximum \n\n#NOTE:The idea is to sort the array first and then use a sliding window to calculate the frequency of the most frequent element for each possible window size. \nclass Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n \n nums.sort() # Sort the array in ascending order\n left = 0 # Left pointer for the sliding window\n max_freq = 0 # Initialize the maximum frequency of the most frequent element\n window_sum = 0 # Initialize the sum of elements within the current window\n\n for right in range(len(nums)):\n window_sum += nums[right] # Add the element at the right pointer to the window sum\n\n # Check if the current window is valid (i.e., the difference between the sum of elements\n # in the window and the window size times the element at the right pointer is not greater than k)\n while (right - left + 1) * nums[right] - window_sum > k:\n window_sum -= nums[left] # Shrink the window from the left side\n left += 1\n\n # Update the maximum frequency encountered so far\n max_freq = max(max_freq, right - left + 1)\n\n return max_freq\n\n# Example usage:\n# nums = [3, 9, 6]\n# k = 2\n# result = maxFrequency(nums, k)\n# print(result) # Output: 1\n\n\n \n# @lc code=end\n\n","repo_name":"AyushKumar1810/.leetcode","sub_path":"1838.frequency-of-the-most-frequent-element.py","file_name":"1838.frequency-of-the-most-frequent-element.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"34"} +{"seq_id":"30445245943","text":"import bpy\nimport os\nimport addon_utils \nfrom .. import addon_updater_ops\nfrom ..utilities.utils import get_path, get_prefs\nfrom ..icons.general import get_icon_id_general\n\nfrom ..layouts.ui_display import draw_display\nfrom ..layouts.ui_edit_curve import draw_edit_curve_ui\nfrom ..layouts.ui_edit_mesh import draw_edit_mesh_ui\nfrom ..layouts.ui_edit_objects import draw_edit_objects_ui\nfrom ..layouts.ui_insert_grid import draw_grid_ui\nfrom ..layouts.ui_insert_instance import draw_instance_ui\nfrom ..layouts.ui_insert_primitive import draw_primitive_ui\nfrom ..layouts.ui_material_panel import draw_mat_ui\nfrom ..layouts.ui_modifier_array import draw_array_ui\nfrom ..layouts.ui_render_camera import draw_camera_ui\nfrom ..layouts.ui_render_light import draw_light_ui\nfrom ..layouts.ui_render_studio import draw_render_ui\n\n\nEDIT = [\"OBJECT\", \"SCULPT\", \"EDIT_MESH\", \"EDIT_CURVE\", \"EDIT_SURFACE\", \"EDIT_METABALL\", \"EDIT_ARMATURE\", \"EDIT_PARTICLE\"]\nGEOM = ['MESH', 'CURVE', 'SURFACE', 'META', 'FONT', 'LATTICE', 'ARMATURE', 'POSE', 'LAMP', 'CAMERA', 'EMPTY', 'SPEAKER']\n\n\nclass RTS_PT_RePattern_Panel(bpy.types.Panel):\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'UI'\n bl_category = \"ReTools\"\n bl_idname = \"RTS_PT_RePattern_Panel\"\n bl_label = \"RePattern\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n isModelingMode = not (\n context.sculpt_object or \n context.vertex_paint_object\n or context.weight_paint_object\n or context.image_paint_object) \n# obj = bpy.context.view_layer.objects.active \n# if obj:\n# obj_type = obj.type \n# if obj_type in GEOM:\n# return isModelingMode and context.mode in EDIT \n return isModelingMode \n\n def draw_header(self, context):\n layout = self.layout\n layout.operator(\"wm.url_open\", text=\"\", icon_value=get_icon_id_general(\"logo\")).url = os.path.join(get_path(), \"docs\", \"index.mhtml\") \n\n def draw(self, context):\n layout = self.layout.column(align=True) \n layout.operator_context = 'INVOKE_REGION_WIN' \n\n prefs = get_prefs()\n panel_prefs = prefs.panel_type\n mat_prefs = prefs.mat_type\n\n # PRIMITIVE # \n if panel_prefs.toggle_primitive_ui == True: \n draw_primitive_ui(self, context) \n\n layout = self.layout \n layout = self.layout.column(align=True) \n \n # TOOLS # \n if context.mode == \"OBJECT\": \n \n # LAYOUT LIST # \n if panel_prefs.toggle_list_ui == False: \n box = layout.box().column(align=True) \n box.separator() \n \n row = box.row(align=True) \n row.alignment = 'CENTER' \n row.prop(panel_prefs, \"toggle_switch_ui\", text=\"\") \n\n box.separator() \n\n # LAYOUT BUTTONS # \n else: \n box = layout.box().column(align=True) \n box.separator() \n \n row = box.row(align=True) \n row.scale_x = 1.5 \n row.scale_y = 1.5 \n row.alignment = 'CENTER' \n row.prop_enum(panel_prefs, \"toggle_switch_ui\", 'L1', text=\"\", icon='GRID')\n row.prop_enum(panel_prefs, \"toggle_switch_ui\", 'L2', text=\"\", icon='MOD_MESHDEFORM')\n row.prop_enum(panel_prefs, \"toggle_switch_ui\", 'L3', text=\"\", icon='GROUP') \n row.prop_enum(panel_prefs, \"toggle_switch_ui\", 'L4', text=\"\", icon='MOD_ARRAY')\n row.prop_enum(panel_prefs, \"toggle_switch_ui\", 'L5', text=\"\", icon='MATERIAL') \n row.prop_enum(panel_prefs, \"toggle_switch_ui\", 'L6', text=\"\", icon='LIGHT') \n row.prop_enum(panel_prefs, \"toggle_switch_ui\", 'L7', text=\"\", icon='CAMERA_DATA') \n row.prop_enum(panel_prefs, \"toggle_switch_ui\", 'L8', text=\"\", icon='RENDER_STILL') \n\n\n box.separator() \n \n\n if panel_prefs.toggle_switch_ui == 'L1': \n draw_grid_ui(self, context) \n \n if panel_prefs.toggle_switch_ui == 'L2': \n draw_instance_ui(self, context) \n\n if panel_prefs.toggle_switch_ui == 'L3': \n draw_edit_objects_ui(self, context) \n \n if panel_prefs.toggle_switch_ui == 'L4': \n draw_array_ui(self, context) \n\n if panel_prefs.toggle_switch_ui == 'L5': \n draw_mat_ui(self, context) \n\n if panel_prefs.toggle_switch_ui == 'L6': \n draw_light_ui(self, context) \n\n if panel_prefs.toggle_switch_ui == 'L7': \n draw_camera_ui(self, context) \n\n if panel_prefs.toggle_switch_ui == 'L8': \n draw_render_ui(self, context) \n \n\n # TOOLS # \n if context.mode == \"EDIT_MESH\":\n box = layout.box().column(align=True) \n box.separator() \n\n row = box.row(align=True) \n row.scale_x = 1.2 \n row.scale_y = 1.2 \n row.alignment = 'CENTER' \n row.prop_enum(panel_prefs, \"toggle_switch_ui\", 'L3', text=\"\", icon='EDITMODE_HLT')\n row.prop_enum(panel_prefs, \"toggle_switch_ui\", 'L5', text=\"\", icon='MATERIAL') \n \n box.separator() \n\n if panel_prefs.toggle_switch_ui == 'L3': \n draw_edit_mesh_ui(self, context) \n\n if panel_prefs.toggle_switch_ui == 'L5': \n draw_mat_ui(self, context) \n\n\n if context.mode == \"EDIT_CURVE\": \n draw_edit_curve_ui(self, context) \n \n\n # GLOBAL SETTINGS #\n layout = self.layout.column(align=True)\n\n col = layout.row(align=True)\n col.alignment ='CENTER' \n obj = context.object\n if obj: \n col.prop(context.object, \"show_in_front\", text=\"\", icon='ZOOM_IN')\n col.prop(context.space_data.overlay, \"show_face_orientation\", text=\"\", icon='ZOOM_SELECTED') \n col.prop(context.space_data.shading, \"show_backface_culling\", text=\"\", icon='META_BALL')\n #col.prop(context.space_data.overlay, \"show_wireframes\", text=\"\", icon='SHADING_WIRE')\n col.operator(\"rts_ot.display_set_shading\", text=\"\", icon='SHADING_RENDERED')\n col.operator(\"rts_ot.display_set_wire\", text=\"\", icon='SHADING_WIRE')\n \n if bpy.context.object.display_type == 'WIRE': \n col.prop_enum(context.object, \"display_type\", 'SOLID', text=\"\", icon='GHOST_DISABLED') \n else: \n col.prop_enum(context.object, \"display_type\", 'WIRE', text=\"\", icon='GHOST_ENABLED') \n\n if bpy.context.object.lock_location[0] == True or bpy.context.object.lock_location[1] == True or \\\n bpy.context.object.lock_location[2] == True or bpy.context.object.lock_rotation[0] == True or \\\n bpy.context.object.lock_rotation[1] == True or bpy.context.object.lock_rotation[2] == True or \\\n bpy.context.object.lock_scale[0] == True or bpy.context.object.lock_scale[1] == True or \\\n bpy.context.object.lock_scale[2] == True: \n ico_lock = 'LOCKED'\n else:\n ico_lock = 'UNLOCKED' \n col.operator(\"rts_ot.transform_lock\", text=\"\", icon =ico_lock) \n col.separator()\n\n if obj.type in {'CURVE'}: \n col.operator(\"rts_ot.dynamic_normalize\", text=\"\", icon='KEYTYPE_BREAKDOWN_VEC') \n\n else:\n col.label(text=\"\", icon='ERROR') \n\n col.separator()\n\n obj = context.object \n if obj:\n obj_type = obj.type\n if obj_type: \n \n is_geometry = (obj_type in {'MESH', 'CURVE', 'SURFACE', 'META', 'FONT'})\n is_wire = (obj_type in {'CAMERA', 'EMPTY'})\n is_empty_image = (obj_type == 'EMPTY' and obj.empty_display_type == 'IMAGE')\n is_dupli = (obj.instance_type != 'NONE')\n is_gpencil = (obj_type == 'GPENCIL')\n\n if bpy.context.space_data.shading.color_type == 'OBJECT': \n if is_geometry or is_dupli or is_empty_image or is_gpencil: \n sub = col.row(align=True)\n sub.scale_x = 0.325\n sub.prop(obj, \"color\", text='') \n else:\n pass\n else: \n sub = col.row(align=True) \n mat = bpy.context.object.active_material\n if mat: \n if mat.use_nodes: \n mat_base = mat.node_tree.nodes.active\n if mat_base: \n sub.scale_x = 0.325\n mat_base_node = mat_base.inputs[0]\n sub.prop(mat_base_node,'default_value', text='') \n else:\n sub.scale_x = 1\n sub.operator('rts_ot.select_bsdf_node', text=\"\", icon='NODE')\n else:\n sub.scale_x = 0.325\n sub.prop(mat, \"diffuse_color\", text=\"\") \n else:\n sub.scale_x = 1\n sub.operator(\"rts_ot.repattern_shader_custom\", text=\"\", icon='MATERIAL')\n \n\n if bpy.context.space_data.shading.color_type == 'OBJECT': \n col.prop_enum(context.space_data.shading, \"color_type\", 'MATERIAL', text=\"\", icon='RESTRICT_COLOR_ON') \n else: \n col.prop_enum(context.space_data.shading, \"color_type\", 'OBJECT', text=\"\", icon='RESTRICT_COLOR_OFF') \n \n \n col.separator() \n col.prop(panel_prefs, \"display_settings_rp\", text=\"\", icon='SETTINGS') \n\n if panel_prefs.display_settings_rp == True:\n \n layout = self.layout.column(align=True) \n box = layout.box().column(align=True)\n box.separator() \n \n row = box.row() \n row.prop(panel_prefs, \"display_settings_type_rp\", expand=True) \n \n box.separator() \n \n if panel_prefs.display_settings_type_rp == 'global':\n \n box = layout.box().column(align=True)\n box.separator() \n \n row = box.column(align=True) \n row.operator(\"preferences.addon_show\", text=\"Addon Preferences\", icon=\"TOOL_SETTINGS\").module=\"view3d_repattern\"\n \n box.separator() \n\n addon_updater_ops.check_for_update_background()\n # call built-in function with draw code/checks\n addon_updater_ops.update_notice_box_ui(self, context) \n \n \n if panel_prefs.display_settings_type_rp == 'display':\n draw_display(self, context)\n\n\n","repo_name":"mkbreuer/view3d_repattern","sub_path":"panels/main_panel.py","file_name":"main_panel.py","file_ext":"py","file_size_in_byte":11796,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"34"} +{"seq_id":"72515203297","text":"with open(\"D:\\Data\\csvtest\\MyDict.csv\") as f:\n csv=f.read()\nx=[i.split(\",\")[1:] for i in csv.split(\"\\n\") if i.split(\",\")[0]!=\"\"]\npins=[]\n\n\nfor i in x:\n for j in i:\n pins.append(j)\nx=\"\\n\".join(pins)\nwith open(\"D:\\Data\\csvtest\\pinjia.txt\",\"w\") as pin:\n y=pin.write(x)\n\nwith open(\"D:\\Data\\csvtest\\pinjia.txt\") as pin:\n y=pin.read()\npins=y.split(\"\\n\")\n\nwith open(\"D:\\WordLibrary\\JiebaUse\\stopwords.txt\",encoding=\"utf8\") as stopp:\n stop=stopp.read()\nstopwords=stop.split(\"\\n\")\n\nimport json\nwith open(\"D:\\Data\\JsonData\\TainanFood\\TainanUniqueXY.json\") as f:\n data=json.load(f)\nnames=[i[\"name\"] for i in data]\nstyles=[i[\"style\"] for i in data]\n\nimport jieba\njieba.set_dictionary(\"D:\\WordLibrary\\JiebaUse\\jieba_dict.txt.big\")\nfor i in pins:\n if i !=\"\":\n jieba.add_word(i)\nfor i in names:\n jieba.add_word(i)\nfor i in styles:\n jieba.add_word(i)\n\n#以上把jiebadict加入該斷的文字\n\n\nx=[[j[\"content\"] for j in i[\"comment\"]] for i in data]\nN=[len(i) for i in x]\ncontents=[\" \".join(i) for i in x]\n\n\ncontentscut=[]\nfor i in contents:\n words=jieba.cut(i)\n contentcut=\" \".join([word for word in words if word not in stopwords and '\\u4e00' <= word <= '\\u9fff'])\n contentscut.append(contentcut)\n##對評論執行斷詞\n\nanalyzetable=[]\nfor name,style,n,contentcut in zip(names,styles,N,contentscut):\n dictt={}\n dictt[\"name\"]=name\n dictt[\"style\"]=style\n dictt[\"n\"]=n\n dictt[\"contentcut\"]=contentcut\n analyzetable.append(dictt)\n#存取斷玩詞的物件\nimport json\nwith open(\"D:\\Data\\JsonData\\TainanFood\\AnalyzeTable2.json\",\"w\") as pin:\n json.dump(analyzetable,pin)\n\nimport json\nwith open(\"D:\\Data\\JsonData\\TainanFood\\AnalyzeTable2.json\") as pin:\n analyzetable=json.load(pin)\n\nwith open(\"D:\\Data\\csvtest\\MyDict.csv\") as f:\n csv=f.read()\n# x=[(float(i.split(\",\")[0]),i.split(\",\")[1:]) for i in csv.split(\"\\n\") if i.split(\",\")[0]!=\"\"]\nx=[{j:float(i.split(\",\")[0]) for j in i.split(\",\")[1:]} for i in csv.split(\"\\n\") if i.split(\",\")[0]!=\"\"]\n\n\nimport pandas\nfrom collections import Counter\nfor i in analyzetable:\n i[\"WordCount\"]=Counter(i[\"contentcut\"].split(\" \"))\n\npindict={}\nfor i in x:\n pindict.update(i)\n\n#每家廠商\nfor dien in analyzetable:\n pinprice=0\n for word in dien[\"WordCount\"]:\n if word in pindict:\n pinprice+=dien[\"WordCount\"][word]*pindict[word]\n if dien['n']!=0:\n if dien['n']<6:\n dien[\"price\"]=round((pinprice/dien[\"n\"])*0.4,2)\n elif dien['n']<11:\n dien[\"price\"]=round((pinprice/dien[\"n\"])*0.6,2)\n elif dien['n']<16:\n dien[\"price\"]=round((pinprice/dien[\"n\"])*0.8,2)\n else:\n dien[\"price\"]=round((pinprice/dien[\"n\"])*1,2)\n\nimport json\nwith open(\"D:\\Data\\JsonData\\TainanFood\\MyDictPrice.json\",\"w\") as pin:\n json.dump(analyzetable,pin)","repo_name":"j122085/pythonCode","sub_path":"pyCharm/ipeen/MyDictScore.py","file_name":"MyDictScore.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"37525132260","text":"#!/usr/bin/python3\n# _*_ coding: utf-8 _*_\n\n__author__ = \"Unai Cervantes\"\n__email__ = \"cf19unai.cervantes@iesjoandaustria.org\"\n__license__ = \"GPL V3\"\n\nfrom glob import glob\nfrom inspect import Parameter\nfrom ossaudiodev import SOUND_MIXER_DIGITAL2\nimport tkinter\nvalor_en_pantalla = 0\nvalor1 = 0\noperacio = \"\"\nvalors = []\n\ndef click_boto(digit):\n global valor_en_pantalla\n valor_en_pantalla *= 10\n valor_en_pantalla += digit\n entrada.delete(0,tkinter.END)\n entrada.insert(0,f\"{valor_en_pantalla}\")\n print(f\"He fet click al boto {digit}\")\n\ndef click_suma():\n global valor_en_pantalla\n global valor1\n global operacio\n global valors\n operacio = \"suma\"\n valors.append(valor_en_pantalla)\n valor1 = valor_en_pantalla\n entrada.delete(0,tkinter.END)\n entrada.insert(0,f\"+\")\n print(f\"El primer numero és {valors}\")\n valor_en_pantalla = 0\n\ndef click_igual(): \n global valors\n print(valor1)\n total = 0\n valor2 = valor_en_pantalla\n entrada.delete(0,tkinter.END)\n valors.append(valor_en_pantalla)\n if operacio == \"suma\":\n for index in valors:\n total += index\n entrada.insert(0,f\"{total}\")\n valors = []\n elif operacio == \"resta\":\n total = 0\n for index in valors:\n total -= index\n entrada.insert(0,f\"{total}\")\n valors = []\n elif operacio == \"multiplicacio\":\n total = 1\n for index in valors:\n total *= index\n entrada.insert(0,f\"{total}\")\n valors = []\n print(f\"El valor de la suma2 és {total}\")\n\ndef click_neteja():\n entrada.delete(0,tkinter.END)\n global valor1\n global valor_en_pantalla\n global valor_anterior\n global valors\n valor1 = 0\n valor_en_pantalla = 0\n valor_anterior = 0\n valors = []\n\ndef click_resta():\n global valor_en_pantalla\n global valor1\n global operacio\n operacio = \"resta\"\n valor1 = valor_en_pantalla\n valors.append(valor_en_pantalla)\n entrada.delete(0,tkinter.END)\n entrada.insert(0,f\"-\")\n print(f\"El primer numero és {valors}\")\n valor_en_pantalla = 0\n\ndef click_multiplicacio():\n global valor_en_pantalla\n global valor1\n global operacio\n operacio = \"multiplicacio\"\n valor1 = valor_en_pantalla\n valors.append(valor_en_pantalla)\n entrada.delete(0,tkinter.END)\n entrada.insert(0,f\"*\")\n print(f\"El primer numero és {valors}\")\n valor_en_pantalla = 0\n\n\nfinestra = tkinter.Tk()\nentrada = tkinter.Entry(finestra,width=60)\nentrada.grid(row=0, column=0, columnspan=3)\nentrada.insert(0,\"0\")\nfinestra.title(\"Calculadora Unai\")\n\nboto_01 = tkinter.Button(finestra,text=\"1\",padx=100, pady=20, fg=\"white\", command=lambda : click_boto(1))\nboto_02 = tkinter.Button(finestra,text=\"2\",padx=100, pady=20, fg=\"white\", command=lambda : click_boto(2))\nboto_03 = tkinter.Button(finestra,text=\"3\",padx=100, pady=20, fg=\"white\", command=lambda : click_boto(3))\nboto_04 = tkinter.Button(finestra,text=\"4\",padx=100, pady=20, fg=\"white\", command=lambda : click_boto(4))\nboto_05 = tkinter.Button(finestra,text=\"5\",padx=100, pady=20, fg=\"white\", command=lambda : click_boto(5))\nboto_06 = tkinter.Button(finestra,text=\"6\",padx=100, pady=20, fg=\"white\", command=lambda : click_boto(6))\nboto_07 = tkinter.Button(finestra,text=\"7\",padx=100, pady=20, fg=\"white\", command=lambda : click_boto(7))\nboto_08 = tkinter.Button(finestra,text=\"8\",padx=100, pady=20, fg=\"white\", command=lambda : click_boto(8))\nboto_09 = tkinter.Button(finestra,text=\"9\",padx=100, pady=20, fg=\"white\", command=lambda : click_boto(9))\nboto_00 = tkinter.Button(finestra,text=\"0\",padx=100, pady=20, fg=\"white\", command=lambda : click_boto(0))\nboto_suma = tkinter.Button(finestra,text=\"+\",padx=100, pady=20, fg=\"white\", command=click_suma)\nboto_igual = tkinter.Button(finestra,text=\"=\",padx=100, pady=20, fg=\"white\", command=click_igual)\nboto_neteja = tkinter.Button(finestra,text=\"clr\",padx=100, pady=20, fg=\"white\", command=click_neteja)\nboto_multiplicacio = tkinter.Button(finestra,text=\"*\",padx=100, pady=20, fg=\"white\", command=click_multiplicacio)\nboto_resta = tkinter.Button(finestra,text=\"-\",padx=100, pady=20, fg=\"white\", command=click_resta)\n\nboto_01.grid(row=1, column=0)\nboto_02.grid(row=1, column=1)\nboto_03.grid(row=1, column=2)\nboto_04.grid(row=2, column=0)\nboto_05.grid(row=2, column=1)\nboto_06.grid(row=2, column=2)\nboto_07.grid(row=3, column=0)\nboto_08.grid(row=3, column=1)\nboto_09.grid(row=3, column=2)\nboto_00.grid(row=4, column=0)\nboto_suma.grid(row=4, column=1)\nboto_igual.grid(row=5, column=2)\nboto_neteja.grid(row=5, column=0)\nboto_resta.grid(row=5, column=1)\nboto_multiplicacio.grid(row=4, column=2)\n\nfinestra.mainloop()\nprint(\"Hem tancat la finestra\")\n\n\"\"\"if __name__ == \"__main__\":\n main()\"\"\"","repo_name":"unaicervantes/ProgramacionASIX_CervantesUnai","sub_path":"Estructures/Exercicis/calculadora_CervantesUnai copy.py","file_name":"calculadora_CervantesUnai copy.py","file_ext":"py","file_size_in_byte":4756,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"39449762575","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom .. import iciba\nimport os\nfrom nose.tools import assert_true, assert_equal\nfrom mock import sentinel, patch\n\n\nROOT = os.path.dirname(__file__)\n\n\ndef hello():\n with open(os.path.join(ROOT, 'hello.iciba.xml'), 'rb') as f:\n return f.read()\n\ndef test_parse():\n ret = iciba.parse(hello())\n for key, value in [\n ('word', 'hello'),\n ('phonetic_symbol', '''heˈləu'''),\n ('custom_translations', [\n 'int. 哈喽,喂;你好,您好;表示问候;打招呼;',\n 'n. “喂”的招呼声或问候声;',\n 'vi. 喊“喂”;'\n ])\n ]:\n assert_true(key in ret.keys)\n assert_equal(value, ret.get(key))\n\n\n#@patch.object(iciba, 'parse')\n#@patch.object(iciba, 'urlopen')\n#def test_engine(urlopen, parse):\n #urlopen.return_value.__enter__.return_value.read.return_value = sentinel.hello\n #engine = iciba.Engine()\n #engine.query('hello')\n #parse.assert_called_with(sentinel.hello)\n\n\ndef test_uri():\n assert_equal(iciba.uri('hello'),\n 'http://dict-co.iciba.com/api/dictionary.php?w=hello')\n","repo_name":"Answeror/memoit","sub_path":"memoit/engines/test/test_iciba.py","file_name":"test_iciba.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"34"} +{"seq_id":"3317037102","text":"'''\r\nCreated on Aug 18, 2009\r\n@author: Patrick\r\n'''\r\nimport networkx as nx\r\nfrom hpf.function.term import Terms, Term\r\nDEFAULT_QUERY=\"select t.id,t.acc from term t where t.acc in (%s)\"\r\n\r\n \r\ndef _pydot(node):\r\n return Term(node.acc.replace(\"GO:\",\"\"),node.name)\r\n\r\nclass GODAG(object):\r\n '''\r\n '''\r\n\r\n def __init__(self, nodes=None,ebunch=None):\r\n self._nodes = []\r\n self._edges = []\r\n if nodes:\r\n self.add_nodes(nodes)\r\n if ebunch:\r\n self.add_edges(ebunch)\r\n\r\n def add_node(self, *nodes):\r\n for node in nodes:\r\n if hasattr(node,'__iter__'):\r\n self.add_nodes(node)\r\n else:\r\n self._nodes.append(node)\r\n \r\n def add_nodes(self, nodes):\r\n \"\"\"\r\n @param nbunch: A container of Terms. \r\n \"\"\"\r\n for node in nodes:\r\n self.add_node(node)\r\n\r\n def add_edges(self, ebunch):\r\n \"\"\"\r\n @param ebunch: A container of (Term1,Term2) tuples. \r\n \"\"\"\r\n self._edges += ebunch\r\n \r\n def load_edges(self,connection,\r\n query=DEFAULT_QUERY):\r\n if not len(self._nodes) > 0:\r\n return\r\n terms_str = \",\".join([\"'%s'\"%t.get_id() for t in self._nodes])\r\n query = query % (terms_str)\r\n cursor = connection.cursor()\r\n cursor.execute(\"drop table if exists terms1\")\r\n cursor.execute(\"drop table if exists terms2\")\r\n q = \"create temporary table terms1 \"+query\r\n #print q\r\n cursor.execute(q)\r\n q = \"create temporary table terms2 \"+query\r\n #print q\r\n cursor.execute(q)\r\n q = \"\"\"select t1.acc,t2.acc from terms1 t1 join graph_path p\r\n on t1.id=p.term1_id and p.distance=1\r\n join terms2 t2 on p.term2_id=t2.id\r\n \"\"\"\r\n #print q\r\n cursor.execute(q)\r\n edges = [(Term(t1),Term(t2)) for t1,t2 in cursor.fetchall()]\r\n cursor.close()\r\n self.add_edges(edges)\r\n\r\n def nodes(self):\r\n return self._nodes\r\n\r\n def graph(self):\r\n graph = nx.DiGraph()\r\n for node in self._nodes:\r\n graph.add_node(_pydot(node))\r\n for t1,t2 in self._edges:\r\n graph.add_edge(_pydot(t1),_pydot(t2))\r\n return graph\r\n","repo_name":"dpenfoldbrown/hpf","sub_path":"hpf/go.py","file_name":"go.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"34"} +{"seq_id":"2321766564","text":"#!/usr/bin/env python3\n'''\n api.py\n Josh Pitkofsky Allie Warren, 30 April 2016\nThe api for the political violence visualizer.\n'''\nimport sys\nimport flask\nimport json\nimport config\nimport psycopg2\n\napp = flask.Flask(__name__, static_folder='static', template_folder='templates')\n\ndef _fetch_all_rows_for_query(query):\n '''\n Returns a list of rows obtained from the countries database\n by the specified SQL query. If the query fails for any reason,\n an empty list is returned.\n '''\n try:\n connection = psycopg2.connect(database=config.database, user=config.user, password=config.password)\n except Exception as e:\n print('Connection error:', e, file=sys.stderr)\n return []\n\n rows = []\n try:\n cursor = connection.cursor()\n cursor.execute(query)\n rows = cursor.fetchall() # This can be trouble if your query results are really big.\n except Exception as e:\n print('Error querying database:', e, file=sys.stderr)\n\n connection.close()\n return rows\n\n@app.route('/') \ndef get_main_page():\n ''' This is the only route intended for human users\n It features an interactive world map that displays political conflicts\n worldwide that occurred between 1946 and 2012'''\n return flask.render_template('maps.html')\n\n@app.route('/politicalconflicts//')\ndef get_all_countries(year, two_letter_code):\n ''' Returns the severity information (severity sum and description of the conflict)\n for the specified country in the specified year. Countries are identified using the two letter country code.\n This is being used by the webpage to get the information that display below the map.'''\n query_two_letter = '''SELECT three_letter FROM idtranslate WHERE UPPER(two_letter) LIKE UPPER('%{0}%')'''.format(two_letter_code)\n for item in _fetch_all_rows_for_query(query_two_letter):\n three_letter_code = item[0]\n query = '''SELECT country, three_letter, year, intind, intviol, intwar, civviol, civwar, ethviol, ethwar FROM severity WHERE year={0} AND UPPER(three_letter) LIKE UPPER('%{1}%')'''.format(year, three_letter_code)\n country_list = []\n for row in _fetch_all_rows_for_query(query):\n severity_sum = row[3] + row[4] + row[5] + row[6] + row[7] + row[8] + row[9] \n country_info = {'country':row[0], 'three_letter':row[1], 'year':row[2], 'sum' : severity_sum}\n \n query_details = '''SELECT description\n FROM detail\n WHERE {1} BETWEEN beginning AND ending \n AND UPPER(three_letter) LIKE UPPER('%{0}%')'''.format(row[1], year)\n descrip = ''\n counter = 0\n for line in _fetch_all_rows_for_query(query_details):\n if counter != 0:\n descrip = descrip + ', ' + line[0]\n else:\n descrip = line[0]\n counter=counter+1\n country_info['description'] = descrip\n \n query_two_letter = '''SELECT two_letter FROM idtranslate WHERE UPPER(three_letter) LIKE UPPER('%{0}%')'''.format(row[1])\n for item in _fetch_all_rows_for_query(query_two_letter):\n two_letter_code = item[0]\n country_info[two_letter_code] = descrip + str(severity_sum) \n\n country_list.append(country_info)\n\n return json.dumps(country_list)\n\n@app.route('/politicalconflicts/highestYear/')\ndef get_most_severe_year(country):\n '''Finds the year that had the highest severity for the specified country,\n then uses that year to get list of dictionaries that contain \n each country in the map and the severity level for that country in the year found \n (using the get_all_countries_two_letter api call)\n This is used by the webpage to update the map when a country is entered'''\n query = '''SELECT year, intind, intviol, intwar, civviol, civwar, ethviol, ethwar\n FROM severity\n WHERE UPPER(country) LIKE UPPER('%{0}%')\n ORDER by year'''.format(country)\n highest_severity = 0\n highest_year = 0\n severity_sum = 0\n for row in _fetch_all_rows_for_query(query):\n severity_sum = row[1] + row[2] + row[3] + row[4] + row[5] + row[6] + row[7] \n if (severity_sum >= highest_severity):\n highest_year = row[0]\n highest_severity = severity_sum \n return json.dumps(highest_year)\n\n@app.route('/politicalconflicts/detail/') \ndef get_most_severe(country):\n '''Finds the year that had the highest severity for the specified country and returns that year''' \n highest_year = get_most_severe_year(country)\n return get_all_countries_two_letter(highest_year)\n\n \n@app.route('/politicalconflicts//')\ndef get_country_details(country, year):\n ''' a list of dictionaries, each of which describes the total severity of \n conflict in a specific country with keys ’three_letter’, ‘country’, ‘year’, ‘sum’\n This is not currently being used by the website.\n '''\n query_severity = '''SELECT three_letter, country, year, intind, intviol, intwar, civviol, civwar, ethviol, ethwar\n FROM severity\n WHERE year={1} \n AND UPPER(country) LIKE UPPER('%{0}%')'''.format(country, year)\n severity_list = {}\n for row in _fetch_all_rows_for_query(query_severity):\n severity_sum = row[3] + row[4] + row[5] + row[6] + row[7] + row[8] + row[9] \n severity_list= {'three_letter':row[0], 'country':row[1], 'year':row[2], 'intind':row[3], 'intviol':row[4],\n 'intwar':row[5], 'civviol':row[6], 'civwar':row[7], 'ethviol':row[8], 'ethwar':row[9]}\n\n query_details = '''SELECT description\n FROM detail\n WHERE {1} BETWEEN beginning AND ending \n AND UPPER(country) LIKE UPPER('%{0}%')'''.format(country, year)\n descrip = ''\n counter = 0\n for row in _fetch_all_rows_for_query(query_details):\n if counter != 0:\n descrip = descrip + ', ' + row[0]\n else:\n descrip = row[0]\n counter=counter+1\n\n country_details= {'description': descrip}\n description = [severity_list, country_details]\n return json.dumps(description)\n\n@app.route('/politicalconflicts/twoletter/')\ndef get_all_countries_two_letter(year):\n '''Returns a list of dictionaries containing a key which is the two letter code\n for the country and the value which is the total severity sum for that country. This\n information is gathered for every country in the year specified.\n This api call is used by the main year search feature of the map'''\n query = '''SELECT country, three_letter, year, intind, intviol, intwar, civviol, civwar, ethviol, ethwar FROM severity WHERE year={0} ORDER by country'''.format(year)\n country_list={}\n for row in _fetch_all_rows_for_query(query):\n severity_sum = row[3] + row[4] + row[5] + row[6] + row[7] + row[8] + row[9]\n country_code = row[1]\n query_two_letter = '''SELECT two_letter FROM idtranslate WHERE UPPER(three_letter) LIKE UPPER('%{0}%')'''.format(country_code)\n for item in _fetch_all_rows_for_query(query_two_letter):\n two_letter_code = item[0]\n country_list[two_letter_code] = severity_sum\n return json.dumps(country_list)\n\nif __name__ == '__main__':\n if len(sys.argv) != 3:\n print('Usage: {0} host port'.format(sys.argv[0]), file=sys.stderr)\n exit()\n\n host = sys.argv[1]\n port = sys.argv[2]\n app.run(host='thacker.mathcs.carleton.edu', port=5147, debug=True)\n\n\n","repo_name":"warrena/webapp","sub_path":"webapp/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":7559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"18548836606","text":"from ml_collections import ConfigDict\n\n\ndef get_config():\n config = ConfigDict()\n\n config.data = ConfigDict()\n config.data.dataset = \"mnist\"\n config.data.train_split = \"train\"\n config.data.validation_split = \"test\"\n config.data.train_batch_size = 128\n config.data.val_batch_size = 128\n\n config.model = ConfigDict()\n config.model.encoder_net = \"ConvEncoder\"\n config.model.decoder_net = \"ConvDecoder\"\n config.model.decoder_dist = \"Bernoulli\"\n config.model.latent_dim = 10\n config.model.num_components = 10\n\n config.model.encoder_net_config = ConfigDict()\n config.model.encoder_net_config.conv_layers = [\n (32, 5, 1),\n (32, 5, 2),\n (64, 5, 1),\n (64, 5, 2),\n (128, 7, 1),\n ]\n\n config.model.decoder_net_config = ConfigDict()\n config.model.decoder_net_config.conv_layers = [\n (64, 7, 1),\n (64, 5, 2),\n (32, 5, 1),\n (32, 5, 2),\n (32, 5, 1),\n (1, 5, 1),\n ]\n\n config.pretrain_steps = int(60000 / config.data.train_batch_size * 150)\n config.steps = int(60000 / config.data.train_batch_size * 300)\n config.validation_freq = 1000\n config.cluster_pred_num_samples = 50\n\n config.pretrain_lr = 0.002\n\n config.lr_schedule = ConfigDict()\n config.lr_schedule.init_value = 0.002\n config.lr_schedule.decay_rate = 0.9\n config.lr_schedule.staircase = False\n config.lr_schedule.transition_steps = int(60000 / config.data.train_batch_size * 10)\n\n config.adam = ConfigDict()\n config.adam.eps = 1e-4\n\n return config\n","repo_name":"lupalab/posterior-matching","sub_path":"configs/vade_mnist.py","file_name":"vade_mnist.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"73106498655","text":"import math\r\nimport numpy as np\r\n\r\nx = 17 % 25\r\nprint(\"Task number:\", x)\r\n\r\nif __name__ == '__main__':\r\n while True:\r\n try:\r\n size = int(input(\"Input array size:\"))\r\n # if size <= 3:\r\n # print(\"Please, input another value > 3!\")\r\n # continue\r\n if size == 0:\r\n print(\"Matrix can`t exist at this size!\")\r\n break\r\n except ValueError:\r\n print(\"Invalid value entered!\")\r\n\r\n\r\n matrix = np.array([[i + 1 for i in range(size)] for _ in range(size)])\r\n array = np.array([[0 for i in range(size)] for _ in range(size)])\r\n\r\n for i in range(size):\r\n for k in range(0,size - i):\r\n array[i][k]=matrix[i][k+i]\r\n\r\n print(array)","repo_name":"d-progonov/IPT-2019-FE71","sub_path":"Tkachuk Labs/Lab4.py","file_name":"Lab4.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"43380412127","text":"import re\n\nimport jsonlines\nimport pandas as pd\nfrom openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE\n\nif __name__ == '__main__':\n # 读取JSONL文件\n data = []\n with jsonlines.open('single_changed_19k_compair_code_1210_unknown_old.jsonl') as reader:\n for obj in reader:\n data.append(obj)\n\n # 提取数据\n id_list = []\n history_list = []\n prompt_list = []\n source_list = []\n response_list = []\n original_response_list = []\n label_source_list = []\n\n for obj in data:\n id_list.append(obj['id'])\n history_list.append(obj['history'])\n changed_prompt = re.sub(ILLEGAL_CHARACTERS_RE, \"\", obj['prompt'])\n prompt_list.append(changed_prompt)\n source_list.append(obj['source'])\n changed_response = re.sub(ILLEGAL_CHARACTERS_RE, \"\", obj['response'])\n response_list.append(changed_response)\n original_response_list.append(obj['original_response'])\n label_source_list.append(obj['label_source'])\n\n print(\"id_list:\", len(id_list))\n print(\"history_list:\", len(history_list))\n print(\"prompt_list:\", len(prompt_list))\n print(\"source_list:\", len(source_list))\n print(\"response_list:\", len(response_list))\n print(\"original_response_list:\", len(original_response_list))\n\n # 构造DataFrame\n df = pd.DataFrame({\n \"id\": id_list,\n \"history\": history_list,\n \"prompt\": prompt_list,\n \"source\": source_list,\n \"response\": response_list,\n \"original_response\": original_response_list,\n \"label_source\": label_source_list,\n })\n\n # 写入Excel文件\n df.to_excel(\"single_changed_19k_compair_code_1210_unknown.xlsx\", index=False)\n","repo_name":"pyhuo/pand","sub_path":"code_pairlabel/jsonl_to_xlsx.py","file_name":"jsonl_to_xlsx.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"29396982348","text":"# Laser profiles library for native implementation\n\nLaserProfile = {}\n\nLaserProfile[\"Gaussian\"] = \\\n\"\"\"\nnamespace gaussianBeam\n{\n static constexpr uint32_t MODENUMBER = ${MODENUMBER};\n PMACC_CONST_VECTOR(float_X, MODENUMBER + 1, LAGUERREMODES, ${LAGUERREMODES}\n );\n}\n struct GaussianBeamParam\n {\n static constexpr float_64 WAVE_LENGTH_SI = ${wavelength};\n static constexpr float_64 AMPLITUDE_SI = -2.0*PI / ::picongpu::SI::ELECTRON_CHARGE_SI * ${a0} / WAVE_LENGTH_SI * ::picongpu::SI::ELECTRON_MASS_SI * ::picongpu::SI::SPEED_OF_LIGHT_SI * ::picongpu::SI::SPEED_OF_LIGHT_SI;\n static constexpr float_64 PULSE_LENGTH_SI = ${tau};\n static constexpr float_64 W0_SI = ${w0};\n static constexpr float_64 FOCUS_POS_SI = ${y_foc};\n static constexpr float_64 PULSE_INIT = ${injection_duration};\n static constexpr float_X LASER_PHASE = ${CEP};\n static constexpr uint32_t initPlaneY = ${iy_antenna};\n using LAGUERREMODES_t = gaussianBeam::LAGUERREMODES_t;\n static constexpr uint32_t MODENUMBER = gaussianBeam::MODENUMBER;\n enum PolarisationType\n {\n LINEAR_X = 1u,\n LINEAR_Z = 2u,\n CIRCULAR = 4u,\n };\n static constexpr PolarisationType Polarisation = ${pol};\n };\n using Selected = GaussianBeam< GaussianBeamParam >;\n\"\"\"\n","repo_name":"hightower8083/PoGit","sub_path":"pogit/codelets/laser.py","file_name":"laser.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"33"} +{"seq_id":"42749733467","text":"# numbers in python\n# print((2+10)*(10+3))\n\na=5\nprint(a+a)\n\na=a*5\nprint(a)\n\nmy_income=100\ntax_rate=0.1\nmy_taxes=my_income*tax_rate\nprint(my_taxes)\n\n\n# def factorial(n):\n# if n==0.0:\n# return 1\n# else:\n# return n*factorial(n-1)\n#\n# print(factorial(5.2))\n","repo_name":"lopesofrin28/Django-course","sub_path":"part1/PYTHON_LEVEL_ONE/numbers.py","file_name":"numbers.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"72509813215","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('website', '0057_auto_20170713_2112'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='page',\n name='layout_text',\n field=models.CharField(default=b'TLST', max_length=25, choices=[(b'PARA', b'Paragraph'), (b'PARAi', b'Paragraph italic'), (b'TLST', b'First ln Header List'), (b'TLSTv', b'First ln Header List Variant'), (b'SLST', b'Simple List'), (b'SLSTv', b'Simple List Variant'), (b'SLSTc', b'Simple List Contained')]),\n ),\n ]\n","repo_name":"maherrub/bca","sub_path":"website/migrations/0058_auto_20170714_0958.py","file_name":"0058_auto_20170714_0958.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"27480349374","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('home', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Atividade',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='ID', auto_created=True)),\n ('nome', models.CharField(max_length=150)),\n ('carga', models.IntegerField()),\n ('local', models.CharField(max_length=150, default='')),\n ('data_inicial', models.DateField(default=datetime.datetime.now)),\n ('data_final', models.DateField(default=datetime.datetime.now)),\n ('hora_inicial', models.TimeField(default=datetime.datetime(2016, 2, 29, 19, 0, 58, 709812))),\n ('hora_final', models.TimeField(default=datetime.datetime(2016, 2, 29, 19, 0, 58, 709863))),\n ('data_definida', models.BooleanField(default=False)),\n ('certificado_disponivel', models.BooleanField(default=False)),\n ('inscricao_aberta', models.BooleanField(default=False)),\n ('maximo_inscritos', models.IntegerField(blank=True, default=30)),\n ('tipo', models.CharField(max_length=50, choices=[('MN', 'Minicurso'), ('PEC', 'PEC'), ('SEM', 'Seminario'), ('TA', 'Topico de Apoio'), ('EX', 'Extensao'), ('OU', 'Outro')], default='OU')),\n ('descricao', models.TextField()),\n ('aviso', models.TextField(blank=True, default='')),\n ],\n options={\n 'ordering': ['-data_inicial'],\n },\n ),\n migrations.CreateModel(\n name='Participacao',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='ID', auto_created=True)),\n ('valido', models.BooleanField(default=False)),\n ('papel', models.CharField(blank=True, max_length=120, default='Ouvinte')),\n ('horas_validas', models.IntegerField(blank=True, help_text='Total de horas validas para a atividade. Deixar 0 caso for a carag total cadastrada na atividade', default=0)),\n ('atividade', models.ForeignKey(to='atividades.Atividade')),\n ('usuario', models.ForeignKey(to='home.Aluno', null=True)),\n ],\n ),\n ]\n","repo_name":"pviniciusm/petcc","sub_path":"portalpetcc/atividades/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"37086616342","text":"import tkinter as tk\nfrom tkinter import Message, mainloop, ttk\n#no funciona\n#window = tk.Tk() #generar ventana\n\n#funcion\n\ndef motion(event):\n print(\"Mouse position: (%s %s)\", (event.x, event.y))\n return \n\n\n#evento\n\nmaster = tk.Tk()\ntexto = \"Demo de texto widget msg para ver el movimiento del ratón\"\nmsg = Message(master, text=texto)\nmsg.config(bg='lightgreen', font=('time', 24, 'italic'))\nmsg.bind('', motion)\nmsg.pack\n\nmainloop()\n\n#window.mainloop() #loop\n\n#sys.exit(0) \n\n\n","repo_name":"sebaspatric/python_basico","sub_path":"sesion10/tk1/tk19eventos_posicion.py","file_name":"tk19eventos_posicion.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"6753417767","text":"#!/usr/bin/env python3\n\n\"\"\"\nThis module contains the functions for solving task 6.\nTask description:\n Output a single csv file per craft per planet (ex. `rocket_venus.csv`)\n\"\"\"\n\nimport glob\nimport csv\nimport pandas as pd\nfrom typing import List, Dict\nfrom types import SimpleNamespace\nfrom code.utils.utils import get_project_root, time_execution\n\n\ndef get_unique_rocket_lander_names(files: List[str]) -> Dict[str, Dict[str, List]]:\n \"\"\"\n Finds all unique rocket names from a list of file names.\n :param files: The list of file names.\n :return: A list of unique names or new files.\n \"\"\"\n # We assume the pattern: rocket__XXX_XXX.csv\n # First, we split on the last '/' to ensure the file name, then we get the first two names separated by '_'.\n # Set is used to remove duplicates and is afterwards casted to list for convenience.\n unique_names = list(set(['_'.join(name.split('/')[-1].split('_')[:2]) for name in files]))\n return {key: {} for key in unique_names}\n\n\ndef get_rocket_lander_data_structure(files: List[str], names: Dict[str, Dict[str, List]]) -> Dict[str, Dict[str, List]]:\n \"\"\"\n Fills the data structure where keys are unique names, e.g. lander_venus with associated file paths as values\n in a list\n :param files: The list of all file paths to parsed files.\n :param names: The data structure where keys are unique missions and values are empty lists.\n :return: A filled data structure in the form of 'names'.\n \"\"\"\n for file in files:\n for key, data in names.items():\n if key in file:\n with open(file, 'rU') as f:\n reader = csv.DictReader(f)\n for row in reader:\n for header, value in row.items():\n data.setdefault(header, list()).append(value)\n return names\n\n\ndef create_merged_file(lander_dict: Dict[str, Dict[str, List]], files_path: str) -> None:\n \"\"\"\n Takes a dictionary with keys as unique lander/rocket missions and corresponding file paths as values.\n Creates a merged .csv file for each key.\n :param lander_dict: The corresponding data structure as dict.\n :param files_path: The path where the merged files should be located.\n :return: None.\n \"\"\"\n for mission_name, file_dicts in lander_dict.items():\n file_uri = get_project_root() + '/' + files_path + mission_name + '.csv'\n pd.DataFrame.from_dict(file_dicts).to_csv(file_uri, index_label=False, index=False)\n\n\n@time_execution\ndef task6(config: SimpleNamespace) -> None:\n \"\"\"\n Executes the solution of the sixth task\n :param config: The configuration file from the initial .yaml\n :type config: SimpleNamespace\n :return: None\n \"\"\"\n files = glob.glob(get_project_root() + '/' + config.get(\"source\") + '*.csv')\n unique_names = get_unique_rocket_lander_names(files)\n\n names = get_rocket_lander_data_structure(files, unique_names)\n create_merged_file(names, config.get(\"sink\"))\n","repo_name":"skoett/de-assignment","sub_path":"code/task_6.py","file_name":"task_6.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"788270227","text":"# Problem Statement: https://practice.geeksforgeeks.org/problems/reversing-the-equation2205/1\n\n# User function Template for python3\n\nclass Solution:\n def __init__(self):\n self.ans = \"\"\n self.st = []\n\n def reverseEqn(self, s):\n start = 0\n for i in range(len(s)):\n sub_str = s[start:i]\n if not s[i].isdigit():\n self.st.append(sub_str)\n self.st.append(s[i])\n start = i + 1\n\n # Push remaining string elements to the stack\n self.st.append(s[start:])\n\n while self.st:\n self.ans += self.st.pop()\n\n return self.ans\n\n\n# {\n # Driver Code Starts\n# Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n s = input().strip()\n ob = Solution()\n ans = ob.reverseEqn(s)\n print(ans)\n# } Driver Code Ends\n","repo_name":"yashitanamdeo/geeks-for-geeks","sub_path":"Easy/reversing_the_equation.py","file_name":"reversing_the_equation.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"33"} +{"seq_id":"34521018180","text":"from __future__ import print_function\r\nimport json\r\nimport csv\r\n\r\nimport numpy as np\r\n\r\n#important when serializing color-dependent data\r\nCOLOR_ORDER = ['black','white','red','blue','green','gold']\r\n#for card prices and requirements of objectives\r\nCOST_COLOR_ORDER = ['black','white','red','blue','green']\r\n\r\nclass ColorCombination(object):\r\n\t\"\"\"\r\n\tthis represents color quantities to make arithmetic simpler\r\n\t\"\"\"\r\n\tdef __init__(self, uses_gold=False, **colors):\r\n\t\tself.uses_gold = uses_gold\r\n\t\tif not uses_gold:\r\n\t\t\tself.possible_colors = COST_COLOR_ORDER\r\n\t\telse:\r\n\t\t\tself.possible_colors = COLOR_ORDER \r\n\t\tfor color in self.possible_colors:\r\n\t\t\tsetattr(self, color, colors.get(color, 0))\r\n\r\n\tdef __getitem__(self, key):\r\n\t\treturn getattr(self, key)\r\n\r\n\tdef __setitem__(self, attr, key):\r\n\t\tsetattr(self, attr, key)\r\n\r\n\tdef __add__(self, c2):\r\n\t\tcolors = {}\r\n\t\tfor color in COLOR_ORDER:\r\n\t\t\t# 0 should only be in the case of gold when discounts and gems are added\r\n\t\t\tcolors[color] = getattr(self, color, 0) + getattr(c2, color, 0)\r\n\r\n\t\treturn ColorCombination(self.uses_gold or c2.uses_gold, **colors)\r\n\r\n\tdef __sub__(self, c2):\r\n\t\tcolors = {}\r\n\t\tif c2.uses_gold:\r\n\t\t\tfor color in self.possible_colors:\r\n\t\t\t\tcolors[color] = getattr(self, color) - getattr(c2, color)\r\n\t\telse:\r\n\t\t\tfor color in COST_COLOR_ORDER:\r\n\t\t\t\tcolors[color] = getattr(self, color) - getattr(c2, color)\r\n\t\t\tif self.uses_gold:\r\n\t\t\t\tcolors['gold'] = self.gold\r\n\r\n\r\n\t\treturn ColorCombination(self.uses_gold, **colors)\r\n\r\n\tdef __mul__(self, factor):\r\n\t\tcolors = {color:getattr(self, color) * factor for color in self.possible_colors}\r\n\t\treturn ColorCombination(self.uses_gold, **colors)\r\n\r\n\tdef __rmul__(self, factor):\r\n\t\treturn self.__mul__(factor)\r\n\r\n\tdef __neg__(self):\r\n\t\tcolors = {color:-getattr(self, color) for color in self.possible_colors}\r\n\t\treturn ColorCombination(self.uses_gold, **colors)\r\n\r\n\tdef __str__(self):\r\n\t\treturn json.dumps(self.as_dict(), indent=4)\r\n\r\n\tdef __repr__(self):\r\n\t\treturn 'ColorCombination object: \\n' + str(self)\r\n\r\n\tdef as_tuple(self):\r\n\t\treturn tuple([getattr(self, color) for color in self.possible_colors])\r\n\r\n\tdef expand(self):\r\n\t\te = []\r\n\t\tfor color in self.possible_colors:\r\n\t\t\te.extend([color] * getattr(self, color))\r\n\t\treturn e\r\n\r\n\tdef as_dict(self):\r\n\t\treturn {color:self[color] for color in self.possible_colors}\r\n\r\n\tdef count(self):\r\n\t\treturn sum([getattr(self, color) for color in self.possible_colors])\r\n\r\n\tdef count_nongold(self):\r\n\t\treturn sum([getattr(self, color) for color in self.possible_colors if color != 'gold'])\r\n\r\n\tdef count_nonnegative(self):\r\n\t\treturn sum([getattr(x, color) for x in self.possible_colors if getattr(x, color) >= 0])\r\n\r\n\tdef truncate_negatives(self):\r\n\t\tcolors = {color:max(0, getattr(self, color)) for color in self.possible_colors}\r\n\t\treturn ColorCombination(self.uses_gold, **colors)\r\n\r\n\tdef keep_only_negatives(self):\r\n\t\t# used for calculating what needs to be converted to gold\r\n\t\tcolors = {color:min(0, getattr(self, color)) for color in self.possible_colors}\r\n\t\treturn ColorCombination(self.uses_gold, **colors)\r\n\r\n\tdef __copy__(self):\r\n\t\tcolors = {color:getattr(self, color) for color in self.possible_colors}\r\n\t\treturn ColorCombination(self.uses_gold, **colors)\r\n\r\n\tdef __deepcopy__(self, *args):\r\n\t\treturn self.__copy__()\r\n\r\n\tdef can_pay_for(self, c2):\r\n\t\tdifference = c2 - self\r\n\t\tnet_shortfall = sum([max(0, getattr(difference, color)) for color in COST_COLOR_ORDER])\r\n\t\tif self.uses_gold:\r\n\t\t\treturn self.gold >= net_shortfall\r\n\t\telse:\r\n\t\t\treturn net_shortfall == 0\r\n\r\n\tdef calculate_actual_cost(self, c2):\r\n\t\t# get actual cost; used after can_pay_for() returns True\r\n\t\tdifference = c2 - self\r\n\t\tnet_shortfall = sum([max(0, getattr(difference, color)) for color in COST_COLOR_ORDER])\r\n\t\tcost = ONE_GOLD * net_shortfall + (c2 - difference.truncate_negatives())\r\n\t\treturn cost\r\n\r\n\tdef has_any_negatives(self):\r\n\t\treturn any([getattr(self, color) < 0 for color in self.possible_colors])\r\n\r\n\tdef make_payment(self, c2):\r\n\t\t\"\"\"\r\n\t\tcalculates difference, but will take out gold when needed\r\n\t\tthis should be done after can_pay_for() checks that it's okay\r\n\t\t\"\"\"\r\n\t\tdifference = self - c2\r\n\t\t#print(difference)\r\n\t\tnet_shortfall = sum([max(0, getattr(difference, color)) for color in COST_COLOR_ORDER])\r\n\t\t# print('net shortfall ', net_shortfall)\r\n\t\tif net_shortfall > 0:\r\n\t\t\tdifference.gold -= net_shortfall\r\n\t\t\tfor color in difference.possible_colors:\r\n\t\t\t\tsetattr(difference, color,\r\n\t\t\t\t\tmax(getattr(difference, color), 0)\r\n\t\t\t\t)\r\n\t\treturn difference\r\n\r\n\tdef serialize(self):\r\n\t\treturn np.asarray([1*getattr(self, color) for color in self.possible_colors])\r\n\r\ndef convert_tuple_to_color_combination(tup):\r\n\tif len(tup) == 5:\r\n\t\treturn ColorCombination(**{COST_COLOR_ORDER[i]:tup[i] for i in range(5)})\r\n\telse:\r\n\t\treturn ColorCombination(True, **{COLOR_ORDER[i]:tup[i] for i in range(6)})\t\r\n\r\n#length = 15\r\ndef serialize_card(card, allow_hidden=False):\r\n\t# this will return a card that is unknown to other players instead of serializing it\r\n\t# requires allow_hidden=True so one doesn't hide their own cards from themselves\r\n\tif card.get('hidden', False) and allow_hidden:\r\n\t\treturn serialize_card(make_blank_card(card['tier']))\r\n\r\n\tcolor_serialization = np.asarray([1*(card['color']==color) for color in COST_COLOR_ORDER])\r\n\tcost_serialization = card['cost'].serialize()\r\n\tpoint_serialization = np.asarray([card['points']])\r\n\ttier_serialization = np.asarray([1*(card['tier']==x) for x in range(1,4)])\r\n\t# this allows a blank card to input *some* value into the network\r\n\tblank_serialization = np.asarray([1*card.get('blank_value', 0)])\r\n\treturn np.concatenate((\r\n\t\tcolor_serialization, \r\n\t\tcost_serialization, \r\n\t\tpoint_serialization, \r\n\t\ttier_serialization, \r\n\t\tblank_serialization), \r\n\t)\r\n\r\n# length=5\r\ndef serialize_objective(objective):\r\n\tif objective is not None:\r\n\t\treturn objective.serialize()\r\n\telse:\r\n\t\treturn ColorCombination().serialize()\r\n\r\n\r\n# used so that it can be serialized easily\r\ndef make_blank_card(tier, blank_value=1):\r\n\t# specify blank_value=0 if it can't be replaced\r\n\t# OR use to indicate that is it not known to other players \r\n\tBLANK_CARD = {\r\n\t\t'tier': tier,\r\n\t\t'color': '',\r\n\t\t'points': 0,\r\n\t\t'cost': ColorCombination(),\r\n\t\t'blank': True,\r\n\t\t# for cards on board, this indicates if it will be replaced or not\r\n\t\t# for cards in player reserve zone, this indicates if card data is known or not\r\n\t\t'blank_value': blank_value, \r\n\t}\r\n\treturn BLANK_CARD\r\n\r\nPURE_BLANK_CARD_SERIALIZATION = serialize_card(make_blank_card(0, 0))\r\n\r\n# a small test case\r\n# v = ColorCombination(True, gold=3, red=1)\r\n# v2 = ColorCombination(red=2, black=1)\r\n# print(v.make_payment(v2))\r\n\r\n\r\n\r\n# these are used for simple arithmetic with ColorCombination class\r\nEACH_COLOR = ColorCombination(True, **{color:1 for color in COST_COLOR_ORDER})\r\n\r\nONE_GOLD = ColorCombination(True, gold=1)\r\n\r\nCARD_CSV_FILENAME = 'card_data.csv' # '/ntfsl/workspace/splendor_ai/card_data.csv'\r\n\r\nCARD_LIST = []\r\n#IF POINTS OR COST IS 0, THEN THAT VALUE WILL BE INSERTED LATER\r\nTIER_1_CARDS = []\r\nTIER_2_CARDS = []\r\nTIER_3_CARDS = []\r\n\r\ndef int_or_zero(x):\r\n\tif x=='':\r\n\t\treturn 0\r\n\telse:\r\n\t\treturn int(x)\r\n\r\ndef LOAD_CARDS():\r\n\tglobal TIER_1_CARDS\r\n\tglobal TIER_2_CARDS\r\n\tglobal TIER_3_CARDS\r\n\tglobal CARD_LIST\r\n\twith open(CARD_CSV_FILENAME, 'r') as f:\r\n\t\treader = csv.reader(f)\r\n\t\tnext(f)\r\n\t\tfor row in reader:\r\n\t\t\tdata = {\r\n\t\t\t'tier': int(row[0]),\r\n\t\t\t'color':row[1],\r\n\t\t\t'points':int(row[2]),\r\n\t\t\t'cost_':{\r\n\t\t\t\tcolor:int_or_zero(value) for color, value in \r\n\t\t\t\tzip(['black','white','red','blue','green'],\r\n\t\t\t\t\trow[3:])\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tdata['cost'] = ColorCombination(**data['cost_'])\r\n\t\t\ttier = int(row[0])\r\n\t\t\tif tier==1:\r\n\t\t\t\tTIER_1_CARDS.append(data)\r\n\t\t\telif tier==2:\r\n\t\t\t\tTIER_2_CARDS.append(data)\r\n\t\t\telse:\r\n\t\t\t\tTIER_3_CARDS.append(data)\r\n\r\n#loads cards into respective lists\r\nLOAD_CARDS()\r\n\r\n# aka \"nobles\"\r\nOBJECTIVE_CARDS_ = [\r\n\t{'green':4,'blue':4},\r\n\t{'black':4,'white':4},\r\n\t{'green':3,'red':3,'blue':3},\r\n\t{'red':4,'green':4},\r\n\t{'black':4,'red':4},\r\n\t{'black':3,'red':3,'white':3},\r\n\t{'blue':4,'white':4},\r\n\t{'black':3,'red':3,'green':3},\r\n\t{'green':3,'blue':3,'white':3},\r\n\t{'black':3,'blue':3,'white':3}\r\n]\r\n\r\nOBJECTIVE_CARDS = [ColorCombination(**v) for v in OBJECTIVE_CARDS_]\r\n\r\n#subtract 1 for each player less than 4 at start of game\r\nCOLOR_STOCKPILE_AMOUNT = 7\r\nGOLD_STOCKPILE_AMOUNT = 5\r\n\r\n# how much is available at the start\r\nGEMS_PILE = ColorCombination(True, \r\n\tgold=GOLD_STOCKPILE_AMOUNT, \r\n\t**{color:COLOR_STOCKPILE_AMOUNT for color in COST_COLOR_ORDER}\r\n)","repo_name":"mcandocia/splendor_ai","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":8531,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"33"} +{"seq_id":"73956542173","text":"# 导入必要的包\nfrom skimage.metrics import structural_similarity\nimport argparse\nimport imutils\nimport cv2\nimport numpy as np\n\n\n\nimageA = cv2.imread(\"c:\\\\logs\\\\a\\\\111.png\")\nimageB = cv2.imread(\"c:\\\\logs\\\\a\\\\222.png\")\n\ncv2.imshow(\"img\",imageA)\ngrayA = cv2.cvtColor(imageA,cv2.COLOR_BGR2GRAY)\n\ngrayB = cv2.cvtColor(imageB,cv2.COLOR_BGR2GRAY)\n\n(score, diff) = structural_similarity(grayA, grayB, full=True)\ndiff = (diff*255).astype(\"uint8\")\nprint(\"SSIM:{}\".format(score))\n\n# 阈值分割差分图像,然后查找轮廓以获得两个输入图片的不同区域\nthresh = cv2.threshold(diff, 0, 255,\n cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]\ncnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, \n cv2.CHAIN_APPROX_SIMPLE)\ncnts = imutils.grab_contours(cnts)\n# 遍历轮廓\nfor c in cnts:\n # 计算轮廓的边界框,然后在两张输入图片中代表图片不同点的区域绘制边界框\n (x, y, w, h) = cv2.boundingRect(c)\n cv2.rectangle(imageA, (x, y), (x + w, y + h), (0, 0, 255), 2)\n cv2.rectangle(imageB, (x, y), (x + w, y + h), (0, 0, 255), 2)\n \n \n# 显示输出图片\ncv2.imshow(\"Original\", imageA)\ncv2.imshow(\"Modified\", imageB)\ncv2.imshow(\"Diff\", diff)\ncv2.imshow(\"Thresh\", thresh)\ncv2.waitKey(0)","repo_name":"daiybh/Shining-Online-helper","sub_path":"Codes/A.PY","file_name":"A.PY","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"70642878814","text":"def get_line(cycle, line, x):\r\n cycle_x = cycle % 40\r\n if cycle_x == 1:\r\n print(line)\r\n line = ''\r\n # print(f\"cycle: {cycle} cycle_x: {cycle_x} x: {x}\")\r\n cycle_x -= 1\r\n if cycle_x == x or cycle_x == x-1 or cycle_x == x+1:\r\n line += '#'\r\n else:\r\n line += '.'\r\n return line\r\n\r\nwith open('input.txt', 'r', encoding=\"utf-8\") as f:\r\n lines = f.readlines()\r\n cycle = 0\r\n crt_line = ''\r\n x = 1\r\n add_x = 0\r\n for line in lines:\r\n command = line.strip().split(' ')\r\n x += add_x\r\n add_x = 0\r\n if command[0].strip() == 'addx':\r\n cycle += 1\r\n add_x = int(command[1])\r\n crt_line = get_line(cycle, crt_line, x)\r\n cycle += 1\r\n crt_line = get_line(cycle, crt_line, x)\r\n # print(f\"cycle: {cycle} command: {command} x: {x}\")\r\n print(crt_line)","repo_name":"delfimov/adventofcode","sub_path":"2022/10/10_1.py","file_name":"10_1.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"74646184413","text":"\"\"\"sysl module loader\"\"\"\n\nimport codecs\nimport os\nimport re\nimport sys\n\nfrom sysl.proto import sysl_pb2\n\nfrom sysl.core import syslalgo\nfrom sysl.core import syslparse\nfrom sysl.core import syslx\n\n\ndef fmt_app_name(appname):\n \"\"\"Format a sysl_pb2.AppName as a syntactically valid string.\"\"\"\n return ' :: '.join(appname.part)\n\n\ndef fmt_call(call):\n \"\"\"Format a sysl_pb2.Call as a syntactically valid string.\"\"\"\n return fmt_app_name(call.target) + ' <- ' + call.endpoint\n\n\ndef _resolve_mixins(module):\n \"\"\"Resolve mixin references.\n\n Copies endpoints from mixed-in apps.\n \"\"\"\n # Detect cycles\n edges = {\n (appname, syslx.fmt_app_name(mixin.name))\n for (appname, app) in module.apps.iteritems()\n for mixin in app.mixin2}\n while True:\n more_edges = {\n (a, c)\n for (a, b1) in edges\n for (b2, c) in edges\n if b1 == b2\n } - edges\n if not more_edges:\n break\n edges |= more_edges\n self_edges = {(a, b) for (a, b) in edges if a == b}\n if self_edges:\n raise RuntimeError(\n \"mixin cycle(s) detected involving: {}\".format(\n ', '.join(a for (a, _) in self_edges)))\n\n # recursively inject mixins, avoiding double-injection\n injected = set()\n\n def inject(appname):\n app = module.apps[appname]\n if appname not in injected:\n for mixin in app.mixin2:\n mixin_app = inject(syslx.fmt_app_name(mixin.name))\n\n # Check for ~abstract\n assert 'abstract' in syslx.patterns(mixin_app.attrs), (\n \"mixin {} must be ~abstract\".format(syslx.fmt_app_name(mixin.name)))\n\n for (epname, endpt) in mixin_app.endpoints.iteritems():\n app.endpoints[epname].CopyFrom(endpt)\n\n for (tname, t) in mixin_app.types.iteritems():\n app.types[tname].CopyFrom(t)\n\n for (vname, v) in mixin_app.views.iteritems():\n app.views[vname].CopyFrom(v)\n\n injected.add(appname)\n\n return app\n\n for appname in module.apps:\n inject(appname)\n\n\ndef _check_deps(module, validate):\n \"\"\"Check app:endpoint dependencies.\"\"\"\n deps = set()\n errors = []\n\n for (appname, app) in module.apps.iteritems():\n for epname in app.endpoints:\n endpt = app.endpoints[epname]\n\n for (_, call) in syslalgo.enumerate_calls(endpt.stmt):\n targetname = syslx.fmt_app_name(call.target)\n if targetname not in module.apps:\n errors.append('{} <- {}: calls non-existent app {}'.format(\n appname, epname, targetname))\n else:\n target = module.apps[targetname]\n assert 'abstract' not in syslx.patterns(target.attrs), (\n \"call target '{}' must not be ~abstract\".format(targetname))\n if call.endpoint not in target.endpoints:\n errors.append(\n '{} <- {}: calls non-existent endpoint {} -> {}'.format(\n appname, epname, targetname, call.endpoint))\n else:\n deps.add(\n ((appname, epname), (targetname, call.endpoint)))\n\n if errors and validate:\n raise Exception('broken deps:\\n ' + '\\n '.join(errors))\n\n return deps\n\n\ndef _map_subscriptions(module):\n \"\"\"Map pubsub subscriptions into direct calls.\"\"\"\n for appname in module.apps:\n app = module.apps[appname]\n\n if 'abstract' in syslx.patterns(app.attrs):\n continue\n\n for epname in app.endpoints:\n endpt = app.endpoints[epname]\n\n if endpt.HasField('source'):\n src_app = module.apps[syslx.fmt_app_name(endpt.source)]\n src_ep_name = endpt.name.split(' -> ')[1]\n assert src_ep_name in src_app.endpoints, (\n appname, epname, src_ep_name, str(src_app))\n src_ep = src_app.endpoints[src_ep_name]\n\n # Add call to pubsub endpoint.\n stmt = src_ep.stmt.add()\n call = stmt.call\n call.target.CopyFrom(app.name)\n call.endpoint = endpt.name\n\n # Maybe add ret.\n ret_payload = syslalgo.return_payload(endpt.stmt)\n if ret_payload:\n stmt = src_ep.stmt.add()\n stmt.ret.payload = ret_payload\n\n\ndef _apply_call_templates(app):\n \"\"\"Apply call templates found in '.. * <- *' | '*' pseudo-endpoints.\n\n Project-specific metadata may be applied as follows:\n\n MyApp:\n .. * <- *:\n Foo <- bar [myproj='XYZ-007']\n\n In the above example, whenever MyApp calls Foo <- bar,\n _apply_call_templates will attach the attribute myproj='XYZ-007' to the\n call.\n\n It will also validate that all templates are applied at least once.\n \"\"\"\n\n # Look for the pseudo endpoint.\n pseudos = {name for name in app.endpoints\n if re.match(r'(\\.\\.\\s*\\*\\s*<-\\s*\\*|\\*)', name)}\n if not pseudos:\n return\n if len(pseudos) > 1:\n raise Exception('Too many call templates: {}'.format(\n ', '.join(repr(p) for p in pseudos)))\n\n pseudo = app.endpoints[pseudos.pop()]\n\n templates = {}\n\n def call_templates():\n # Discover templates.\n for stmt in pseudo.stmt:\n if stmt.HasField('call'):\n templates[fmt_call(stmt.call)] = [stmt.attrs, 0]\n\n # Apply templates.\n endpoints = [endpt for (_, endpt) in app.endpoints.iteritems(\n ) if not re.match(r'(\\.\\.\\s*\\*\\s*<-\\s*\\*|\\*)', endpt.name)]\n\n for endpt in endpoints:\n for (stmt, call) in syslalgo.enumerate_calls(endpt.stmt):\n fmtcall = fmt_call(call)\n template = templates.get(fmtcall)\n if template is not None:\n for (name, attr) in template[0].iteritems():\n stmt.attrs[name].CopyFrom(attr)\n template[1] += 1\n\n def ep_templates():\n # Discover templates.\n for stmt in pseudo.stmt:\n if stmt.HasField('action'):\n templates[stmt.action.action] = [stmt.attrs, 0]\n\n # Apply templates.\n endpoints = [endpt for (_, endpt) in app.endpoints.iteritems(\n ) if not re.match(r'(\\.\\.\\s*\\*\\s*<-\\s*\\*|\\*)', endpt.name)]\n\n for endpt in endpoints:\n template = templates.get(endpt.name)\n if template is not None:\n for (name, attr) in template[0].iteritems():\n endpt.attrs[name].CopyFrom(attr)\n template[1] += 1\n\n call_templates()\n ep_templates()\n\n # Error on unused templates, in case of typos.\n call = None # In case of empty loop\n unused = {\n call\n for (call, n) in templates.iteritems()\n if n[1] == 0}\n\n # TODO: add better message\n # App is referring to an unused app-endpoint\n if unused:\n raise RuntimeError('Unused templates in {}: {}', fmt_app_name(\n app.name), ', '.join(repr(c) for c in unused))\n\n\ndef _infer_types(app):\n \"\"\"Infer types of views and expressions from their bodies.\n\n Synthesize types for anonymous transforms.\n \"\"\"\n\n for (vname, v) in app.views.iteritems():\n assert (\n (v.expr.WhichOneof('expr') == 'transform') ^\n ('abstract' in syslx.patterns(v.attrs))\n ), '{}: {}'.format(vname, v.expr)\n\n if v.ret_type.WhichOneof('type') is None:\n assert v.expr.type.WhichOneof('type')\n v.ret_type.CopyFrom(v.expr.type)\n\n nAnons = [0]\n\n def infer_expr_type(expr, top=True):\n which_expr = expr.WhichOneof('expr')\n\n if which_expr == 'transform':\n transform = expr.transform\n\n # Must recurse first\n for stmt in transform.stmt:\n which_stmt = stmt.WhichOneof('stmt')\n if which_stmt in ['assign', 'let']:\n infer_expr_type(getattr(stmt, which_stmt).expr, False)\n\n if not top and not expr.type.WhichOneof('type'):\n tname = 'AnonType_{}__'.format(nAnons[0])\n nAnons[0] += 1\n\n newt = app.types[tname].tuple\n\n for stmt in transform.stmt:\n which_stmt = stmt.WhichOneof('stmt')\n if which_stmt == 'assign':\n assign = stmt.assign\n aexpr = assign.expr\n assert aexpr.WhichOneof(\n 'expr') == 'transform', aexpr\n ftype = aexpr.type\n setof = ftype.WhichOneof('type') == 'set'\n if setof:\n ftype = ftype.set\n assert ftype.WhichOneof('type') == 'type_ref'\n\n t = sysl_pb2.Type()\n tr = t.type_ref\n tr.context.appname.CopyFrom(app.name)\n tr.context.path.append(tname)\n tr.ref.CopyFrom(ftype.type_ref.ref)\n\n if setof:\n t = sysl_pb2.Type(set=t)\n\n newt.attr_defs[assign.name].CopyFrom(t)\n\n tr = expr.type.set.type_ref\n tr.context.appname.CopyFrom(app.name)\n tr.ref.appname.CopyFrom(app.name)\n tr.ref.path.append(tname)\n\n elif which_expr == 'relexpr':\n relexpr = expr.relexpr\n\n if relexpr.op == relexpr.RANK:\n if not top and not expr.type.WhichOneof('type'):\n raise RuntimeError(\n \"rank() type inference not implemented\")\n expr.type.CopyFrom(infer_expr_type(relexpr.target))\n rank = expr.type.add()\n rank.primitive = rank.INT\n\n return expr.type\n\n infer_expr_type(v.expr)\n\n\ndef postprocess(module):\n _resolve_mixins(module)\n _map_subscriptions(module)\n for (appname, app) in module.apps.iteritems():\n _apply_call_templates(app)\n _infer_types(app)\n\n\ndef load(names, validate, root):\n \"\"\"Load a sysl module.\"\"\"\n if isinstance(names, basestring):\n names = [names]\n\n module = sysl_pb2.Module()\n imports = set()\n\n def do_import(name, indent=\"-\"):\n \"\"\"Import a sysl module and its dependencies.\"\"\"\n imports.add(name)\n (basedir, _) = os.path.split(name)\n new_imports = {\n root + i if i[:1] == '/' else os.path.join(basedir, i)\n for i in syslparse.Parser().parse(\n codecs.open(name + '.sysl', 'r', 'utf8'), name + '.sysl', module)\n } - imports\n while new_imports:\n do_import(new_imports.pop(), indent + \"-\")\n new_imports -= imports\n\n for name in names:\n if name not in imports:\n if name[:1] != '/':\n name = '/' + name\n if name.endswith('.sysl'):\n name = name[:-5]\n do_import(root + name)\n\n try:\n postprocess(module)\n deps = _check_deps(module, validate)\n except RuntimeError as ex:\n raise Exception('load({!r})'.format(names), ex, sys.exc_info()[2])\n\n return (module, deps, imports)\n","repo_name":"anz-bank/sysl-legacy","sub_path":"src/sysl/core/syslloader.py","file_name":"syslloader.py","file_ext":"py","file_size_in_byte":11661,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"42938157298","text":"# Convert a text file to JSON\nimport json\n# import sys\nfrom os.path import join, dirname\n\n# Read the text file with utf-8 encoding\nwith open(join(dirname(__file__), 'MBTI.txt'), 'r', encoding='utf-8') as f:\n lines = f.readlines()\n\n# Convert the text file to JSON\njson_data = []\nfor line in lines:\n if line[0].isdigit():\n json_data.append({\n \"question\": line.strip() + ' ',\n \"options\": {\"A\": \"\", \"B\": \"\",},\n })\n elif line[0] == 'a':\n json_data[-1][\"options\"][\"A\"] = line.strip()\n elif line[0] == 'b':\n json_data[-1][\"options\"][\"B\"] = line.strip()\n\n\n# Write the JSON file\nwith open(join(dirname(__file__), \"out.json\"), 'w') as f:\n json.dump(json_data, f)\n\n# Run the script\n# python TEXT_to_JSON.py text_file.json output_file.json","repo_name":"oscarchen178/mentalHealth_wechatApp","sub_path":"src/TEXT_to_JSON.py","file_name":"TEXT_to_JSON.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"43443352661","text":"import os\nimport json\nimport argparse # Parser for command-line options, arguments and sub-commands\nfrom tqdm import tqdm # A Fast, Extensible Progress Bar for Python and CLI\nfrom google.cloud import storage\nfrom google.cloud import speech_v1p1beta1 as speech\nfrom google.protobuf.json_format import MessageToDict\nfrom typing import *\nimport gconfig # google cloud config file\n\ndef main(args):\n print(\"Started!!!!\")\n # Check if the output directory exists\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n\n # List all audio files in the bucket.\n storage_client = storage.Client()\n bucket = storage_client.get_bucket(gconfig.BUCKET_NAME)\n blobs = bucket.list_blobs()\n # 'blobs is a list of Google blob objects. We need to extract filenames.\n original_filenames = [b.name for b in blobs]\n\n # Create a signle Google API client and configuration to reuse\n client = speech.SpeechClient()\n rc = speech.types.RecognitionConfig(\n encoding = speech.RecognitionConfig.AudioEncoding.FLAC,\n language_code = \"th-TH\",\n enable_word_confidence=True,\n enable_word_time_offsets=True,\n enable_speaker_diarization=True,\n diarization_speaker_count=2,\n audio_channel_count=1,\n model=\"default\", # phone_call model is not support th-TH\n ) \n\n # Skip already completed files.\n filenames: List[str] = []\n for filename in original_filenames:\n output_fqn = os.path.join(\n args.output_dir, filename.replace(\".flac\", \".json\")\n )\n if os.path.exists(output_fqn):\n continue\n else:\n filenames.append(filename)\n\n print(f\"Saving json output to: {args.output_dir}\")\n print(f\"Transcribing {len(filenames)} files from bucket: {gconfig.BUCKET_NAME}\")\n\n for filename in tqdm(filenames):\n # Run Automatic Speech Recognition\n audio = speech.types.RecognitionAudio(\n uri=f\"gs://{gconfig.BUCKET_NAME}/{filename}\"\n )\n\n #response = client.long_running_recognize()\n\n #ret = transcribe(client=client, rc=rc, audio=audio)\n\n transcribe2(client=client, rc=rc, audio=audio)\n\n # Save the output to json file.\n #with open(output_fqn, \"w\") as pointer:\n # json.dump(ret, pointer, indent=2, separators=(\",\", \": \"))\n\n\ndef transcribe2(client: speech.SpeechClient, rc: speech.types.RecognitionConfig, audio: speech.types.RecognitionAudio):\n operation = client.long_running_recognize(config=rc, audio=audio)\n\n print(\"Waiting for operation to complete...\")\n response = operation.result(timeout=None)\n\n transcript = \"\"\n confidence = 0.0\n count = 0\n\n # Each result is for a consecutive portion of the audio. Iterate through\n # them to get the transcripts for the entire audio file.\n for result in response.results:\n transcript += result.alternatives[0].transcript\n confidence += result.alternatives[0].confidence\n count += 1\n # The first alternative is the most likely one for this portion.\n print(u\"Transcript: {}\".format(result.alternatives[0].transcript))\n print(\"Confidence: {}\".format(result.alternatives[0].confidence))\n \n confidence = confidence / count\n print(u\"Transcript: {}\".format(transcript))\n print(\"Average Confidence {}\".format(confidence))\n print(\"Completed...\")\n\n\ndef transcribe(client: speech.SpeechClient, rc: speech.types.RecognitionConfig, audio: speech.types.RecognitionAudio):\n operation = client.long_running_recognize(config=rc, audio=audio)\n response = operation.result()\n result = MessageToDict(response)\n return result\n\nif __name__ == \"__main__\":\n os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = gconfig.KEY\n parser = argparse.ArgumentParser()\n parser.add_argument(\"output_dir\", type=str, help=\"Location for the transcription output.\")\n args = parser.parse_args()\n main(args)","repo_name":"Dhanabhon/GCP-Thai-Speech-to-Text","sub_path":"transcribe.py","file_name":"transcribe.py","file_ext":"py","file_size_in_byte":3929,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"34870529786","text":"#coding=utf-8\r\nimport unittest\r\nfrom selenium import webdriver\r\nimport HTMLTestRunner\r\nimport os\r\nfrom time import sleep\r\nclass Test(unittest.TestCase):\r\n\r\n def setUp(self):\r\n self.driver = webdriver.Chrome(\"D:\\Google\\Chrome\\Application\\chromedriver.exe\")\r\n self.driver.maximize_window()\r\n url = \"http://www.baidu.com\"\r\n self.driver.get(url)\r\n print(\"前置\")\r\n\r\n def test00(self):\r\n driver = self.driver\r\n driver.find_element_by_id(\"kw\").send_keys(\"123\")\r\n driver.find_element_by_id(\"su\").click()\r\n\r\n\r\n def test01(self):\r\n driver = self.driver\r\n try:\r\n d = driver.find_element_by_id(\"dsfsfd\").click()\r\n except:\r\n return False\r\n sleep(3)\r\n\r\n def test02(self):\r\n test01 = self.test01()\r\n self.assertTrue(test01,\"error!!!\")\r\n\r\n def tearDown(self):\r\n sleep(2)\r\n for method_name,error in self._outcome.errors:\r\n print(method_name,error)\r\n print(\"后置\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n suite = unittest.TestSuite()\r\n suite.addTest(Test(\"test00\"))\r\n suite.addTest(Test(\"test01\"))\r\n suite.addTest(Test(\"test02\"))\r\n fp = open(\"./ress.html\",\"wb\")\r\n runner = HTMLTestRunner.HTMLTestRunner(stream=fp,\r\n title=\"这是第一份测试报告\",\r\n description=\"用例执行情况:\")\r\n runner.run(suite)\r\n fp.close()","repo_name":"dengjifeng01/seleniumpython","sub_path":"selen/run_case.py","file_name":"run_case.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"2426929363","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\nFILE = 'INPUT.txt'\n\n\n# In[ ]:\n\n\n### Change attributes as per question given\nclass OBSERVATIONS:\n def __init__(self,obsNo,outlook,temp,humidity,wind,playTennis=\"NO\"):\n self.obsNo = obsNo\n self.OUTLOOK = outlook\n self.TEMP = temp\n self.HUMIDITY = humidity\n self.WIND = wind\n self.PLAYTENNIS = playTennis\n\n\n# In[ ]:\n\n\n## READING DATA\ninput_data = open(FILE)\ndata = input_data.read().splitlines()\nprint(\"----- DATA FROM INPUT FILE-----\")\ndata\n\n\n# In[ ]:\n\n\n### Loading Data and Storing Observations\n\nNo_of_Ob = int(data[0])\nNo_of_Attr = int(data[1])+1\n\nlistOfTitles = []\nlistOfObs = []\n\nj = 0\nfor i in data[2].split(\" \"):\n if j==0 or j==5:\n j=j+1\n continue\n listOfTitles.append(i)\n j=j+1\n \n\nprint(\"Attributes observed: \\n\\n\",listOfTitles)\n\nindex = 3\n\nwhile index < len(data)-1: ### -1 because last touple is out test data\n line = data[index].split(\" \")\n obsNo = ''.join(line[0])\n outlook = line[1]\n temp = line[2] ### Change values as per given question\n humidity = line[3]\n wind = line[4]\n playTennis = line[5]\n \n \n tempOb = OBSERVATIONS(obsNo,outlook,temp,humidity,wind,playTennis) ### Change calling parameters\n listOfObs.append(tempOb)\n index=index+1\n\n\n# In[ ]:\n\n\n## FINDING COUNT OF OUTPUT (Y)\n\ncount_OP = {}\n\nfor obsn in listOfObs:\n key = str(obsn.PLAYTENNIS) ### Change\n \n if key in count_OP:\n count_OP[key] = count_OP[key] +1;\n \n else:\n count_OP[key] = 1;\n \n \ntotal= No_of_Ob\n \nprint(\"TOTAL COUNT OF Classifications : \\n\")\nfor x,y in count_OP.items():\n print(x,y,sep=' : ')\n\n\n# In[ ]:\n\n\n### FINDING PROBABILITY OF OUTPUT COLUMN P(N) = No(N)/No(TOTAL)\nprob_OP = {}\n\nfor key in count_OP.keys():\n prob_OP[key] = count_OP[key]/total\n\nprint(\"PROBABILITY OF OUTPUT FIELD : \\n\")\nfor x,y in prob_OP.items():\n print(x,y,sep=' : ')\n\n\n# In[ ]:\n\n\n### FINDING THE CONDITIONAL PROBABILITIES of Rest of Attributes\n\nlistOfProbabilities = []\n\nfor title in listOfTitles:\n \n tempMap = {}\n \n for obsn in listOfObs:\n value = getattr(obsn,title)\n opvalue = getattr(obsn,'PLAYTENNIS') ### Change as per given question\n \n key = str(value)+\"|\"+str(opvalue) ### Change as per given question\n \n if key in tempMap:\n tempMap[key] = tempMap[key]+ (1/count_OP[str(opvalue)])\n else:\n tempMap[key] = 1/count_OP[str(opvalue)]\n \n listOfProbabilities.append(tempMap);\n\nlistOfProbabilities.append(prob_OP)\n\n\n# In[ ]:\n\n\nprint(\"Conditional Probabilities of Attributes : \\n\")\nfor i in listOfProbabilities:\n \n for x,y in i.items():\n print(x,y,sep=\" : \")\n print()\n\n\n# In[ ]:\n\n\n### GETTING TEST DATA\n\nline = data[len(data)-1].split(\" \")\ntest = OBSERVATIONS(No_of_Ob+1,line[0],line[1],line[2],line[3])\n\nprint(\"Test Data : \\n\",line)\n\n\n# In[ ]:\n\n\n### STEP 1 : Find the Probability of given touple with every class attribute\n\ntempMap = {}\n\nfor x in count_OP.keys():\n \n temp=1\n \n for y,z in zip(listOfTitles,listOfProbabilities):\n \n key = getattr(test,str(y))+\"|\"+str(x) ### Change as per question\n ###print(key)\n if key in z:\n ###print(\"inside if\")\n temp = temp * z[key]\n else:\n ###print(\"inside else\")\n temp = temp*0\n \n tempMap[x] = temp\n \n \nprint(\"Probability of T = { test_dat} with YES and NO \\n\\n\") \nfor x,y in tempMap.items():\n print(x,y)\n \n \n### ALL respective probabilites are in tempMap\n\n\n# In[ ]:\n\n\n### NOW WE CALCULATE LIKELIHOOD for YES and NO\n### WE REPLACE VALUES IN tempMap with value(tempMap)*P(either YES OR NO)\n\nfor x in tempMap:\n tempMap[x] = tempMap[x]*prob_OP[x]\n\nprint(\"Likelihood for Yes and No : \\n\")\nfor x,y in tempMap.items():\n print(x,y)\n\n\n# In[ ]:\n\n\n### NOW we calculate ESTIMATED VALUE i.e. P(T)\n\nestVal = 0\nfor x in tempMap:\n estVal = tempMap[x]+estVal\n \nprint(\"Estimated value P(T) = \\n \",estVal)\n\n\n# In[ ]:\n\n\n### Calculating actual probability\nfinalProb = {}\n\nmax = float('-inf')\nans = ''\nfor x in tempMap:\n finalProb[x] = tempMap[x]/estVal\n ###print(finalProb[x],max)\n if finalProb[x] > max: ### Comapring for the highest probability and marking the output in ans.\n max = finalProb[x]\n ans = x\n \nprint(\"PLAY TENNIS = \"+str(ans))\n \n\n","repo_name":"TamsilAmani/First_Project","sub_path":"Naive Bayesian Classifier.py","file_name":"Naive Bayesian Classifier.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"72411908573","text":"# Задача 10: На столе лежат n монеток. Некоторые из них лежат вверх решкой, а\n# некоторые – гербом. Определите минимальное число монеток, которые нужно\n# перевернуть, чтобы все монетки были повернуты вверх одной и той же стороной.\n# Выведите минимальное количество монет, которые нужно перевернуть.\n# 5 -> 1 0 1 1 0\n# 2\n\n\nc = int(input(\"сколько лежит монет: \"))\nrever = aver = 0\nfor i in range(c):\n k = int(input(\"Введите 1 /орёл/ или 0 /решка/: \"))\n if k > 1:\n print(\"Вы ввели неверное число.\")\n k = int(input(\"Введите верное /1 или 0/: \"))\n elif k == 1:\n rever += 1\n elif k == 0:\n aver += 1\n\nif rever < aver:\n print(f'{rever}')\nelif rever > aver:\n print(f' {aver}')\nelse:\n print(c // 2)\n\n# c = int(input(\"сколько лежит монет: \"))\n# n = 0\n# for i in range(c):\n# k = int(input(\"Введите 1/орёл/ или 0/решка/: \"))\n# if k > 1:\n# print('Вы ввели неверное число')\n# k = int(input(\"Введите 1 или 0: \"))\n# elif k == 1:\n# n += 1\n#\n# if n < c / 2:\n# print(n)\n# else:\n# print(c - n)\n\n","repo_name":"VikBrains/repo-github","sub_path":"Python_New_GB_2/Task_10.py","file_name":"Task_10.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"43725175886","text":"from collections import deque\n\nfood_qty = int(input())\norders = deque(map(int, input().split()))\nprint(max(orders))\n\nfor order in orders.copy():\n if food_qty >= order:\n orders.popleft()\n food_qty -= order\n else:\n break\n\nif len(orders) > 0:\n print(f'Orders left: {\" \".join([str(x) for x in orders])}')\nelse:\n print('Orders complete')","repo_name":"KrasimirTolev/python_advanced","sub_path":"lists_as_stacks_and_queues_exersise/fast_food.py","file_name":"fast_food.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"9689676604","text":"import mock\n\nfrom testing_utils import testing\n\nfrom libs.test_results.gtest_test_results import GtestTestResults\nfrom libs.test_results import test_results_util\n\n\nclass TestResultsTest(testing.AppengineTestCase):\n\n @mock.patch.object(\n GtestTestResults, 'IsTestResultsInExpectedFormat', return_value=False)\n def testGetTestResultObjectNoMatch(self, _):\n self.assertIsNone(test_results_util.GetTestResultObject('log'))\n\n @mock.patch.object(\n GtestTestResults, 'IsTestResultsInExpectedFormat', return_value=True)\n def testGetTestResultObject(self, _):\n test_results = test_results_util.GetTestResultObject('log')\n self.assertTrue(isinstance(test_results, GtestTestResults))\n\n @mock.patch.object(\n test_results_util,\n 'GetTestResultObject',\n return_value=GtestTestResults('test_results_log'))\n def testIsTestResultsValid(self, _):\n self.assertTrue(test_results_util.IsTestResultsValid('test_results_log'))\n\n def testRemoveSuffixFromStepName(self):\n self.assertEqual(\n 'a_tests',\n test_results_util.RemoveSuffixFromStepName('a_tests on Platform'))\n self.assertEqual(\n 'a_tests',\n test_results_util.RemoveSuffixFromStepName('a_tests on Other-Platform'))\n self.assertEqual('a_tests',\n test_results_util.RemoveSuffixFromStepName('a_tests'))\n","repo_name":"xinghun61/infra","sub_path":"appengine/findit/libs/test_results/test/test_results_util_test.py","file_name":"test_results_util_test.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"4636993108","text":"# Read price sequence of each fund\nfrom extract_data import *\np_ivv = extract_data('ivv.txt')\np_ijh = extract_data('ijh.txt')\np_ijr = extract_data('ijr.txt')\np_efa = extract_data('efa.txt')\np_eem = extract_data('eem.txt')\np_iyr = extract_data('iyr.txt')\np_ifgl = extract_data('ifgl.txt')\np_agg = extract_data('agg.txt')\np_mub = extract_data('mub.txt')\np_iau = extract_data('iau.txt')\nprint(len(p_ivv))\nprint(len(p_ijh))\nprint(len(p_ijr))\nprint(len(p_efa))\nprint(len(p_eem))\nprint(len(p_iyr))\nprint(len(p_ifgl))\nprint(len(p_agg))\nprint(len(p_mub))\nprint(len(p_iau))\n\nfrom calc_return import *\ncalc_return_1yr(p_ijr)\n\n###################################################\n# Portfolio of US stocks: IVV + IJH + IJR\n###################################################\nf1 = open('us_1yr_return.txt', 'w')\nf3 = open('us_3yr_return.txt', 'w')\nf5 = open('us_5yr_return.txt', 'w')\nf1.write(\"IVV\"+'\\t'+\"IJH\"+'\\t'+\"IJR\"+'\\t'+\"Avg_return_1yr\"+'\\t'+\"Sigma_1yr\"+'\\n')\nf3.write(\"IVV\"+'\\t'+\"IJH\"+'\\t'+\"IJR\"+'\\t'+\"Avg_return_3yr\"+'\\t'+\"Sigma_3yr\"+'\\n')\nf5.write(\"IVV\"+'\\t'+\"IJH\"+'\\t'+\"IJR\"+'\\t'+\"Avg_return_5yr\"+'\\t'+\"Sigma_5yr\"+'\\n')\nfor w1 in range(0, 21):\n w_ivv = w1 * 0.05\n for w2 in range(0, 21-w1):\n w_ijh = w2 * 0.05\n w_ijr = 1 - w_ivv - w_ijh\n\n [p_return_1yr, p_sigma_1yr] = calc_return3_1yr(p_ivv, w_ivv, p_ijh, w_ijh, p_ijr, w_ijr, 200)\n print(p_return_1yr, p_sigma_1yr)\n f1.write(str(w_ivv) + '\\t' + str(w_ijh) + '\\t' + str(w_ijr) + '\\t' + str(p_return_1yr) + '\\t' + str(\n p_sigma_1yr) + '\\n')\n\n [p_return_3yr, p_sigma_3yr] = calc_return3_3yr(p_ivv, w_ivv, p_ijh, w_ijh, p_ijr, w_ijr, 200)\n print(p_return_3yr, p_sigma_3yr)\n f3.write(str(w_ivv) + '\\t' + str(w_ijh) + '\\t' + str(w_ijr) + '\\t' + str(p_return_3yr) + '\\t' + str(\n p_sigma_3yr) + '\\n')\n\n [p_return_5yr, p_sigma_5yr] = calc_return3_5yr(p_ivv, w_ivv, p_ijh, w_ijh, p_ijr, w_ijr, 200)\n print(p_return_5yr, p_sigma_5yr)\n f5.write(str(w_ivv) + '\\t' + str(w_ijh) + '\\t' + str(w_ijr) + '\\t' + str(p_return_5yr) + '\\t' + str(\n p_sigma_5yr) + '\\n')\n\nf1.close()\nf3.close()\nf5.close()\n\n###################################################\n# Portfolio of all 10 ETFs\n###################################################\nsharpe_max = [0] * 15\nw_ivv_opt = [0] * 15\nw_ijh_opt = [0] * 15\nw_ijr_opt = [0] * 15\nw_efa_opt = [0] * 15\nw_eem_opt = [0] * 15\nw_iyr_opt = [0] * 15\nw_ifgl_opt = [0] * 15\nw_agg_opt = [0] * 15\nw_mub_opt = [0] * 15\nw_iau_opt = [0] * 15\nreturn_opt = [0] * 15\nsigma_opt = [0] * 15\n\nfor w1 in range(0, 21):\n w_ivv = w1 * 0.05\n for w2 in range(0, 21-w1):\n w_ijh = w2 * 0.05\n for w3 in range(0, 21-w1-w2):\n w_ijr = w3 * 0.05\n for w4 in range(0, 21-w1-w2-w3):\n w_efa = w4 * 0.05\n for w5 in range(0, 21-w1-w2-w3-w4):\n w_eem = w5 * 0.05\n for w6 in range(0, 21-w1-w2-w3-w4-w5):\n w_iyr = w6 * 0.05\n for w7 in range(0, 21-w1-w2-w3-w4-w5-w6):\n w_ifgl = w7 * 0.05\n for w8 in range(0, 21-w1-w2-w3-w4-w5-w6-w7):\n w_agg = w8 * 0.05\n for w9 in range(0, 21-w1-w2-w3-w4-w5-w6-w7-w8):\n w_mub = w9 * 0.05\n w_iau = 1 - w_ivv - w_ijh - w_ijr - w_efa - w_eem - w_iyr - w_ifgl - w_agg - w_mub\n\n [p_return_1yr, p_sigma_1yr] = calc_return10_1yr(p_ivv, w_ivv, p_ijh, w_ijh, p_ijr,\n w_ijr, p_efa, w_efa, p_eem, w_eem,\n p_iyr, w_iyr, p_ifgl, w_ifgl, p_agg,\n w_agg, p_mub, w_mub, p_iau, w_iau,\n 109)\n print(p_return_1yr, p_sigma_1yr)\n sharpe = p_return_1yr / p_sigma_1yr\n i = int(p_return_1yr*100)\n if sharpe > sharpe_max[i]:\n sharpe_max[i] = sharpe\n return_opt[i] = p_return_1yr\n sigma_opt[i] = p_sigma_1yr\n w_ivv_opt[i] = w_ivv\n w_ijh_opt[i] = w_ijh\n w_ijr_opt[i] = w_ijr\n w_efa_opt[i] = w_efa\n w_eem_opt[i] = w_eem\n w_iyr_opt[i] = w_iyr\n w_ifgl_opt[i] = w_ifgl\n w_agg_opt[i] = w_agg\n w_mub_opt[i] = w_mub\n w_iau_opt[i] = w_iau\n else:\n continue\n\nprint(sharpe_max)\nprint(return_opt)\nprint(sigma_opt)\nprint(w_ivv_opt)\nprint(w_ijh_opt)\nprint(w_ijr_opt)\nprint(w_efa_opt)\nprint(w_eem_opt)\nprint(w_iyr_opt)\nprint(w_ifgl_opt)\nprint(w_agg_opt)\nprint(w_mub_opt)\nprint(w_iau_opt)\n","repo_name":"wizardyang/portfolio_eval","sub_path":"portfolio_eval.py","file_name":"portfolio_eval.py","file_ext":"py","file_size_in_byte":5445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"10986694978","text":"import Telefone,CPF,Email,time\r\n\r\nentS = [] # entrada separada\r\n\r\nwhile True:\r\n try:\r\n RM = int(input(\"\"\"Qual dos identificadores de validade voce quer usar\r\n [0] Numero de Telefone\r\n [1] CPF\r\n [2] Email\r\n \"\"\"))\r\n ent = input(\"Qual o termo que voce quer validar? \")\r\n if RM == 0:\r\n Telefone.Telefone(ent)\r\n elif RM == 1:\r\n CPF.CPF(ent)\r\n elif RM == 2:\r\n Email.Email(ent)\r\n else:\r\n print(\"Tu é burro pra krl\")\r\n time.sleep(10)\r\n except ValueError:\r\n print(\"Invalido\")\r\n pass\r\n\r\n","repo_name":"DouglasEd/Pratica2Claudio","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"13248686385","text":"import sys\nsys.stdin = open(\"4613_input.txt\")\n\nT = int(input())\n\nfor tc in range(1,T+1):\n N, M = map(int, input().split())\n arr = []\n res = []\n\n for i in range(N):\n arr += [' '.join(input()).split()]\n\n for i in range(1,N-1):\n for j in range(1,N-i):\n k = N - i - j\n cnt = 0\n for a in range(N):\n if 0 <= a < i:\n obj = 'W'\n elif i <= a < j+i:\n obj = 'B'\n else:\n obj = 'R'\n for b in range(M):\n if arr[a][b] != obj:\n cnt += 1\n res += [cnt]\n\n min_v = res[0]\n for i in range(len(res)):\n if min_v > res[i]:\n min_v = res[i]\n print('#{} {}'.format(tc,min_v))","repo_name":"steven9408/Algorithm_Study","sub_path":"SWEA/SSAFY/04_queue/210305/4613.py","file_name":"4613.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"27435429061","text":"import asyncio\nimport io\nimport math\nimport urllib.request\nfrom os import remove\nfrom secrets import choice\n\nimport requests\nfrom bs4 import BeautifulSoup as bs\nfrom PIL import Image\nfrom telethon import events\nfrom telethon.errors import PackShortNameOccupiedError\nfrom telethon.errors.rpcerrorlist import YouBlockedUserError\nfrom telethon.tl import functions, types\nfrom telethon.tl.functions.contacts import UnblockRequest\nfrom telethon.tl.functions.messages import GetStickerSetRequest\nfrom telethon.tl.types import (\n DocumentAttributeFilename,\n DocumentAttributeSticker,\n InputStickerSetID,\n MessageMediaPhoto,\n MessageMediaUnsupported,\n)\nfrom telethon.utils import get_input_document\n\nfrom userbot import CMD_HANDLER as cmd\nfrom userbot import CMD_HELP\nfrom userbot import S_PACK_NAME as custompack\nfrom userbot import tgbot\nfrom userbot.modules.sql_helper.globals import addgvar, gvarstatus\nfrom userbot.utils import edit_delete, edit_or_reply, man_cmd\nfrom userbot.utils.misc import animator\n\nKANGING_STR = [\n \"Colong Sticker dulu yee kan\",\n \"Ini Sticker aku colong yaa DUARR!\",\n \"Waw Stickernya Bagus Nih...Colong Dulu Yekan..\",\n \"ehh, keren nih... gua colong ya stickernya...\",\n \"Boleh juga ni Sticker Colong ahh~\",\n]\n\n\n@man_cmd(pattern=\"(?:tikel|kang)\\s?(.)?\")\nasync def kang(args):\n user = await args.client.get_me()\n if not user.username:\n user.username = user.first_name\n message = await args.get_reply_message()\n photo = None\n emojibypass = False\n is_video = False\n is_anim = False\n emoji = None\n\n if not message:\n return await edit_delete(\n args, \"**Silahkan Reply Ke Pesan Media Untuk Mencuri Sticker itu!**\"\n )\n\n if isinstance(message.media, MessageMediaPhoto):\n xx = await edit_or_reply(args, f\"`{choice(KANGING_STR)}`\")\n photo = io.BytesIO()\n photo = await args.client.download_media(message.photo, photo)\n elif isinstance(message.media, MessageMediaUnsupported):\n await edit_delete(\n args, \"**File Tidak Didukung, Silahkan Reply ke Media Foto/GIF !**\"\n )\n elif message.file and \"image\" in message.file.mime_type.split(\"/\"):\n xx = await edit_or_reply(args, f\"`{choice(KANGING_STR)}`\")\n photo = io.BytesIO()\n await args.client.download_file(message.media.document, photo)\n if (\n DocumentAttributeFilename(file_name=\"sticker.webp\")\n in message.media.document.attributes\n ):\n emoji = message.media.document.attributes[1].alt\n if emoji != \"✨\":\n emojibypass = True\n elif message.file and \"tgsticker\" in message.file.mime_type:\n xx = await edit_or_reply(args, f\"`{choice(KANGING_STR)}`\")\n await args.client.download_file(message.media.document, \"AnimatedSticker.tgs\")\n attributes = message.media.document.attributes\n for attribute in attributes:\n if isinstance(attribute, DocumentAttributeSticker):\n emoji = attribute.alt\n emojibypass = True\n is_anim = True\n photo = 1\n elif message.media.document.mime_type in [\"video/mp4\", \"video/webm\"]:\n if message.media.document.mime_type == \"video/webm\":\n xx = await edit_or_reply(args, f\"`{choice(KANGING_STR)}`\")\n await args.client.download_media(message.media.document, \"Video.webm\")\n else:\n xx = await edit_or_reply(args, \"`Downloading...`\")\n await animator(message, args, xx)\n await xx.edit(f\"`{choice(KANGING_STR)}`\")\n is_video = True\n emoji = \"✨\"\n emojibypass = True\n photo = 1\n else:\n return await edit_delete(\n args, \"**File Tidak Didukung, Silahkan Reply ke Media Foto/GIF !**\"\n )\n if photo:\n splat = args.text.split()\n if not emojibypass:\n emoji = \"✨\"\n pack = 1\n if len(splat) == 3:\n pack = splat[2]\n emoji = splat[1]\n elif len(splat) == 2:\n if splat[1].isnumeric():\n pack = int(splat[1])\n else:\n emoji = splat[1]\n\n packname = f\"Sticker_u{user.id}_Ke{pack}\"\n if custompack is not None:\n packnick = f\"{custompack}\"\n else:\n f_name = f\"@{user.username}\" if user.username else user.first_name\n packnick = f\"Sticker Pack {f_name}\"\n\n cmd = \"/newpack\"\n file = io.BytesIO()\n\n if is_video:\n packname += \"_vid\"\n packnick += \" (Video)\"\n cmd = \"/newvideo\"\n elif is_anim:\n packname += \"_anim\"\n packnick += \" (Animated)\"\n cmd = \"/newanimated\"\n else:\n image = await resize_photo(photo)\n file.name = \"sticker.png\"\n image.save(file, \"PNG\")\n\n response = urllib.request.urlopen(\n urllib.request.Request(f\"http://t.me/addstickers/{packname}\")\n )\n htmlstr = response.read().decode(\"utf8\").split(\"\\n\")\n\n if (\n \" A Telegram user has created the Sticker Set.\"\n not in htmlstr\n ):\n async with args.client.conversation(\"@Stickers\") as conv:\n try:\n await conv.send_message(\"/addsticker\")\n except YouBlockedUserError:\n await args.client(UnblockRequest(\"@Stickers\"))\n await conv.send_message(\"/addsticker\")\n await conv.get_response()\n await args.client.send_read_acknowledge(conv.chat_id)\n await conv.send_message(packname)\n x = await conv.get_response()\n limit = \"50\" if (is_anim or is_video) else \"120\"\n while limit in x.text:\n pack += 1\n if custompack is not None:\n packname = f\"Sticker_u{user.id}_Ke{pack}\"\n packnick = f\"{custompack}\"\n else:\n f_name = (\n f\"@{user.username}\" if user.username else user.first_name\n )\n packname = f\"Sticker_u{user.id}_Ke{pack}\"\n packnick = f\"Sticker Pack {f_name}\"\n await xx.edit(\n \"`Membuat Sticker Pack Baru \"\n + str(pack)\n + \" Karena Sticker Pack Sudah Penuh`\"\n )\n await conv.send_message(packname)\n x = await conv.get_response()\n if x.text == \"Gagal Memilih Pack.\":\n await conv.send_message(cmd)\n await conv.get_response()\n await args.client.send_read_acknowledge(conv.chat_id)\n await conv.send_message(packnick)\n await conv.get_response()\n await args.client.send_read_acknowledge(conv.chat_id)\n if is_anim:\n await conv.send_file(\"AnimatedSticker.tgs\")\n remove(\"AnimatedSticker.tgs\")\n elif is_video:\n await conv.send_file(\"Video.webm\")\n remove(\"Video.webm\")\n else:\n file.seek(0)\n await conv.send_file(file, force_document=True)\n await conv.get_response()\n await conv.send_message(emoji)\n await args.client.send_read_acknowledge(conv.chat_id)\n await conv.get_response()\n await conv.send_message(\"/publish\")\n if is_anim:\n await conv.get_response()\n await conv.send_message(f\"<{packnick}>\")\n await conv.get_response()\n await args.client.send_read_acknowledge(conv.chat_id)\n await conv.send_message(\"/skip\")\n await args.client.send_read_acknowledge(conv.chat_id)\n await conv.get_response()\n await conv.send_message(packname)\n await args.client.send_read_acknowledge(conv.chat_id)\n await conv.get_response()\n await args.client.send_read_acknowledge(conv.chat_id)\n return await xx.edit(\n \"`Sticker ditambahkan ke pack yang berbeda !\"\n \"\\nIni pack yang baru saja dibuat!\"\n f\"\\nTekan [Sticker Pack](t.me/addstickers/{packname}) Untuk Melihat Sticker Pack\",\n parse_mode=\"md\",\n )\n if is_anim:\n await conv.send_file(\"AnimatedSticker.tgs\")\n remove(\"AnimatedSticker.tgs\")\n elif is_video:\n await conv.send_file(\"Video.webm\")\n remove(\"Video.webm\")\n else:\n file.seek(0)\n await conv.send_file(file, force_document=True)\n rsp = await conv.get_response()\n if \"Sorry, the file type is invalid.\" in rsp.text:\n return await xx.edit(\n \"**Gagal Menambahkan Sticker, Gunakan @Stickers Bot Untuk Menambahkan Sticker Anda.**\"\n )\n await conv.send_message(emoji)\n await args.client.send_read_acknowledge(conv.chat_id)\n await conv.get_response()\n await conv.send_message(\"/done\")\n await conv.get_response()\n await args.client.send_read_acknowledge(conv.chat_id)\n else:\n await xx.edit(\"`Membuat Sticker Pack Baru`\")\n async with args.client.conversation(\"@Stickers\") as conv:\n try:\n await conv.send_message(cmd)\n except YouBlockedUserError:\n await args.client(UnblockRequest(\"@Stickers\"))\n await conv.send_message(cmd)\n await conv.get_response()\n await args.client.send_read_acknowledge(conv.chat_id)\n await conv.send_message(packnick)\n await conv.get_response()\n await args.client.send_read_acknowledge(conv.chat_id)\n if is_anim:\n await conv.send_file(\"AnimatedSticker.tgs\")\n remove(\"AnimatedSticker.tgs\")\n elif is_video:\n await conv.send_file(\"Video.webm\")\n remove(\"Video.webm\")\n else:\n file.seek(0)\n await conv.send_file(file, force_document=True)\n rsp = await conv.get_response()\n if \"Sorry, the file type is invalid.\" in rsp.text:\n return await xx.edit(\n \"**Gagal Menambahkan Sticker, Gunakan @Stickers Bot Untuk Menambahkan Sticker.**\"\n )\n await conv.send_message(emoji)\n await args.client.send_read_acknowledge(conv.chat_id)\n await conv.get_response()\n await conv.send_message(\"/publish\")\n if is_anim:\n await conv.get_response()\n await conv.send_message(f\"<{packnick}>\")\n await conv.get_response()\n await args.client.send_read_acknowledge(conv.chat_id)\n await conv.send_message(\"/skip\")\n await args.client.send_read_acknowledge(conv.chat_id)\n await conv.get_response()\n await conv.send_message(packname)\n await args.client.send_read_acknowledge(conv.chat_id)\n await conv.get_response()\n await args.client.send_read_acknowledge(conv.chat_id)\n\n await xx.edit(\n \"** Sticker Berhasil Ditambahkan!**\"\n f\"\\n 👻 **[KLIK DISINI](t.me/addstickers/{packname})** 👻\\n**Untuk Menggunakan Stickers**\",\n parse_mode=\"md\",\n )\n\n\nasync def resize_photo(photo):\n image = Image.open(photo)\n if (image.width and image.height) < 512:\n size1 = image.width\n size2 = image.height\n if size1 > size2:\n scale = 512 / size1\n size1new = 512\n size2new = size2 * scale\n else:\n scale = 512 / size2\n size1new = size1 * scale\n size2new = 512\n size1new = math.floor(size1new)\n size2new = math.floor(size2new)\n sizenew = (size1new, size2new)\n image = image.resize(sizenew)\n else:\n maxsize = (512, 512)\n image.thumbnail(maxsize)\n\n return image\n\n\n@man_cmd(pattern=\"pkang(?:\\\\s|$)([\\\\s\\\\S]*)\")\nasync def _(event):\n xnxx = await edit_or_reply(event, f\"`{choice(KANGING_STR)}`\")\n reply = await event.get_reply_message()\n query = event.text[7:]\n ManUbot = await tgbot.get_me()\n BOT_USERNAME = ManUbot.username\n bot_ = BOT_USERNAME\n bot_un = bot_.replace(\"@\", \"\")\n user = await event.client.get_me()\n OWNER_ID = user.id\n un = f\"@{user.username}\" if user.username else user.first_name\n un_ = user.username or OWNER_ID\n if not reply:\n return await edit_delete(\n xnxx, \"**Mohon Balas sticker untuk mencuri semua Sticker Pack itu.**\"\n )\n pname = f\"{un} Sticker Pack\" if query == \"\" else query\n if reply.media and reply.media.document.mime_type == \"image/webp\":\n tikel_id = reply.media.document.attributes[1].stickerset.id\n tikel_hash = reply.media.document.attributes[1].stickerset.access_hash\n got_stcr = await event.client(\n functions.messages.GetStickerSetRequest(\n stickerset=types.InputStickerSetID(id=tikel_id, access_hash=tikel_hash)\n )\n )\n stcrs = []\n for sti in got_stcr.documents:\n inp = get_input_document(sti)\n stcrs.append(\n types.InputStickerSetItem(\n document=inp,\n emoji=(sti.attributes[1]).alt,\n )\n )\n try:\n gvarstatus(\"PKANG\")\n except BaseException:\n addgvar(\"PKANG\", \"0\")\n x = gvarstatus(\"PKANG\")\n try:\n pack = int(x) + 1\n except BaseException:\n pack = 1\n await xnxx.edit(f\"`{choice(KANGING_STR)}`\")\n try:\n create_st = await tgbot(\n functions.stickers.CreateStickerSetRequest(\n user_id=OWNER_ID,\n title=pname,\n short_name=f\"man_{un_}_V{pack}_by_{bot_un}\",\n stickers=stcrs,\n )\n )\n addgvar(\"PKANG\", str(pack))\n except PackShortNameOccupiedError:\n await asyncio.sleep(1)\n await xnxx.edit(\"`Sedang membuat paket baru...`\")\n pack += 1\n create_st = await tgbot(\n functions.stickers.CreateStickerSetRequest(\n user_id=OWNER_ID,\n title=pname,\n short_name=f\"man_{un_}_V{pack}_by_{bot_un}\",\n stickers=stcrs,\n )\n )\n addgvar(\"PKANG\", str(pack))\n await xnxx.edit(\n f\"**Berhasil Mencuri Sticker Pack,** [Klik Disini](t.me/addstickers/{create_st.set.short_name}) **Untuk Melihat Pack anda**\"\n )\n else:\n await xnxx.edit(\"**Berkas Tidak Didukung. Harap Balas ke stiker saja.**\")\n\n\n@man_cmd(pattern=\"stickerinfo$\")\nasync def get_pack_info(event):\n if not event.is_reply:\n return await edit_delete(event, \"**Mohon Balas Ke Sticker**\")\n\n rep_msg = await event.get_reply_message()\n if not rep_msg.document:\n return await edit_delete(\n event, \"**Balas ke sticker untuk melihat detail pack**\"\n )\n\n try:\n stickerset_attr = rep_msg.document.attributes[1]\n xx = await edit_or_reply(event, \"`Processing...`\")\n except BaseException:\n return await edit_delete(xx, \"**Ini bukan sticker, Mohon balas ke sticker.**\")\n\n if not isinstance(stickerset_attr, DocumentAttributeSticker):\n return await edit_delete(xx, \"**Ini bukan sticker, Mohon balas ke sticker.**\")\n\n get_stickerset = await event.client(\n GetStickerSetRequest(\n InputStickerSetID(\n id=stickerset_attr.stickerset.id,\n access_hash=stickerset_attr.stickerset.access_hash,\n )\n )\n )\n pack_emojis = []\n for document_sticker in get_stickerset.packs:\n if document_sticker.emoticon not in pack_emojis:\n pack_emojis.append(document_sticker.emoticon)\n\n OUTPUT = (\n f\"âž  **Nama Sticker:** [{get_stickerset.set.title}](http://t.me/addstickers/{get_stickerset.set.short_name})\\n\"\n f\"âž  **Official:** `{get_stickerset.set.official}`\\n\"\n f\"âž  **Arsip:** `{get_stickerset.set.archived}`\\n\"\n f\"âž  **Sticker Dalam Pack:** `{len(get_stickerset.packs)}`\\n\"\n f\"âž  **Emoji Dalam Pack:** {' '.join(pack_emojis)}\"\n )\n\n await xx.edit(OUTPUT)\n\n\n@man_cmd(pattern=\"delsticker ?(.*)\")\nasync def _(event):\n if event.fwd_from:\n return\n if not event.reply_to_msg_id:\n await edit_delete(event, \"**Mohon Reply ke Sticker yang ingin anda Hapus.**\")\n return\n reply_message = await event.get_reply_message()\n chat = \"@Stickers\"\n if reply_message.sender.bot:\n await edit_delete(event, \"**Mohon Reply ke Sticker.**\")\n return\n xx = await edit_or_reply(event, \"`Processing...`\")\n async with event.client.conversation(chat) as conv:\n try:\n response = conv.wait_event(\n events.NewMessage(incoming=True, from_users=429000)\n )\n await conv.send_message(\"/delsticker\")\n await conv.get_response()\n await asyncio.sleep(2)\n await event.client.forward_messages(chat, reply_message)\n response = await response\n except YouBlockedUserError:\n await event.client(UnblockRequest(chat))\n await conv.send_message(\"/delsticker\")\n await conv.get_response()\n await asyncio.sleep(2)\n await event.client.forward_messages(chat, reply_message)\n response = await response\n if response.text.startswith(\n \"Sorry, I can't do this, it seems that you are not the owner of the relevant pack.\"\n ):\n await xx.edit(\"**Maaf, Sepertinya Anda bukan Pemilik Sticker pack ini.**\")\n elif response.text.startswith(\n \"You don't have any sticker packs yet. You can create one using the /newpack command.\"\n ):\n await xx.edit(\"**Anda Tidak Memiliki Stiker untuk di Hapus**\")\n elif response.text.startswith(\"Please send me the sticker.\"):\n await xx.edit(\"**Tolong Reply ke Sticker yang ingin dihapus**\")\n elif response.text.startswith(\"Invalid pack selected.\"):\n await xx.edit(\"**Maaf Paket yang dipilih tidak valid.**\")\n else:\n await xx.edit(\"**Berhasil Menghapus Stiker.**\")\n\n\n@man_cmd(pattern=\"editsticker ?(.*)\")\nasync def _(event):\n if event.fwd_from:\n return\n if not event.reply_to_msg_id:\n await edit_delete(event, \"**Mohon Reply ke Sticker dan Berikan emoji.**\")\n return\n reply_message = await event.get_reply_message()\n emot = event.pattern_match.group(1)\n if reply_message.sender.bot:\n await edit_delete(event, \"**Mohon Reply ke Sticker.**\")\n return\n xx = await edit_or_reply(event, \"`Processing...`\")\n if emot == \"\":\n await xx.edit(\"**Silahkan Kirimkan Emot Baru.**\")\n else:\n chat = \"@Stickers\"\n async with event.client.conversation(chat) as conv:\n try:\n response = conv.wait_event(\n events.NewMessage(incoming=True, from_users=429000)\n )\n await conv.send_message(\"/editsticker\")\n await conv.get_response()\n await asyncio.sleep(2)\n await event.client.forward_messages(chat, reply_message)\n await conv.get_response()\n await asyncio.sleep(2)\n await conv.send_message(f\"{emot}\")\n response = await response\n except YouBlockedUserError:\n await event.client(UnblockRequest(chat))\n await conv.send_message(\"/editsticker\")\n await conv.get_response()\n await asyncio.sleep(2)\n await event.client.forward_messages(chat, reply_message)\n await conv.get_response()\n await asyncio.sleep(2)\n await conv.send_message(f\"{emot}\")\n response = await response\n if response.text.startswith(\"Invalid pack selected.\"):\n await xx.edit(\"**Maaf Paket yang dipilih tidak valid.**\")\n elif response.text.startswith(\n \"Please send us an emoji that best describes your sticker.\"\n ):\n await xx.edit(\n \"**Silahkan Kirimkan emoji yang paling menggambarkan stiker Anda.**\"\n )\n else:\n await xx.edit(\n f\"**Berhasil Mengedit Emoji Stiker**\\n**Emoji Baru:** {emot}\"\n )\n\n\n@man_cmd(pattern=\"getsticker$\")\nasync def sticker_to_png(sticker):\n if not sticker.is_reply:\n await edit_delete(sticker, \"**Harap balas ke stiker**\")\n return False\n img = await sticker.get_reply_message()\n if not img.document:\n await edit_delete(sticker, \"**Maaf , Ini Bukan Sticker**\")\n return False\n xx = await edit_or_reply(sticker, \"`Berhasil Mengambil Sticker!`\")\n image = io.BytesIO()\n await sticker.client.download_media(img, image)\n image.name = \"sticker.png\"\n image.seek(0)\n await sticker.client.send_file(\n sticker.chat_id, image, reply_to=img.id, force_document=True\n )\n await xx.delete()\n\n\n@man_cmd(pattern=\"stickers ?([\\s\\S]*)\")\nasync def cb_sticker(event):\n query = event.pattern_match.group(1)\n if not query:\n return await edit_delete(event, \"**Masukan Nama Sticker Pack!**\")\n xx = await edit_or_reply(event, \"`Searching sticker packs...`\")\n text = requests.get(f\"https://combot.org/telegram/stickers?q={query}\").text\n soup = bs(text, \"lxml\")\n results = soup.find_all(\"div\", {\"class\": \"sticker-pack__header\"})\n if not results:\n return await edit_delete(xx, \"**Tidak Dapat Menemukan Sticker Pack 🥺**\")\n reply = f\"**Keyword Sticker Pack:**\\n {query}\\n\\n**Hasil:**\\n\"\n for pack in results:\n if pack.button:\n packtitle = (pack.find(\"div\", \"sticker-pack__title\")).get_text()\n packlink = (pack.a).get(\"href\")\n reply += f\" • [{packtitle}]({packlink})\\n\"\n await xx.edit(reply)\n\n\n@man_cmd(pattern=\"itos$\")\nasync def _(event):\n if event.fwd_from:\n return\n if not event.reply_to_msg_id:\n await edit_delete(\n event, \"sir this is not a image message reply to image message\"\n )\n return\n reply_message = await event.get_reply_message()\n if not reply_message.media:\n await edit_delete(event, \"sir, This is not a image \")\n return\n chat = \"@buildstickerbot\"\n xx = await edit_or_reply(event, \"Membuat Sticker..\")\n async with event.client.conversation(chat) as conv:\n try:\n response = conv.wait_event(\n events.NewMessage(incoming=True, from_users=164977173)\n )\n msg = await event.client.forward_messages(chat, reply_message)\n response = await response\n except YouBlockedUserError:\n await event.client(UnblockRequest(chat))\n msg = await event.client.forward_messages(chat, reply_message)\n response = await response\n if response.text.startswith(\"Hi!\"):\n await xx.edit(\n \"Can you kindly disable your forward privacy settings for good?\"\n )\n else:\n await xx.delete()\n await event.client.send_read_acknowledge(conv.chat_id)\n await event.client.send_message(event.chat_id, response.message)\n await event.client.delete_message(event.chat_id, [msg.id, response.id])\n\n\n@man_cmd(pattern=\"get$\")\nasync def _(event):\n rep_msg = await event.get_reply_message()\n if not event.is_reply or not rep_msg.sticker:\n return await edit_delete(event, \"**Harap balas ke stiker**\")\n xx = await edit_or_reply(event, \"`Mengconvert ke foto...`\")\n foto = io.BytesIO()\n foto = await event.client.download_media(rep_msg.sticker, foto)\n im = Image.open(foto).convert(\"RGB\")\n im.save(\"sticker.png\", \"png\")\n await event.client.send_file(\n event.chat_id,\n \"sticker.png\",\n reply_to=rep_msg,\n )\n await xx.delete()\n remove(\"sticker.png\")\n\n\nCMD_HELP.update(\n {\n \"stickers\": f\"**Plugin : **`stickers`\\\n \\n\\n • **Syntax :** `{cmd}kang` atau `{cmd}tikel` [emoji]\\\n \\n • **Function : **Balas .kang Ke Sticker Atau Gambar Untuk Menambahkan Ke Sticker Pack Mu\\\n \\n\\n • **Syntax :** `{cmd}kang` [emoji] atau `{cmd}tikel` [emoji]\\\n \\n • **Function : **Balas {cmd}kang emoji Ke Sticker Atau Gambar Untuk Menambahkan dan costum emoji sticker Ke Pack Mu\\\n \\n\\n • **Syntax :** `{cmd}pkang` \\\n \\n • **Function : **Balas {cmd}pkang Ke Sticker Untuk Mencuri semua sticker pack tersebut\\\n \\n\\n • **Syntax :** `{cmd}delsticker` \\\n \\n • **Function : **Untuk Menghapus sticker dari Sticker Pack.\\\n \\n\\n • **Syntax :** `{cmd}editsticker` \\\n \\n • **Function : **Untuk Mengedit emoji stiker dengan emoji yang baru.\\\n \\n\\n • **Syntax :** `{cmd}stickerinfo`\\\n \\n • **Function : **Untuk Mendapatkan Informasi Sticker Pack.\\\n \\n\\n • **Syntax :** `{cmd}stickers` \\\n \\n • **Function : **Untuk Mencari Sticker Pack.\\\n \\n\\n • **NOTE:** Untuk Membuat Sticker Pack baru Gunakan angka dibelakang `{cmd}kang`\\\n \\n • **CONTOH:** `{cmd}kang 2` untuk membuat dan menyimpan ke sticker pack ke 2\\\n \"\n }\n)\n\n\nCMD_HELP.update(\n {\n \"sticker_v2\": f\"**Plugin : **`stickers`\\\n \\n\\n • **Syntax :** `{cmd}getsticker`\\\n \\n • **Function : **Balas Ke Stcker Untuk Mendapatkan File 'PNG' Sticker.\\\n \\n\\n • **Syntax :** `{cmd}get`\\\n \\n • **Function : **Balas ke sticker untuk mendapatkan foto sticker\\\n \\n\\n • **Syntax :** `{cmd}itos`\\\n \\n • **Function : **Balas ke foto untuk membuat foto menjadi sticker\\\n \"\n }\n)\n","repo_name":"mrismanaziz/Man-Userbot","sub_path":"userbot/modules/stickers.py","file_name":"stickers.py","file_ext":"py","file_size_in_byte":27242,"program_lang":"python","lang":"en","doc_type":"code","stars":198,"dataset":"github-code","pt":"33"} +{"seq_id":"73076138335","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n # In case of one of them is NULL return the other one\n if t1 is None:\n return t2\n elif t2 is None:\n return t1\n\n # Initiate DFS\n t_res = TreeNode(t1.val + t2.val)\n stuck = [(t1, t2, t_res)]\n\n # DFS\n while len(stuck) > 0:\n cur_elem = stuck.pop(0)\n\n if (cur_elem[0] is not None and cur_elem[0].left is not None) \\\n or (cur_elem[1] is not None and cur_elem[1].left is not None):\n new_node_val = 0\n next_t1_node = None\n next_t2_node = None\n if cur_elem[0] is not None and cur_elem[0].left is not None:\n new_node_val += cur_elem[0].left.val\n next_t1_node = cur_elem[0].left\n if cur_elem[1] is not None and cur_elem[1].left is not None:\n new_node_val += cur_elem[1].left.val\n next_t2_node = cur_elem[1].left\n new_node = TreeNode(new_node_val)\n cur_elem[2].left = new_node\n\n stuck.insert(0, (next_t1_node, next_t2_node, new_node))\n\n if (cur_elem[0] is not None and cur_elem[0].right is not None) \\\n or (cur_elem[1] is not None and cur_elem[1].right is not None):\n new_node_val = 0\n next_t1_node = None\n next_t2_node = None\n if cur_elem[0] is not None and cur_elem[0].right is not None:\n new_node_val += cur_elem[0].right.val\n next_t1_node = cur_elem[0].right\n if cur_elem[1] is not None and cur_elem[1].right is not None:\n new_node_val += cur_elem[1].right.val\n next_t2_node = cur_elem[1].right\n new_node = TreeNode(new_node_val)\n cur_elem[2].right = new_node\n\n stuck.insert(0, (next_t1_node, next_t2_node, new_node))\n\n return t_res\n\n\n# Sample test case:\n# Input:\n# -\n# Output:\n# -\n\n# Performance Result:\n# Coding Time: 00:28:47\n# Time Complexity: O(N)\n# Space Complexity: O(N)\n# Runtime: 96 ms, faster than 18.89% of Python3\n# online submissions for Merge Two Binary Trees.\n# Memory Usage: 13 MB, less than 100.00% of Python3\n# online submissions for Merge Two Binary Trees.\n","repo_name":"zuqqhi2/my-leetcode-answers","sub_path":"617-Merge-Two-Binary-Trees.py","file_name":"617-Merge-Two-Binary-Trees.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"16163567787","text":"# from data import *\r\n# from atm import mainfunc\r\natm = None\r\ndef load_amount():\r\n global atm\r\n print(\"Load option \\n\")\r\n amount = int(input(\"Enter the amount \\n\"))\r\n print(\"Enter the atm.denomination \\n\")\r\n n2 = int(input(\"Enter the no of 2000 \\n\"))\r\n n5 = int(input(\"Enter the no of 500 \\n\"))\r\n chk = (n2*2000)+(n5*500)\r\n if(atm.denomination[2000]+n2 <= 100 and atm.denomination[500]+n5 <= 100):\r\n if(chk == amount):\r\n atm.atm_balance += chk\r\n atm.denomination[2000] += n2\r\n atm.denomination[500] += n5\r\n print(\"Amount of\", amount ,\"loaded successfully \\n\")\r\n print(\"The new ATM balance is\",atm.atm_balance ,\"\\n\")\r\n else:\r\n print(\"The entered amount and atm.denomination does not match \\n\")\r\n else:\r\n print(\"You can insert only \", 100 - atm.denomination[2000], \"2000 notes \\n\")\r\n print(\"You can insert only \", 100 -atm.denomination[2000], \"2000 notes \\n\")\r\n\r\ndef chk_atm_balance(atm_balance):\r\n print(\"Checking your balance....... \\n\")\r\n print(\"The available ATM balance is\",atm_balance)\r\n print(\"\\n\")\r\ndef admin(at):\r\n global atm\r\n atm = at\r\n us_name = input(\"Enter username \\n\")\r\n pas = input(\"Enter your password \\n\")\r\n if (us_name!=atm.admin_user or pas!=atm.admin_pass):\r\n print(\"Enter valid crdentials\")\r\n print(\"\\n\")\r\n return \r\n else:\r\n while True:\r\n print(\"\\n\")\r\n print(\"1. Check ATM balance\")\r\n print(\"2. Load amount\")\r\n print(\"Press any other number to return to main menu\")\r\n print(\"\\n\")\r\n op = int(input(\"Enter your choice\"))\r\n if(op==1):\r\n chk_atm_balance(atm.atm_balance)\r\n elif(op==2):\r\n load_amount()\r\n else:\r\n print(\"\\n Thank you for using our ATM\")\r\n break\r\n \r\n","repo_name":"sunilsks1412/Console-ATM","sub_path":"admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"23817225811","text":"\"\"\"\n Scalanie (mergesort)\n\"\"\"\nfrom tester import Sorter\n\n\nclass Merge_sort(Sorter):\n def __str__(self):\n return \"Merge Sort\"\n\n def sort(self):\n self.mergeSort(self.array)\n\n def mergeSort(self, arr):\n if len(arr) <= 1:\n return arr\n mid = len(arr) // 2\n left = arr[:mid]\n right = arr[mid:]\n\n self.mergeSort(left)\n self.mergeSort(right)\n self.merge(left, right, arr)\n\n def merge(self, left, right, arr):\n i = j = k = 0\n while i < len(left) and j < len(right):\n if left[i] < right[j]:\n arr[k] = left[i]\n i += 1\n else:\n arr[k] = right[j]\n j += 1\n k += 1\n\n while i < len(left):\n arr[k] = left[i]\n i += 1\n k += 1\n while j < len(right):\n arr[k] = right[j]\n j += 1\n k += 1\n\n\ndef main():\n sort = Merge_sort()\n sort.main()\n sort.print_results()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Isur/python-algorithms","sub_path":"app/sorting/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"26683740744","text":"'''\nThis module defines the entire model architecture and combines the different\npieces that are defined in other modules. It also defines a method for model\ntraining and defines some default configuration for the model such as the\npatching size P.\n'''\nimport datetime\n\nimport numpy as np\nimport torch\n\nimport Patching as p\nimport Recognition as r\nimport ResNet as rn\nimport Constants\n\n\nclass PatchingModel(torch.nn.Module):\n\n def __init__(self, height_width, P, c_prime):\n super(PatchingModel, self).__init__()\n self.resnet = rn.get_resnet_model()\n self.patching = p.Patching(height_width, P)\n self.recognition = r.Recognition(c_prime)\n\n def forward(self, x):\n output = self.resnet(x)\n output = self.patching(output)\n output = self.recognition(output)\n return output\n\n# Define default model configuration\nresnet_out_height_width = int(Constants.image_crop_size/32)\nc_prime = 2048\nP = 6\npatching_model = PatchingModel(resnet_out_height_width, P, c_prime)\noptimizer = torch.optim.Adam(patching_model.parameters(), lr=0.001, weight_decay=0.1)\nn_epochs = 10\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\ndef custom_loss(output, target):\n positive_prob_loss = torch.sum(target * torch.log(output))\n negative_prob_loss = torch.sum((1 - target) * torch.log(1 - output))\n total_loss = -positive_prob_loss - negative_prob_loss\n return total_loss\n\ndef train_model(train_dataloader, model = patching_model, n_epoch=n_epochs, optimizer=optimizer):\n model.train()\n for epoch in range(n_epoch):\n print(f\"Starting Epoch {epoch}\")\n print(datetime.datetime.now())\n curr_epoch_loss = []\n for data, target in train_dataloader:\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n output = 1 - output\n output = (output * 0.02) + 0.98\n output = torch.prod(output, 3)\n output = torch.prod(output, 2)\n prediction = 1 - output\n loss = custom_loss(prediction, target)\n loss.backward()\n curr_epoch_loss.append(loss.cpu().data.numpy())\n optimizer.step()\n\n del loss\n del output\n del prediction\n del data\n del target\n torch.cuda.empty_cache()\n\n print(f\"Epoch {epoch}: curr_epoch_loss={np.mean(curr_epoch_loss)}\")\n return model\n","repo_name":"dawei1/cs598_project","sub_path":"full_model.py","file_name":"full_model.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"19979895084","text":"import argparse\n\nfrom support import timing\n\n\ndef compute(s: str) -> None:\n layer_size = 25 * 6\n s = s.strip()\n n_layers = len(s) // layer_size\n layers = [\n s[i * layer_size:layer_size + i * layer_size]\n for i in range(n_layers)\n ]\n\n for y in range(6):\n for x in range(25):\n for layer in layers:\n if layer[y * 25 + x] != '2':\n print(layer[y * 25 + x].replace('0', ' '), end='')\n break\n else:\n print('?', end='')\n print()\n\n\ndef main() -> int:\n parser = argparse.ArgumentParser()\n parser.add_argument('data_file')\n args = parser.parse_args()\n\n with open(args.data_file) as f, timing():\n compute(f.read())\n\n return 0\n\n\nif __name__ == '__main__':\n exit(main())\n","repo_name":"anthonywritescode/aoc2019","sub_path":"day08/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"33"} +{"seq_id":"28721908112","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.core.validators import MaxValueValidator\n\n# for ratings\nfrom django.db.models import Avg\nfrom django.db.models.signals import post_save, post_delete\nfrom django.dispatch import receiver\n\n\n# Create your models here.\nclass RoyalHotelModel(models.Model):\n name = models.CharField(max_length=50)\n address = models.TextField(max_length=60)\n description = models.TextField(max_length=200)\n photos = models.ImageField(upload_to=\"static/photos/\", null=True, blank=True)\n reviews = models.ManyToManyField(User, through=\"User_Reviews\")\n cost_per_day = models.DecimalField(\n max_digits=10, decimal_places=2, null=True, default=500\n )\n average_rating = models.IntegerField(default=0)\n\n class Meta:\n verbose_name_plural = \"Royal Hotel's\"\n\n def __str__(self) -> str:\n return self.name\n\n\nclass User_Reviews(models.Model):\n hotel = models.ForeignKey(RoyalHotelModel, on_delete=models.CASCADE)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n review_text = models.CharField(max_length=200)\n rating = models.IntegerField(validators=[MaxValueValidator(5)])\n\n class Meta:\n verbose_name_plural = \"Reviews\"\n unique_together = (\"hotel\", \"user\")\n\n\n# Define a signal handler to update average_rating when a review is saved or deleted\n@receiver(post_save, sender=User_Reviews)\n@receiver(post_delete, sender=User_Reviews)\ndef update_average_rating(sender, instance, **kwargs):\n hotel = instance.hotel\n average_rating = User_Reviews.objects.filter(hotel=hotel).aggregate(Avg(\"rating\"))[\n \"rating__avg\"\n ]\n hotel.average_rating = int(average_rating) or 0\n hotel.save()\n","repo_name":"Obaidur1/royal-hotels","sub_path":"home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"25222992733","text":"# Programming 2 \n# Jonah Labeda 2B.\n\n# The Hangman List that draws the hang man when guesses are wrong\n\nfrom random import randint\nHANGMAN = [\n\"\"\"\n ------\n | |\n |\n |\n |\n |\n |\n |\n |\n----------\n\"\"\",\n\"\"\"\n ------\n | |\n | O\n |\n |\n |\n |\n |\n |\n----------\n\"\"\",\n\"\"\"\n ------\n | |\n | O\n | -+-\n | \n | \n | \n | \n | \n----------\n\"\"\",\n\"\"\"\n ------\n | |\n | O\n | /-+-\n | \n | \n | \n | \n | \n----------\n\"\"\",\n\"\"\"\n ------\n | |\n | O\n | /-+-/\n | \n | \n | \n | \n | \n----------\n\"\"\",\n\"\"\"\n ------\n | |\n | O\n | /-+-/\n | |\n | \n | \n | \n | \n----------\n\"\"\",\n\"\"\"\n ------\n | |\n | O\n | /-+-/\n | |\n | |\n | | \n | | \n | \n----------\n\"\"\",\n\"\"\"\n ------\n | |\n | O\n | /-+-/\n | |\n | |\n | | |\n | | |\n | \n----------\n\"\"\"]\n\nMAX_WRONG = len(HANGMAN) - 1\nWORDS = [\"PYTHON\", \"PROGRAMMING\", \"GUESS\", \"CODE\", \"COMPILE\", \"BUG\", \"KITTEN\", \"RISE\", \"OF\", \"KINGDOMS\", \"RISEOFKINGDOMS\", \"AMOGUS\", \"CAN\", \"MOM\", \"DAD\", \"MILK\"] #words to guess -- enter your own words here (10)\nsomething = randint(0,len(WORDS)-1)\n# initialize variables\n# the word to be guessed\nword = WORDS[something] # replace this to pick a random word from the list.\nso_far = [\"-\"] * len(word) # one dash for each letter in word to be guessed\nwrong = 0 # number of wrong guesses player has made\nused = [] # letters already guessed\nword = list(word) # turns chosen word into a list\nlength = len(word)\n#print(word)\nprint(\"Welcome to Hangman. Good luck!\") #opening statement\nprint(\"HINT: The word is\", \"_\"*length, \"letters long.\") # clues user to word length \nprint(HANGMAN[wrong])\n\n\n\nwhile wrong < MAX_WRONG and so_far != word:\n guess = input(\"\\n\\nEnter your guess: \") #tell user to guess a word\n guess = guess.upper()\n if len(guess) == 1:\n used += guess\n used.sort()\n for i in range(len(word)):\n if guess == word[i]:\n so_far.pop(i)\n so_far.insert(i, guess)\n \n # continue to ask the user for the guess if the guess is in the used list.\n \n # add the guess onto the used letter list. \n guesslist = []\n finalWord = \"\"\n if len(guess) != 1:\n for i in guess:\n guesslist += i\n if guesslist == word:\n so_far = word\n print(\"You got it!! :)\")\n print(\"The word was: \",*so_far, sep=\"\")\n if len(guess) == 1:\n for i in range(len(so_far)):\n if so_far == word:\n print(\"You got it!! :)\")\n print(\"The word was: \",*so_far, sep = \"\")\n break\n if so_far == word:\n break\n # check to see if the guess is in the word, if so then go through the list and \n #if so_far == word:\n #break\n # replace each occurence of the letter in the so_far list. \n if guess not in word:\n wrong += 1\n \n if wrong == 7:\n print(\"YOU LOSE!!! (^-° )\")\n print(\"The word was: \",*word, sep = \"\")\n print(HANGMAN[wrong])\n break\n print(HANGMAN[wrong])\n\n \n\n\n\n\n\n \n \n # otherwise: Tell the user the letter isn't in the word, increase number wrong, display the new HANGMAN\n \n print(\"\\nYou've used the following letters:\\n\", *used, sep = \" \")\n print(\"\\nSo far, the word is:\\n\", *so_far, sep = \" \") \n\n# after the loop is over:\n# if they didn't guess it tell them what it was, otherwise tell them you guessed it. \n\n\n\n","repo_name":"cillybro/hangman","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"1519643481","text":"import torch\nfrom torch import nn\n\n# Default constants\n#LEARNING_RATE = 1e-2\n\nEVAL_FREQ = 10\nBATCH_SIZE = 32\n\n# %reload_ext autoreload\n# %autoreload 2\n\nnum_groups = 4 \n\nclass MLP_Model(nn.Module):\n def __init__(self, inputSize, numClasses):\n super(MLP_Model, self).__init__()\n \n self.fltn = nn.Flatten()\n self.fc1 = nn.Linear(inputSize, 128)\n # self.bc1 = nn.BatchNorm1d(128)\n self.bc1 = nn.GroupNorm(num_groups, 128)\n self.relu1 = nn.ReLU(inplace=True)\n\n\n self.fc2 = nn.Linear(128, 128)\n self.bc2 = nn.GroupNorm(num_groups, 128)\n self.relu2 = nn.ReLU(inplace=True)\n\n self.fc21 = nn.Linear(128, 128)\n self.bc21 = nn.GroupNorm(num_groups, 128)\n self.relu21 = nn.ReLU(inplace=True)\n\n\n self.fc3 = nn.Linear(128, 64)\n self.bc3 = nn.GroupNorm(num_groups, 64)\n self.relu3 = nn.ReLU(inplace=True)\n\n \n self.fc4 = nn.Linear(64, 64)\n self.bc4 = nn.GroupNorm(num_groups, 64)\n self.relu4 = nn.ReLU(inplace=True)\n\n\n self.fc5 = nn.Linear(64, numClasses)\n\n\n self.initialize_weights()\n\n self.relu = nn.ReLU(inplace=True)\n self.dropout = nn.Dropout(p=0.1)\n self.logsm = nn.LogSoftmax(dim=1)\n \n def forward(self, x):\n \n # out = self.fc1(self.fltn(x))\n out = self.fc1(x)\n assert not torch.isnan(out).any()\n out = self.bc1(out)\n out = self.relu1(out)\n out = self.dropout(out)\n \n out2 = self.fc2(out)\n assert not torch.isnan(out2).any()\n out = self.bc2(out2)\n out = self.relu2(out)\n out = self.dropout(out)\n \n \n out21 = self.fc21(out)\n assert not torch.isnan(out21).any()\n out = self.bc21(out21)\n out = self.relu21(out)\n out = self.dropout(out)\n\n \n out3 = self.fc3(out)\n assert not torch.isnan(out3).any()\n out3 = self.bc3(out3)\n out = self.relu3(out3)\n out = self.dropout(out)\n \n \n out = self.fc4(out)\n out = self.bc4(out)\n out = self.relu4(out)\n out4 = self.dropout(out)\n assert not torch.isnan(out4).any()\n \n out5 = self.fc5(out4)\n assert not torch.isnan(out5).any()\n \n # out = self.logsm(out)\n \n return out\n \n \n def initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Linear):\n nn.init.kaiming_uniform_(m.weight, nonlinearity='relu')\n\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)","repo_name":"klarteno/IDS_Project","sub_path":"net_models_made/mlp_model.py","file_name":"mlp_model.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"44914301142","text":"from django.contrib.auth.models import User\nfrom rest_framework import serializers\n\n\n\n\nclass PostSerializer(serializers.ModelSerializer):\n tracks = serializers.SlugRelatedField(\n many=True,\n read_only=True,\n slug_field='username'\n )\n\n class Meta:\n model = User\n fields = ['id', 'username']","repo_name":"nathaniel-prog/carpool","sub_path":"serials.py","file_name":"serials.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"34734523481","text":"from DecExp import DecExp\nfrom param import args\nimport numpy as np\nimport sys\nimport os\n\nIMG_NUM=args.img_num\nargs.train='train'\nargs.valid='val'\nargs.batch_size=16\nargs.epochs=1 #number of successive epochs for each image batch\nargs.tiny=True\nargs.dotrain=False\ndir='./snap/train_full_12h_1_1_1/'\nargs.dotrain=True\nargs.llayers=1\nargs.xlayers=1\nargs.rlayers=1\n\nfor modelnb in range(0,10):\n print(\"Evaluating model n°\", modelnb+1)\n args.load=dir+'epoch_'+str(modelnb+1)\n decexp = DecExp()\n\n #Perform evaluation only\n train_accuracy, avg_train_loss=decexp.evaluate(decexp.trainset)\n val_accuracy, avg_val_loss=decexp.evaluate(decexp.validset)\n print(\"Train accuracy\", train_accuracy*100., \"Avg loss: \", avg_train_loss)\n print(\"Val accuracy\", val_accuracy*100., \"Avg loss: \", avg_val_loss)\n with open(dir + '/acc_loss_'+dir[18:-1]+'.log', 'a') as f:\n f.write(\"\\n\\nModel: \")\n f.write(args.load)\n f.write(\"\\nTolerance: 0.5\")\n f.write(\"\\nNumber of needed bits: 25\")\n f.write(\"\\nHeads: 12\")\n f.write(\"\\nTrain accuracy: \")\n f.write(str(train_accuracy*100.))\n f.write(\" Avg loss: \")\n f.write(str(avg_train_loss))\n f.write(\"\\nVal accuracy: \")\n f.write(str(val_accuracy*100.))\n f.write(\" Avg loss: \")\n f.write(str(avg_val_loss))\n f.flush()","repo_name":"TiezWan/Decision-Explanation-BDDOIA-LXMERT","sub_path":"src_DecExp/DecExp_eval.py","file_name":"DecExp_eval.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"32655196425","text":"\"\"\"\nsum >= 8\n1 3 5 3 8 1 5 3 1 8 1 4\n\n1 3 5 size = 3\n 3 5 size = 2\n 5 3 size = 2\n 3 8 size = 2\n 8 size = 1 return\n\"\"\"\n\nimport math\n\ndef smallestSub(li, sum):\n n = len(li)\n\n smallestSize = math.inf\n for i in range(n):\n currentSum = 0\n for j in range(i, n):\n currentSum += li[j]\n if(currentSum >= sum):\n smallestSize = min(smallestSize, j - i + 1)\n break\n if(smallestSize == 1):\n return 1\n return smallestSize\n\nli = [1, 3, 5, 3, 8, 1, 5, 3, 1, 8, 1, 4]\nk = 8\n\nres = smallestSub(li, k)\nprint(res)","repo_name":"mdpabel/Data-structure-and-algorithm","sub_path":"01. Sliding Window/01. (bruteforce)_Smallest_subarray.py","file_name":"01. (bruteforce)_Smallest_subarray.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"16054606646","text":"import os\nimport sys\nimport django\nimport csv\nfrom collections import defaultdict\nfrom django.core.exceptions import ObjectDoesNotExist\n\nhomepath = os.environ['HOMEPATH']\ngenesite = os.path.join(homepath,'Desktop/AWD Development Area/advanced_web_dev/ZZZ_midterm/genesite')\n\nsys.path.append(genesite)\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'genesite.settings')\n\ndjango.setup() \nfrom genedata.models import Organism, Protein\n\ndata_file = os.path.join(genesite,'csvfiles/assignment_data_set.csv')\n\n# initialise the dictionary for organisms as a default dictionary\nproteins = defaultdict(list)\nlast_protein_id = 0\n\n# open the CSV file(s) and read the data into dictionaries \nwith open(data_file) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n #header = csv_reader.__next__()\n for row in csv_reader:\n if row[0] != last_protein_id :\n proteins[row[0]] = row[1]\n #print(row[0],proteins[row[0]])\n last_protein_id = row[0]\n\n# set the DB object(s), retrieve the data from the dictionary and save into the DB object\nprint('LOADING PROTEINS WITH TAX')\n\nfor item in proteins.items():\n # get the protein id and taxa_id data\n protein_id = item[0]\n taxa_id = item[1]\n\n #print(protein_id, taxa_id)\n \n # Look up the value in the of the taxa_id in the organism table\n try:\n protein = Protein.objects.get(protein_id=protein_id)\n except ObjectDoesNotExist:\n protein = None\n try:\n organism = Organism.objects.get(taxa_id=taxa_id)\n except ObjectDoesNotExist:\n organism = None\n\n # Set the protein.tax_id field only if it exists\n if protein != None:\n protein.taxonomy = organism\n protein.save()\n\nprint('LOADING PROTEINS WITH TAX COMPLETE')\n","repo_name":"wesleypersad/AWD-MT-Project","sub_path":"scripts/step5_pop_protein_tax.py","file_name":"step5_pop_protein_tax.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"37582146721","text":"# -*- coding: utf-8 -*-\nimport os\nfrom functools import cmp_to_key\n\nimport exceptions\nfrom validators import TableSchemaValidator\nfrom notifications import EmailNotification\nfrom errors import ErrorBag, ErrorsCache\n\nimport yaml\nimport toml\nimport giturlparse\nfrom semver import VersionInfo, cmp as SemverCmp\nfrom git import Repo as GitRepo\nfrom git.exc import GitError\n\n\nclass Metadata(object):\n BASE_DOMAIN = \"https://schema-datagouv.antoine-augusti.fr\"\n\n def __init__(self):\n super(Metadata, self).__init__()\n self.data = {}\n\n def add(self, metadata):\n slug = metadata[\"slug\"]\n if slug in self.data:\n self.data[slug][\"versions\"].append(metadata[\"version\"])\n self.data[slug][\"has_changelog\"] = metadata[\"has_changelog\"]\n else:\n special_keys = [\"version\", \"slug\"]\n self.data[slug] = {\n k: v for k, v in metadata.items() if k not in special_keys\n }\n self.data[slug][\"versions\"] = [metadata[\"version\"]]\n\n def schema_url(self, slug):\n details = self.get()[slug]\n if details[\"type\"] not in Repo.SCHEMA_TYPES:\n raise NotImplementedError\n return {\n \"tableschema\": \"%s/schemas/%s/latest/%s\"\n % (self.BASE_DOMAIN, slug, TableSchemaValidator.SCHEMA_FILENAME)\n }[details[\"type\"]]\n\n def get(self):\n for slug, data in self.data.items():\n sorted_versions = sorted(data[\"versions\"], key=cmp_to_key(SemverCmp))\n self.data[slug][\"latest_version\"] = sorted_versions[-1]\n return self.data\n\n def save_schemas(self):\n # Save in YAML\n with open(\"data/schemas.yml\", \"w\") as f:\n yaml.dump(self.get(), f, allow_unicode=True)\n\n # Save in TOML\n with open(\"data/schemas.toml\", \"w\") as f:\n toml.dump(self.generate_toml(), f)\n\n def generate_toml(self):\n toml_data = {}\n for slug, details in self.data.items():\n toml_data[slug] = {\n \"title\": details[\"title\"],\n \"description\": details[\"description\"],\n \"version\": details[\"latest_version\"],\n \"doc_url\": \"https://schema.data.gouv.fr/%s/latest.html\" % slug,\n \"schema\": self.schema_url(slug),\n }\n return toml_data\n\n\nclass Repo(object):\n SCHEMA_TYPES = [\"tableschema\"]\n\n def __init__(self, git_url, email, schema_type):\n super(Repo, self).__init__()\n parsed_git = giturlparse.parse(git_url)\n self.git_url = git_url\n self.owner = parsed_git.owner\n self.name = parsed_git.name\n self.email = email\n self.git_repo = None\n self.current_tag = None\n self.cache_latest_valid_tag = None\n if schema_type not in self.SCHEMA_TYPES:\n raise exceptions.InvalidSchemaTypeException(\n self,\n \"`%s` is not a supported schema type. Supported: %s\"\n % (schema_type, \",\".join(self.SCHEMA_TYPES)),\n )\n self.schema_type = schema_type\n\n @property\n def clone_dir(self):\n return os.path.join(self.repo_dir, self.owner, self.name)\n\n @property\n def repo_dir(self):\n current_dir = os.path.dirname(os.path.realpath(__file__))\n return os.path.join(current_dir, \"repos\")\n\n @property\n def slug(self):\n return \"%s/%s\" % (self.owner, self.name)\n\n @property\n def current_version(self):\n return str(self.current_tag)\n\n def validator(self):\n if self.schema_type == \"tableschema\":\n return TableSchemaValidator(self)\n raise NotImplementedError\n\n def clone_or_pull(self):\n try:\n if os.path.isdir(self.clone_dir):\n git_repo = GitRepo(self.clone_dir)\n git_repo.remotes.origin.pull(\"refs/heads/master:refs/heads/origin\")\n else:\n git_repo = GitRepo.clone_from(self.git_url, self.clone_dir)\n except GitError:\n raise exceptions.GitException(self, \"Cannot clone or pull Git repository\")\n\n self.git_repo = git_repo\n\n def tags(self):\n if self.git_repo is None or len(self.git_repo.tags) == 0:\n raise exceptions.NoTagsException(self, \"Cannot found tags\")\n versions = [self.parse_version(t.name) for t in self.git_repo.tags]\n return sorted(versions, key=cmp_to_key(SemverCmp))\n\n def latest_valid_tag(self):\n if self.cache_latest_valid_tag is not None:\n return self.cache_latest_valid_tag\n previous_tag = self.current_tag\n for tag in self.tags():\n try:\n self.checkout_tag(tag)\n self.validator().validate()\n self.cache_latest_valid_tag = tag\n except exceptions.ValidationException:\n continue\n self.checkout_tag(previous_tag)\n return self.cache_latest_valid_tag\n\n def checkout_tag(self, tag):\n try:\n self.git_repo.git.checkout(self.normalize_tag(tag))\n except GitError:\n raise exceptions.GitException(self, \"Cannot checkout tag %s\" % tag)\n self.current_tag = tag\n\n def normalize_tag(self, tag):\n tag_name = str(tag)\n if str(tag) not in list(map(str, self.git_repo.tags)):\n tag_name = \"v\" + str(tag)\n return tag_name\n\n def parse_version(self, version):\n try:\n return VersionInfo.parse(version.replace(\"v\", \"\"))\n except ValueError:\n raise exceptions.InvalidVersionException(\n self, \"Version was invalid: %s\" % version\n )\n\n\nerrors = ErrorBag()\n\nwith open(\"repertoires.yml\", \"r\") as f:\n config = yaml.safe_load(f)\n\nmetadata = Metadata()\nfor repertoire_slug, conf in config.items():\n try:\n repo = Repo(conf[\"url\"], conf[\"email\"], conf[\"type\"])\n repo.clone_or_pull()\n tags = repo.tags()\n except exceptions.ValidationException as e:\n errors.add(e)\n continue\n\n for tag in tags:\n try:\n repo.checkout_tag(tag)\n validator = repo.validator()\n validator.validate()\n validator.extract()\n metadata.add(validator.metadata())\n except exceptions.ValidationException as e:\n errors.add(e)\n\nmetadata.save_schemas()\n\nprint(\"### Errors by slug ###\\n\")\n\nfor slug, details in errors.errors_by_slug.items():\n messages = \"\\n\".join([\" - \" + repr(e) for e in details])\n print(\"%s:\\n%s\" % (slug, messages))\n\nprint(\"\\n\\n### Errors by email ###\\n\")\nfor email, details in errors.errors_by_email.items():\n messages = \"\\n\".join([\"- \" + repr(e) for e in details])\n print(\"%s:\\n%s\" % (email, messages))\n\nerrors_cache = ErrorsCache()\nfor email, details in errors.errors_by_email.items():\n errors_cache.add_error(email, details)\n if len(details) > 0 and errors_cache.should_send_notification(email, details):\n EmailNotification(email, details).send()\n\nerrors_cache.save_cache()\n","repo_name":"AntoineAugusti/schema-agg","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"3360959335","text":"from .entrez_base import Gene2AccessionParser\n\n__metadata__ = {\n '__collection__': 'entrez_accession',\n}\n\n\ndef load_genedoc(self):\n parser = Gene2AccessionParser()\n parser.set_all_species()\n gene2acc = parser.load()\n return gene2acc\n\n\ndef get_mapping(self):\n mapping = {\n \"accession\": {\n \"dynamic\": False,\n #\"path\": \"just_name\", #make both fields, accession.rna and rna, work\n \"properties\": {\n \"genomic\": {\n \"type\": \"string\",\n\t\t\t\"index\": \"no\",\n \"include_in_all\": False,\n },\n \"rna\": {\n \"type\": \"string\",\n \"analyzer\": \"refseq_analyzer\",\n },\n 'protein': {\n \"type\": \"string\",\n \"analyzer\": \"refseq_analyzer\",\n #\"index_name\": \"accession\",\n },\n 'translation': {\n \"type\": \"object\",\n\t\t\t\"enabled\": False,\n \"include_in_all\": False,\n },\n }\n }\n }\n return mapping\n","repo_name":"karawallace/mygene","sub_path":"src/dataload/sources/entrez/entrez_accession.py","file_name":"entrez_accession.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"73098760093","text":"import boto3\nimport json\nimport os\n\n\nregion = os.environ[\"region\"]\nqueue = os.environ[\"queue\"]\n\n\ndef handler(event, context):\n body = json.loads(event[\"body\"])\n messages = body.get(\"messages\")\n\n sqs = boto3.client(\"sqs\", region_name=region)\n\n responses = []\n for message in messages:\n payload = {\"message\": message}\n response = sqs.send_message(\n MessageBody=json.dumps(payload),\n QueueUrl=queue\n )\n responses.append({\"payload\": payload, \"response\": response})\n\n return {\"statusCode\": 200, \"body\": json.dumps(responses)}\n","repo_name":"emersonoliveiradev/terraform-studies","sub_path":"splitter/lambdas/split/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"37517312249","text":"import os\n\nimport pprint\nimport pandas as pd\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport requests\n\nfrom mi_graph import triple_generation\nfrom rdf_parser.rdf_parser import RdfParser\nfrom resources.error import error\nfrom resources.knowledgegraph_info_container import KnowledgeGraphInfo\n\n\nclass KnowledgeGraph:\n \"\"\"\n Generates triples from the text which has been natural language processed,\n and the metadata extracted from a Content object.\n Triples are saved to the database(.csv) file provided to the object during instantiation.\n \"\"\"\n knowledge_graph_triples = []\n\n def __init__(self):\n self.rdf_parser = RdfParser()\n self.knowledge_graph_triples = []\n\n def generate_triples(self, kg_info: KnowledgeGraphInfo):\n \"\"\"\n Generates knox_triples (subj, rel, obj) from the text which has been natural language processed\n and the metadata extracted from a Content object\n \"\"\"\n\n self.knowledge_graph_triples.extend(\n triple_generation.generate_triples_for_metadata(kg_info.manual))\n self.knowledge_graph_triples.extend(\n triple_generation.generate_triples_for_sentences(kg_info.sentences))\n\n def show_graph(self):\n \"\"\"\n Opens a new window with the graph plotted within\n \"\"\"\n graph = nx.from_pandas_edgelist(\n self.__create_branches_from_triples(), 'subject', 'object', edge_attr=True, create_using=nx.MultiDiGraph())\n\n plt.figure(figsize=(12, 12))\n\n pos = nx.spring_layout(graph)\n nx.draw(graph, pos, edge_color='black',\n node_color='skyblue', alpha=0.9, with_labels=True)\n nx.draw_networkx_edge_labels(graph, pos=pos)\n\n plt.show()\n\n def __create_branches_from_triples(self):\n\n data_frame = pd.DataFrame(columns=[\"subject\", \"relation\", \"object\"])\n for triple in self.knowledge_graph_triples:\n try:\n data_frame = data_frame.append(\n pd.DataFrame(\n {'subject': [triple.subj_()], 'relation': [triple.rel_()], 'object': [triple.obj_()]}))\n except KeyError as error:\n print(error)\n\n return data_frame\n\n def pretty_print_graph(self):\n for triple in self.knowledge_graph_triples:\n pprint.pprint(triple.parse())\n\n def save_to_csv(self, csv_file_path):\n triple_dataframe = self.__create_branches_from_triples()\n\n if not os.path.exists(csv_file_path):\n triple_dataframe.to_csv(csv_file_path, mode='a', index=False)\n elif os.stat(csv_file_path).st_size == 0:\n triple_dataframe.to_csv(csv_file_path, mode='a', index=False)\n else:\n triple_dataframe.to_csv(csv_file_path, mode='a', index=False, header=None)\n\n def save_to_database(self):\n data = self.__generate_data()\n\n self.__update_triples(data)\n self.__commit_triples()\n\n def __update_triples(self, data):\n # Remember: ssh username@student.aau.dk@knox-node02.srv.aau.dk -L 8080:localhost:8080\n update_url = 'http://127.0.0.1:8080/update/'\n\n update_header: dict = {'content-type': 'application/json; charset=utf-16'}\n response = requests.post(update_url, data=data.encode('utf-16'), headers=update_header)\n self.__print_response(response)\n\n def __commit_triples(self):\n commit_url = 'http://127.0.0.1:8080/commit/'\n\n response = requests.post(commit_url)\n self.__print_response(response)\n\n def __generate_data(self):\n data = \"\"\n for triple in self.knowledge_graph_triples:\n try:\n data += repr(triple) + \" .\\n\"\n except KeyError as err:\n error(\"The key is wrong\", err)\n return data\n\n @staticmethod\n def __print_response(response):\n print(\"Status code: \", response.status_code)\n print(response.text)\n","repo_name":"AndersSpringborg/knox-d","sub_path":"mi_graph/knowledge_graph.py","file_name":"knowledge_graph.py","file_ext":"py","file_size_in_byte":3927,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"34757977594","text":"##---------------------------------------------\n## PROJECT: Dutil FILE NAME: Dill\n## USER: sasha PRODUCT: PyCharm\n##---------------------------------------------\n## 5/19/17:10:15 AM\n##---------------------------------------------\n\nimport dill\n\n\nclass MSGpack(object):\n\t\"\"\"\n\tWe want to be able to ship Python object to different type of infrastructure -\n\theterogeneous programming - byte streams\n\t\"\"\"\n\n\tdef __init__(self):\n\t\t##print(\"License {}\".format(dill.license()))\n\t\tpass\n\n\t@staticmethod\n\tdef pack(obj):\n\t\t\"Pack it to bytes as object\"\n\t\t_f = dill.dumps(obj)\n\t\treturn _f\n\n\n\t@staticmethod\n\tdef unpack(bf):\n\t\t\"Unpack it to dill object and get back original object from packed dill\"\n\t\tobj = dill.loads(bf)\n\t\treturn obj\n\n## for test purposes\nclass Foo(object):\n\tdef bar(self, x):\n\t\treturn x + self.y\n\n\ty = 1\n\n\ndef main():\n\tf = Foo()\n\td = MSGpack()\n\tbf = d.pack(f)\n\tnewObj = d.unpack(bf)\n\tprint(\"unpacked {}\".format(newObj))\n\tprint(newObj.y)\n\n\tfrom TD.util.PSUtil import PSInterrogate\n\tnstat = PSInterrogate()\n\tres = nstat.run()\n\tbres = d.pack(res)\n\tnewObj = d.unpack(bres)\n\tprint(\"unpacked {}\".format(newObj))\n\tprint(newObj[0]._fields)\n\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"catchmonster/cat5test","sub_path":"mobiusr/util/Dill.py","file_name":"Dill.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"41989865215","text":"from lxml import etree as et\n\nclass SOLUTION:\n\n def __init__(self, timetable = {}):\n\n self.timetable = timetable\n self.objective = 0\n self.infeasability = 0\n\n def export(self, path):\n root = et.Element(\"Solution\")\n meta_element = et.SubElement(root,\"MetaData\")\n games_element = et.SubElement(root,\"Games\")\n for t in self.timetable:\n for game in self.timetable[t]:\n g_element = et.SubElement(games_element,\"ScheduledMatch\")\n g_element.attrib[\"home\"] = str(game[0])\n g_element.attrib[\"away\"] = str(game[1])\n g_element.attrib[\"slot\"] = str(t)\n \n root.getroottree().write(path, xml_declaration=True, encoding=\"UTF-8\")\n\n def import_xml(self, path):\n root = et.parse(path)\n for game in root.findall(\".//Games/ScheduledMatch\"):\n i = int(game.get(\"home\"))\n j = int(game.get(\"away\"))\n t = int(game.get(\"slot\"))\n self.timetable.setdefault(t,[]).append((i,j))\n\n ","repo_name":"AminosDz/ITC2021","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"15908141692","text":"import discord, datetime, time\n\nfrom time import sleep\nfrom discord import Embed\nfrom discord.ext import commands\nfrom discord.ext.commands.cooldowns import BucketType\n\nts = time.time()\nst = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n\nclass Changelog(commands.Cog):\n\tdef __init__(self, client):\n\t\tself.client = client\n\n\t@commands.command(aliases = [\"change\", \"chlog\"])\n\t@commands.cooldown(1, 10, commands.BucketType.user)\n\tasync def changelog(self, ctx):\n\n\t\tasync with ctx.channel.typing():\n\t\t\n\t\t\tchangelogembed = discord.Embed(\n\t\t\t\ttitle=\"Changelog\",\n\t\t\t\tcolour=discord.Color.green(),\n\t\t\t\ttimestamp=datetime.datetime.now()\n\t\t\t\t)\n\n\t\t\tchangelogembed.add_field(name=\"[!] NEW FEATURE!\", value=\"Bot is now 24/7!\", inline=False)\n\t\t\tchangelogembed.add_field(name=\"[+] Added a command\", value=\"Added `mute` and `unmute` :')\", inline=False)\n\t\t\tchangelogembed.add_field(name=\"[+] Added a command\", value=\"Added corona stuff\", inline=False)\n\t\t\tchangelogembed.add_field(name=\"[+] Added a command\", value=\"Added `nuke` :3\", inline=False)\n\t\t\tchangelogembed.add_field(name='[!] Improved a command', value='Improved help (,help ', inline=False)\n\t\t\tchangelogembed.add_field(name='[+] Added a command', value='Added `bug`, (Report and bug)', inline=False)\n\t\t\tchangelogembed.add_field(name='[+] Added a command', value='Added `nick` and `unnick` :>', inline=False)\n\n\t\t\tawait ctx.send(ctx.author.mention, embed=changelogembed)\n\n\t@changelog.error\n\tasync def changelog_error(self, ctx, error):\n\t\tif isinstance(error, commands.CommandOnCooldown):\n\t\t\tawait ctx.send(' {} Cooldown activated! Please try again in {:.2}s'.format(ctx.author.mention, error.retry_after))\n\n\t\telse:\n\t\t\tawait ctx.send(error)\n\t\t\tprint(error)\n\ndef setup(client):\n\tclient.add_cog(Changelog(client))","repo_name":"siddhant-deepsource/Uruha-Rushia.-","sub_path":"cogs/changelog.py","file_name":"changelog.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"842621842","text":"import os\nimport sys\nfrom datetime import datetime\n\nif 'SUMO_HOME' in os.environ:\n tools = os.path.join(os.environ['SUMO_HOME'], 'tools')\n sys.path.append(tools)\nelse:\n sys.exit(\"Please declare the environment variable 'SUMO_HOME'\")\n\nimport traci\nfrom sumo_env import SumoEnvironment\nfrom agent import Agent\nfrom epsilon_greedy import EpsilonGreedy\nfrom configparser import SafeConfigParser\nfrom util import save_csv, plot\n\nif __name__ == '__main__':\n\n # load default config\n rl_params = SafeConfigParser()\n rl_params.read('rl.ini')\n simulation_step = int(rl_params.get('DEFAULT', 'num_simulations'))\n\n # define output csv file\n experiment_time = str(datetime.now()).split('.')[0]\n out_csv = 'outputs/{}_{}_{}Agent'.format(experiment_time,\n rl_params.get('DEFAULT', 'signal'),\n rl_params.get('DEFAULT', 'rl_agent')\n )\n\n # init sumo environment\n signal_type = rl_params.get('DEFAULT', 'signal')\n\n #Get the signal phases for the traffic network\n if signal_type == 'one_way':\n signal_phase = [traci.trafficlight.Phase(42000,-1,1, \"GGrr\"), \n traci.trafficlight.Phase(2000,-1,1, \"yyrr\"),\n traci.trafficlight.Phase(42000,-1,1, \"rrGG\"), \n traci.trafficlight.Phase(2000,-1,1, \"rryy\")]\n \n elif signal_type == 'two_way':\n signal_phase = [traci.trafficlight.Phase(32000,-1,1, \"GGrrrrGGrrrr\"),\n traci.trafficlight.Phase(2000,-1,1, \"yyrrrryyrrrr\"),\n traci.trafficlight.Phase(32000,-1,1, \"rrGrrrrrGrrr\"),\n traci.trafficlight.Phase(2000,-1,1, \"rryrrrrryrrr\"),\n traci.trafficlight.Phase(32000,-1,1, \"rrrGGrrrrGGr\"),\n traci.trafficlight.Phase(2000,-1,1, \"rrryyrrrryyr\"),\n traci.trafficlight.Phase(32000,-1,1, \"rrrrrGrrrrrG\"),\n traci.trafficlight.Phase(2000,-1,1, \"rrrrryrrrrry\")]\n\n #Initialize SUMO traffic simulation environment and get initial states\n rl_env = SumoEnvironment(rl_params,\n out_csv_name=out_csv,\n phases=signal_phase)\n initial_states = rl_env.sumo_init()\n\n #Initialize the RL agent\n rl_agent = rl_params.get('DEFAULT', 'rl_agent')\n agent = Agent(starting_state=rl_env.encode_states(initial_states),\n action_space=rl_env.action_space,\n alpha=float(rl_params.get('DEFAULT', 'alpha')),\n gamma=float(rl_params.get('DEFAULT', 'gamma')),\n exploration_strategy=EpsilonGreedy(initial_epsilon=float(rl_params.get('DEFAULT', 'epsilon')),\n min_epsilon=float(rl_params.get('DEFAULT', 'minimum_epsilon')),\n decay=float(rl_params.get('DEFAULT', 'decay')))\n )\n \n #Start simulation\n step = 0 \n while step < simulation_step:\n # Take a step\n action = agent.act(step)\n step += 1\n # Compute next_state and reward\n next_state, reward = rl_env.step(actions=action)\n if rl_agent == 'ql':\n # Apply Q-Learning\n agent.learn_q(new_state=rl_env.encode_states(next_state), reward=reward)\n elif rl_agent == 'sarsa':\n # Apply sarsa learning\n agent.learn_sarsa(new_state=rl_env.encode_states(next_state), reward=reward)\n elif rl_agent == 'dql':\n # Apply dql learning\n agent.learn_dql(new_state=rl_env.encode_states(next_state), reward=reward)\n\n # Save and plot the traffic metrics:(step count, stopped vehicles, total wait time)\n save_csv(rl_env.metrics, out_csv)\n plot(out_csv)\n \n rl_env.close()\n\n","repo_name":"manogna-s/traffic_rlagent","sub_path":"rl_control.py","file_name":"rl_control.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"10995184968","text":"class ProgrammingLanguage:\n \"\"\"Information of programming language\"\"\"\n\n def __init__(self, field, typing, reflection, year):\n \"\"\" constructor in ProgrammingLanguage oriented concepts\"\"\"\n self.field = field\n self.typing = typing\n self.reflection = reflection\n self.year = year\n\n def is_dynamic(self):\n \"\"\"Determine is the language dynamic\"\"\"\n return self.typing == \"Dynamic\"\n\n def __str__(self):\n \"\"\"Return ProgrammingLanguage in string\"\"\"\n return f\"{self.field}, {self.typing} Typing, Reflection={self.reflection}, First appeared in {self.year}\"\n\n\ndef test_program():\n \"\"\"Test the function of ProgrammingLanguage class.\"\"\"\n ruby = ProgrammingLanguage(\"Ruby\", \"Dynamic\", True, 1995)\n python = ProgrammingLanguage(\"Python\", \"Dynamic\", True, 1991)\n visual_basic = ProgrammingLanguage(\"Visual Basic\", \"Static\", False, 1991)\n languages = [ruby, python, visual_basic]\n print(\"The dynamically typed languages are:\")\n for language in languages:\n if language.is_dynamic():\n print(language.field)\n\n\nif __name__ == \"__main__\":\n test_program()\n","repo_name":"goodysq/1404","sub_path":"prac_06/programming_language.py","file_name":"programming_language.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"1206304559","text":"from .base import JsonObject, JsonObjectDataMapper\n\nclass EncounterObject(JsonObject):\n _version = '1.0'\n _pathPrefix = \"encounter\"\n _defaultConfig = {\n 'campaign_id': None,\n 'size': 0,\n 'monster_ids': [],\n 'loot': [],\n }\n _fieldTypes = {\n 'id': int,\n 'user_id': int,\n 'campaign_id': int,\n 'size': int,\n 'monster_ids': {\n '*': int,\n },\n 'challenge_rating': float,\n 'challenge_rating_sum': float,\n 'challenge_rating_precise': float,\n 'challenge_rating_precise_sum': float,\n 'challenge_modified': float,\n 'modifier': {\n '*': float\n },\n 'xp': int,\n 'xp_modified': int,\n 'xp_rating_sum': int,\n 'xp_rating': float,\n 'loot': {\n 'count': int\n }\n }\n\n def __init__(self, config={}):\n self._party = None\n self._monsters = []\n self._encounter_modifiers = {\n \"party\": [\n {\"min\": 1, \"max\": 2, \"modifier\": 0.5},\n {\"min\": 3, \"max\": 5, \"modifier\": 0.0},\n {\"min\": 6, \"max\": 8, \"modifier\": -0.5}\n ],\n \"encounter\": [\n {\"min\": 1, \"max\": 1, \"modifier\": 1.0},\n {\"min\": 2, \"max\": 2, \"modifier\": 1.5},\n {\"min\": 3, \"max\": 6, \"modifier\": 2.0},\n {\"min\": 7, \"max\": 10, \"modifier\": 2.5},\n {\"min\": 11, \"max\": 14, \"modifier\": 3.0},\n {\"min\": 15, \"max\": 20, \"modifier\": 4.0},\n {\"min\": 21, \"max\": 30, \"modifier\": 5.0}\n ]\n }\n super(EncounterObject, self).__init__(config)\n\n def migrate(self, mapper):\n if not len(self.monster_ids or []):\n monster_ids = [\n monster.id\n for monster in mapper.monster.getByEncounterId(self.id)\n ]\n monster_ids = dict(\n (monster_id, monster_ids.count(monster_id))\n for monster_id in monster_ids\n )\n self.monster_ids = [\n {'id': monster_id, 'count': count}\n for monster_id, count in list(monster_ids.items())\n ]\n\n monsters = []\n for m in self.monster_ids:\n monster = mapper.monster.getById(m['id'])\n monster.migrate()\n monsters.append(monster)\n self.monsters = monsters\n\n super(EncounterObject, self).migrate()\n\n @property\n def party(self):\n return self._party\n\n @party.setter\n def party(self, party):\n self._party = party\n self.compute()\n\n @property\n def monsters(self):\n return self._monsters\n\n @monsters.setter\n def monsters(self, monsters):\n self._monsters = monsters\n self.compute()\n\n @property\n def countByMonsterId(self):\n return dict([\n (group['id'], group['count'])\n for group in self.monster_ids\n ])\n\n def modifierByPartySize(self, size):\n for data in self._encounter_modifiers['party']:\n if data['min'] <= size <= data['max']:\n return data['modifier']\n return 0.0\n\n def modifierByEncounterSize(self, size):\n for data in self._encounter_modifiers['encounter']:\n if data['min'] <= size <= data['max']:\n return data['modifier']\n return 1.0\n\n def compute(self):\n self.version = self._version\n\n self.modifierParty = 0.0\n if self.party is not None:\n self.modifierParty = self.modifierByPartySize(self._party.size)\n\n self.size = sum([\n monster['count']\n for monster in self.monster_ids\n ])\n self.modifierMonster = self.modifierByEncounterSize(self.size)\n\n self.challenge_rating_sum = 0.0\n self.challenge_rating_precise_sum = 0.0\n self.xp = 0\n self.xp_rating_sum = 0\n for m in self.monster_ids:\n monster = next((\n monster for monster in self.monsters\n if monster.id == m['id']\n ), None)\n self.xp += \\\n monster.xp * m['count']\n self.challenge_rating_sum += \\\n monster.challenge_rating * m['count']\n self.challenge_rating_precise_sum += \\\n monster.challenge_rating_precise * m['count']\n self.xp_rating_sum += \\\n monster.xp_rating * m['count']\n\n modifierMonster = self.modifierMonster\n\n self.challenge_rating = \\\n self.challenge_rating_sum * modifierMonster\n\n self.modifierTotal = \\\n modifierMonster + self.modifierParty\n self.challenge_modified = \\\n self.challenge_rating_sum * self.modifierTotal\n self.xp_modified = \\\n self.xp * self.modifierTotal\n self.challenge_rating_precise = \\\n self.challenge_rating_precise_sum * self.modifierTotal\n self.xp_rating = \\\n self.xp_rating_sum * modifierMonster\n\n\nclass EncounterMapper(JsonObjectDataMapper):\n obj = EncounterObject\n table = \"encounter\"\n fields = [\n 'name', 'user_id', 'campaign_id',\n 'size', 'challenge_rating', 'xp_rating', 'xp']\n join_tables = {\n 'encounter_monsters': ('id', 'encounter_id'),\n }\n\n def _read(self, dbrow):\n obj = super(EncounterMapper, self)._read(dbrow)\n if obj is None:\n return obj\n obj.monster_ids = self.getMonsterCounts(obj.id)\n return obj\n\n def getList(self, search=None):\n \"\"\"Returns a list of encounters matching the search parameter\"\"\"\n return self.getMultiple(\n \"`name` LIKE :search\",\n {\"search\": '%%%s%%' % search}\n )\n\n def getByDmUserId(self, user_id):\n \"\"\"Returns all encounters created by DM by user_id\"\"\"\n return self.getMultiple(\n \"`user_id` = :userId\",\n {\"userId\": user_id}\n )\n\n def getByCampaignId(self, campaign_id):\n \"\"\"Returns all encounters associated with campaign_id\"\"\"\n return self.getMultiple(\n \"`campaign_id` = :campaignId\",\n {\"campaignId\": campaign_id}\n )\n\n def getMonsterCounts(self, encounter_id):\n \"\"\"Returns all monters and their counts in the encounter\n by encounter_id\"\"\"\n with self._db.connect() as db:\n cur = db.execute(\"\"\"\n SELECT `monster_id` AS `id`, `count`\n FROM `encounter_monsters`\n WHERE `encounter_id` = :encounterId\n ORDER BY `monster_id` ASC\n \"\"\",\n {\"encounterId\": encounter_id}\n )\n rows = cur.fetchall() or []\n cur.close()\n\n return [dict(row) for row in rows]\n\n def fillJoinTables(self, obj):\n \"\"\"Populates entries in encounter_monsters table\"\"\"\n if not len(obj.monster_ids):\n return\n\n with self._db.connect() as db:\n db.executemany(\"\"\"\n INSERT INTO `encounter_monsters`\n (`encounter_id`, `monster_id`, `count`)\n VALUES (?, ?, ?)\n \"\"\", [\n (obj.id, monster['id'], monster['count'])\n for monster in obj.monster_ids\n if monster['count'] > 0\n ])\n db.commit()\n","repo_name":"SebastiaanPasterkamp/dnd-machine","sub_path":"app/models/encounter.py","file_name":"encounter.py","file_ext":"py","file_size_in_byte":7471,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"41"} +{"seq_id":"3345279487","text":"from os import path\nfrom typing import Union\n\nimport numpy as np\nimport torch\n\nfrom flex.tools.base_algo import BaseProtocol\nfrom flex.crypto.key_exchange.api import make_agreement\nfrom flex.crypto.paillier.api import generate_paillier_encryptor_decryptor\nfrom flex.tools.ionic import make_broadcast_channel\nfrom flex.crypto.onetime_pad.iterative_add import iterative_add\nfrom flex.tools.iterative_apply import iterative_encryption, iterative_decryption, iterative_divide\n\n\nclass Mixin:\n def _make_channel(self):\n self.broadcast_chan = make_broadcast_channel(name=\"he_sa_ft_broadcast\",\n root=self.federal_info.coordinator,\n remote_group=self.federal_info.guest_host)\n\n def _do_exchange(self, theta: Union[list, np.ndarray, torch.Tensor], remote_id: str) -> Union[list, np.ndarray, torch.Tensor]:\n # step1\n seed = make_agreement(remote_id, key_size=self.sec_param.key_exchange_size)\n encryptor, decryptor = generate_paillier_encryptor_decryptor(self.sec_param.he_key_length, seed)\n # step2\n enc_theta = iterative_encryption(encryptor, theta)\n self.broadcast_chan.gather(enc_theta, tag=\"theta\")\n # step4\n enc_sum_theta = self.broadcast_chan.broadcast(tag=\"sum_theta\")\n sum_theta = iterative_decryption(decryptor, enc_sum_theta)\n avg_theta = iterative_divide(sum_theta, 2.0)\n return avg_theta\n\n\nclass HESAFTCoord(BaseProtocol, Mixin):\n def __init__(self, federal_info: dict, sec_param: dict):\n \"\"\"\n\n Args:\n federal_info:\n sec_param:\n \"\"\"\n if sec_param is not None:\n self.load_default_sec_param(path.join(path.dirname(__file__), 'sec_param.json'))\n super().__init__(federal_info, sec_param)\n self._make_channel()\n\n def exchange(self, *args, **kwargs):\n # step3\n enc_theta_list = self.broadcast_chan.gather(tag=\"theta\")\n sum_enc_theta = enc_theta_list[0]\n for i in range(1, len(enc_theta_list)):\n sum_enc_theta = iterative_add(sum_enc_theta, enc_theta_list[i])\n self.broadcast_chan.broadcast(sum_enc_theta, tag=\"sum_theta\")\n return\n\n\nclass HESAFTGuest(BaseProtocol, Mixin):\n def __init__(self, federal_info: dict, sec_param: dict):\n \"\"\"\n\n Args:\n federal_info:\n sec_param:\n \"\"\"\n if sec_param is not None:\n self.load_default_sec_param(path.join(path.dirname(__file__), 'sec_param.json'))\n super().__init__(federal_info, sec_param)\n self._make_channel()\n\n def exchange(self, theta: Union[list, np.ndarray, torch.Tensor]) -> Union[list, np.ndarray, torch.Tensor]:\n avg_theta = self._do_exchange(theta, remote_id=self.federal_info.host[0])\n return avg_theta\n\n\nclass HESAFTHost(BaseProtocol, Mixin):\n def __init__(self, federal_info: dict, sec_param: dict):\n \"\"\"\n\n Args:\n federal_info:\n sec_param:\n \"\"\"\n if sec_param is not None:\n self.load_default_sec_param(path.join(path.dirname(__file__), 'sec_param.json'))\n super().__init__(federal_info, sec_param)\n self._make_channel()\n\n def exchange(self, theta: Union[list, np.ndarray, torch.Tensor]) -> Union[list, np.ndarray, torch.Tensor]:\n avg_theta = self._do_exchange(theta, remote_id=self.federal_info.guest[0])\n return avg_theta\n","repo_name":"tongdun/iBond-flex","sub_path":"flex/federated_training/secure_aggregation/he_sa_ft/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"41"} +{"seq_id":"2105208318","text":"from data import users_data\nimport requests\nfrom config import settings\nimport pytest\n\nbase_url = settings.Settings().baseUrl()\nlogin_api_path = 'users/login'\nlogin_url = f'{base_url}/{login_api_path}'\nlogin_users = users_data.login_users()\n\n\n@pytest.fixture\ndef get_user_token():\n user = login_users[0]\n header = {\n 'Content-Type': 'application/json',\n }\n login_json = {\n 'email': user['email'],\n 'password': str(user['password']),\n }\n\n res = requests.post(\n login_url, headers=header, json=login_json)\n\n token = res.json()['token']\n return token\n","repo_name":"stephenZ22/mall_test","sub_path":"cases/users/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"72001723963","text":"# def greet(first_name, last_name):\n# print(f' Hi, {first_name} {last_name}')\n# print(\"Welcome To Python World!!\")\n\n\n# greet(\"Jatin\", \"Yadav\")\n\nimport random\n\nclass Dice:\n def roll(self):\n first = random.randint(1,6)\n second = random.randint(1,6)\n\n return(first, second)\n\nludo = Dice()\nprint(ludo.roll())\n\n\nfrom pathlib import Path\n\npath = Path(\"emails\")\nprint(path.mkdir()) #rmdir to remove directory\n\n\n","repo_name":"jatiinyadav/Python","sub_path":"Programs/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"32230978482","text":"import pathlib\nimport os\nimport io\nimport uuid\nfrom functools import lru_cache\nfrom fastapi import (\n FastAPI,\n Header,\n HTTPException,\n Depends,\n Request,\n File,\n UploadFile\n )\nfrom fastapi.responses import HTMLResponse, FileResponse\nfrom fastapi.templating import Jinja2Templates\nfrom pydantic import BaseSettings\nfrom PIL import Image\nimport pytesseract\n\nclass Settings(BaseSettings):\n debug: bool = False\n echo_active: bool = False\n app_auth_token: str = None\n app_auth_token_prod: str = None\n skip_auth: bool = False\n class Config:\n env_file = '.env'\n\n@lru_cache\ndef get_settings():\n return Settings()\n\nsettins=get_settings()\nDEBUG=settins.debug\nBASE_DIR = pathlib.Path(__file__).parent\nUPLOAD_DIR = BASE_DIR / 'uploaded'\n\n# print((BASE_DIR / \"templates\").exists())\n\napp = FastAPI()\ntemplats = Jinja2Templates(directory=BASE_DIR/'templates')\n#print('DEBUG:', DEBUG)\n# REST API\n\n@app.get(\"/\", response_class=HTMLResponse) # http GET -> JSON\ndef home_view(request: Request, settings: Settings = Depends(get_settings)):\n print(settings.debug)\n return templats.TemplateResponse('home.html', {'request': request, \"abc\": \"123\"})\n\n\ndef verify_auth(authorization = Header(None), settings: Settings = Depends(get_settings)):\n \"\"\"\n Authorization: Bearrerer \n {\"authorization\": \"Bearrerer \"}\n \"\"\"\n print(settings.dict())\n if settings.debug and settings.skip_auth:\n return\n if authorization is None:\n raise HTTPException(status_code=401, detail=\"Invalid endpoint\")\n\n label, token = authorization.split()\n #print('token', token)\n #print('settings.app_auth_token', settings.app_auth_token)\n if token != settings.app_auth_token:\n raise HTTPException(status_code=401, detail=\"Invalid endpoint\")\n\n@app.post(\"/\") # http POST\nasync def prediction_view(file:UploadFile = File(...), authorization=Header(None), settings: Settings = Depends(get_settings)):\n verify_auth(authorization, settings)\n UPLOAD_DIR.mkdir(exist_ok=True)\n bytes_str = io.BytesIO(await file.read())\n try:\n img = Image.open(bytes_str)\n except:\n raise HTTPException(status_code=400, detail=\"Invalid image\")\n\n preds = pytesseract.image_to_string(img,lang='kor+eng')\n predictions = [x for x in preds.split('\\n')]\n\n return {\"result:\": predictions, \"original\": preds}\n\n@app.post(\"/img-echo/\", response_class=FileResponse) # http POST\nasync def img_echo_view(file:UploadFile = File(...), settings: Settings = Depends(get_settings)):\n if not settings.echo_active:\n raise HTTPException(status_code=400, detail=\"Invalid endpoint\")\n UPLOAD_DIR.mkdir(exist_ok=True)\n bytes_str = io.BytesIO(await file.read())\n try:\n img = Image.open(bytes_str)\n except:\n raise HTTPException(status_code=400, detail=\"Invalid image\")\n fname = pathlib.Path(file.filename)\n fext = fname.suffix #.jpg #.png\n dest = UPLOAD_DIR / f\"{uuid.uuid1()}{fext}\"\n img.save(dest)\n\n return dest","repo_name":"bumjin/ms-fastapi-django","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"42487437382","text":"\"\"\"ggf Datenbank erstellen und Tabellen anlegen\"\"\"\nimport sqlite3\nconnection = sqlite3.connect(\"Rezeptdatenbank.db\")\ncursor = connection.cursor()\n\n#cursor.execute(\"\"\"DROP TABLE rezepte;\"\"\")\n#cursor.execute(\"\"\"DROP TABLE zutaten;\"\"\")\n\ncursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS rezepte (\n rezeptname TEXT, dauer TEXT, zubereitung TEXT)\"\"\")\ncursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS zutaten (\n rezeptname TEXT, menge INTEGER, einheit TEXT, zutat TEXT)\"\"\")\n\nconnection.commit()","repo_name":"YoTcA/Rezeptdatenbank","sub_path":"src_alt/StartUp.py","file_name":"StartUp.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"22548724116","text":"\nimport torch\nimport argparse\nfrom tqdm import tqdm\nfrom transformer.Translator import Translator\nfrom DataLoader import DataLoader\nfrom preprocess import read_instances_from_file, convert_instance_to_idx_seq\n\ndef main():\n\n parser = argparse.ArgumentParser(description='translate.py')\n\n parser.add_argument('-model', default='trained.chkpt',\n help='Path to model .pt file')\n parser.add_argument('-src', default = 'data/multi30k/test.en.atok',\n help='Source sequence to decode (one line per sequence)')\n parser.add_argument('-ctx', required=False, default=\"\",\n help='Context sequence to decode (one line per sequence)')\n parser.add_argument('-vocab', default='data/multi30k.atok.low.pt',\n help='Data that contains the source vocabulary')\n parser.add_argument('-output', default='pred.txt',\n help=\"\"\"Path to output the predictions (each line will\n be the decoded sequence\"\"\")\n parser.add_argument('-beam_size', type=int, default=5,\n help='Beam size')\n parser.add_argument('-batch_size', type=int, default=30,\n help='Batch size')\n parser.add_argument('-n_best', type=int, default=1,\n help=\"\"\"If verbose is set, will output the n_best\n decoded sentences\"\"\")\n parser.add_argument('-no_cuda', action='store_false')\n parser.add_argument('-max_token_seq_len', type=int, default=100)\n\n opt = parser.parse_args()\n opt.cuda = not opt.no_cuda\n\n # Prepare DataLoader\n preprocess_data = torch.load(opt.vocab)\n preprocess_settings = preprocess_data['settings']\n\n test_src_word_insts = read_instances_from_file(\n opt.src,\n opt.max_token_seq_len,\n preprocess_settings.keep_case)\n test_src_insts = convert_instance_to_idx_seq(\n test_src_word_insts, preprocess_data['dict']['src'])\n\n if opt.ctx:\n from preprocess_ctx import read_instances_from_file as read_instances_from_file_ctx\n test_ctx_word_insts = read_instances_from_file_ctx(\n opt.ctx,\n opt.max_token_seq_len,\n preprocess_settings.keep_case,\n is_ctx=True)\n test_ctx_insts = convert_instance_to_idx_seq(\n test_ctx_word_insts, preprocess_data['dict']['src'])\n\n test_data = DataLoader(\n preprocess_data['dict']['src'],\n preprocess_data['dict']['tgt'],\n src_insts=test_src_insts,\n ctx_insts=(test_ctx_insts if opt.ctx else None),\n cuda=opt.cuda,\n shuffle=False,\n batch_size=opt.batch_size,\n is_train=False)\n\n translator = Translator(opt)\n translator.model.eval()\n\n with open(opt.output, 'w') as f:\n for batch in tqdm(test_data, mininterval=2, desc=' - (Test)', leave=False):\n print(---------1111111111)\n all_hyp, all_scores = translator.translate_batch(*batch)\n print(---------2222222222)\n for idx_seqs in all_hyp:\n for idx_seq in idx_seqs:\n if idx_seq[-1] == 3: # if last word is EOS\n idx_seq = idx_seq[:-1]\n pred_line = ' '.join([test_data.tgt_idx2word[int(idx)] for idx in idx_seq])\n f.write(pred_line + '\\n')\n print(\"end\")\n \n print('[Info] Finished.')\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"FreedomIntelligence/complex-order","sub_path":"TRANSLATION/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"41"} +{"seq_id":"11018286772","text":"'''\nPlayer for the barnes-Hutt N-body simulation created by Matt Griffiths and James Archer.\nPlayer Written by Matt Griffiths.\n\nREQUIRES VPYTHON TO RUN\n\nAvaliable for use under a GPL v3 licence.\n'''\n\n#Import dependent libraries\nimport pickle\nfrom time import sleep\n\nclass player():\n#Player Class containing unpacker and ply function\n\n \n def __init__(self,filename, play_rate = 30):\n #Unpacks data from file\n self.play_rate = play_rate\n self.index = 1\n self.scene = display(width = 1000, height = 800)\n self.trail = False\n while True:\n try:\n self.file = open(filename + str(self.index) + '.barnes','rb')\n print(\"Opened file \" + filename + str(self.index))\n self.index += 1\n except:\n print('Ended trying to open file ' + str(self.index))\n break\n #Open file, set up data structures for incoming data\n \n self.steps = []\n self.particles = []\n\n #Unpack data into pre-existing data structures\n self.steps = pickle.load(self.file)\n self.file.close()\n\n #print('Number of steps is ' + str(len(self.steps)))\n\n #Create visual representations\n for i in self.steps[0]:\n self.particles.append(sphere(pos = (i[0],i[1],i[2]),radius = 0.1*pow(i[3],0.33)))#\n if self.trail:\n self.particles[-1].trail = curve()\n if self.index == 1:\n self.scene.autoscale = True\n else:\n self.scene.autoscale = False\n #pass\n self.play()\n \n def play(self):\n #Play function\n\n #Set iteration pos to zero\n i = 0\n #print('f called')\n #Loop through steps\n sleep(1)\n while i < len(self.steps):\n\n #set refresh rate\n rate(self.play_rate)\n #Move spheres to relavent posiions\n for j in range(0,len(self.particles)):\n self.particles[j].pos = (self.steps[i][j][0],self.steps[i][j][1],self.steps[i][j][2])\n if self.trail:\n self.particles[j].trail.append(pos = self.particles[j].pos)\n\n #Step player\n i += 1\n\n #Handle looping\n #if i >= len(self.steps):\n # i = 0\n for i in self.particles:\n i.visible = False\n del i\n\n\nif __name__ == '__main__':\n from visual import *\n#If this is executed as standalone give input options\n while True:\n try:\n ifn = input('Input file name: ')\n break\n except:\n pass\n r = int(input('Playback rate: '))\n p = player(ifn, r)\n print('fin')\n","repo_name":"UOWPhysSoc/Barnes-Hutt-Simulation--James-MattG-","sub_path":"barnesplayer.py","file_name":"barnesplayer.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"41"} +{"seq_id":"71607188604","text":"from typing import Dict\n\nimport fire_watch\nfrom fire_watch.log.log_configs import get_logger\nfrom fire_watch.utils import pagination_utils\n\nfrom .base_model import BaseModel\n\n\nclass AdminModel(BaseModel):\n logger = get_logger(__name__, filename=\"./alerts.log\")\n\n def log_user_request(self, doc: Dict[str, str]):\n existing_user = self.db.Admin.find_one({\"email\": doc[\"email\"]})\n #! Change to sns or ses\n if existing_user:\n self.logger.warning(f\"User Update Request!\")\n else:\n self.logger.warning(f\"User insertion!\")\n # Maintain a record of all units with users!\n self.db.Admin.insert_one(doc)\n\n def get_unit_details(self, page: int):\n project_pipeline = {\n \"$project\": {\n \"_id\": 0,\n }\n }\n skip, limit = pagination_utils(\n page=page,\n page_limit=fire_watch.conf.pagination_limit,\n )\n data = self.db.Admin.aggregate(\n pipeline=[\n {\"$limit\": limit},\n {\"$skip\": skip},\n project_pipeline,\n ]\n )\n return list(data)\n","repo_name":"Aradhya-Tripathi/fire-watch","sub_path":"server/models/admin_model.py","file_name":"admin_model.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"41"} +{"seq_id":"11334130259","text":"from transformers import SegformerFeatureExtractor, SegformerForSemanticSegmentation\nfrom PIL import Image\nimport requests\n\n# Function to recognize urban landscapes and identify different objects in the image\n# Uses the Segformer model fine-tuned on CityScapes at resolution 1024x1024\n# The model is loaded from Hugging Face Transformers\n\ndef urban_landscape_recognition(url):\n # Load the pre-trained model\n feature_extractor = SegformerFeatureExtractor.from_pretrained('nvidia/segformer-b5-finetuned-cityscapes-1024-1024')\n model = SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b5-finetuned-cityscapes-1024-1024')\n\n # Open the image\n image = Image.open(requests.get(url, stream=True).raw)\n\n # Convert the image into input tensors\n inputs = feature_extractor(images=image, return_tensors='pt')\n\n # Feed the input tensors to the model\n outputs = model(**inputs)\n\n # Get the output logits\n logits = outputs.logits\n\n return logits","repo_name":"vixuowis/Research-2309","sub_path":"Exp-2/output/hf-eval-data-v1/f00747_urban_landscape_recognition.py","file_name":"f00747_urban_landscape_recognition.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"72549889402","text":"from services import Services\r\nfrom person_auth import PersonAuth\r\nimport pandas as pd\r\n\r\n\r\ndf=pd.read_csv('client_list.csv') #Our practise dataset contains pin code, balance account and name\r\n\r\ncard_in=True\r\n\r\n\r\nauthorized=PersonAuth()\r\namount, name, indexx, pin =authorized.authorized(df)\r\nwhile card_in:\r\n\r\n action = input('What would you like to do withdraw[w], deposit[d], change pin [c], exit[e]?')\r\n if action.lower()[0] == 'w':\r\n\r\n withdraw = Services(amount, name)\r\n wanted=withdraw.get_money()\r\n new_balance=withdraw.current_balance(amount, -wanted)\r\n authorized.update_file(df,indexx,new_balance, pin)\r\n amount = new_balance\r\n\r\n elif action.lower()[0] == 'd':\r\n\r\n deposit = Services(amount, name)\r\n deposit_amount=deposit.give_money()\r\n new_balance=deposit.current_balance(amount, deposit_amount)\r\n authorized.update_file(df,indexx,new_balance, pin)\r\n amount = new_balance\r\n\r\n elif action.lower()[0] =='e':\r\n print(f'Good Buy Mr/Ms {name}')\r\n print('Card returned')\r\n\r\n card_in =False\r\n\r\n elif action.lower()[0] =='c':\r\n pinchange = Services(amount, name)\r\n newpin=pinchange.pin_change(pin)\r\n authorized.update_file(df, indexx, amount, newpin)\r\n\r\n else:\r\n print('Not clear action is requested')\r\n\r\n","repo_name":"kvalaroutsos/ATM_simultion_OOP","sub_path":"basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"42750594706","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any, Optional\n\nfrom ..utils.text_decorations import add_surrogates, remove_surrogates\nfrom .base import MutableTelegramObject\n\nif TYPE_CHECKING:\n from .user import User\n\n\nclass MessageEntity(MutableTelegramObject):\n \"\"\"\n This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc.\n\n Source: https://core.telegram.org/bots/api#messageentity\n \"\"\"\n\n type: str\n \"\"\"Type of the entity. Currently, can be 'mention' (:code:`@username`), 'hashtag' (:code:`#hashtag`), 'cashtag' (:code:`$USD`), 'bot_command' (:code:`/start@jobs_bot`), 'url' (:code:`https://telegram.org`), 'email' (:code:`do-not-reply@telegram.org`), 'phone_number' (:code:`+1-212-555-0123`), 'bold' (**bold text**), 'italic' (*italic text*), 'underline' (underlined text), 'strikethrough' (strikethrough text), 'spoiler' (spoiler message), 'code' (monowidth string), 'pre' (monowidth block), 'text_link' (for clickable text URLs), 'text_mention' (for users `without usernames `_), 'custom_emoji' (for inline custom emoji stickers)\"\"\"\n offset: int\n \"\"\"Offset in `UTF-16 code units `_ to the start of the entity\"\"\"\n length: int\n \"\"\"Length of the entity in `UTF-16 code units `_\"\"\"\n url: Optional[str] = None\n \"\"\"*Optional*. For 'text_link' only, URL that will be opened after user taps on the text\"\"\"\n user: Optional[User] = None\n \"\"\"*Optional*. For 'text_mention' only, the mentioned user\"\"\"\n language: Optional[str] = None\n \"\"\"*Optional*. For 'pre' only, the programming language of the entity text\"\"\"\n custom_emoji_id: Optional[str] = None\n \"\"\"*Optional*. For 'custom_emoji' only, unique identifier of the custom emoji. Use :class:`aiogram.methods.get_custom_emoji_stickers.GetCustomEmojiStickers` to get full information about the sticker\"\"\"\n\n if TYPE_CHECKING:\n # DO NOT EDIT MANUALLY!!!\n # This section was auto-generated via `butcher`\n\n def __init__(\n __pydantic__self__,\n *,\n type: str,\n offset: int,\n length: int,\n url: Optional[str] = None,\n user: Optional[User] = None,\n language: Optional[str] = None,\n custom_emoji_id: Optional[str] = None,\n **__pydantic_kwargs: Any,\n ) -> None:\n # DO NOT EDIT MANUALLY!!!\n # This method was auto-generated via `butcher`\n # Is needed only for type checking and IDE support without any additional plugins\n\n super().__init__(\n type=type,\n offset=offset,\n length=length,\n url=url,\n user=user,\n language=language,\n custom_emoji_id=custom_emoji_id,\n **__pydantic_kwargs,\n )\n\n def extract_from(self, text: str) -> str:\n return remove_surrogates(\n add_surrogates(text)[self.offset * 2 : (self.offset + self.length) * 2]\n )\n","repo_name":"aiogram/aiogram","sub_path":"aiogram/types/message_entity.py","file_name":"message_entity.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","stars":3971,"dataset":"github-code","pt":"41"} +{"seq_id":"17482348618","text":"\"\"\"unidic.py\nData processing script for unidic dictionary\n\"\"\"\n\nimport warnings\nfrom pathlib import Path\n\nimport pandas as pd\n\nfrom yomikata.config import config, logger\n\nwarnings.filterwarnings(\"ignore\")\n\n\ndef unidic_data():\n \"\"\"Extract, load and transform the unidic data\"\"\"\n\n # Extract sentences from the data files\n unidic_file = list(Path(config.RAW_DATA_DIR, \"unidic\").glob(\"*.csv\"))[0]\n\n # Load file\n df = pd.read_csv(\n unidic_file,\n header=None,\n names=\"surface id1 id2 id3 pos1 pos2 pos3 pos4 cType \"\n \"cForm lForm lemma orth orthBase pron pronBase goshu iType iForm fType \"\n \"fForm iConType fConType type kana kanaBase form formBase aType aConType \"\n \"aModType lid lemma_id\".split(\" \"),\n )\n\n df[\"surface\"] = df[\"surface\"].astype(str).str.strip()\n df[\"kana\"] = df[\"kana\"].astype(str).str.strip()\n df = df[df[\"kana\"] != \"*\"]\n df = df[df[\"surface\"] != df[\"kana\"]]\n df = df[[\"surface\", \"kana\"]]\n\n df.to_csv(Path(config.READING_DATA_DIR, \"unidic.csv\"), index=False)\n\n logger.info(\"✅ Processed unidic data!\")\n\n\nif __name__ == \"__main__\":\n unidic_data()\n","repo_name":"passaglia/yomikata","sub_path":"yomikata/dataset/unidic.py","file_name":"unidic.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"41"} +{"seq_id":"38722333068","text":"class Movie():\n\n #constructor\n \n def __init__(self, id_imdb: str, title: str, yearr: int, description: str, directors: str, stars: str, genres: str, image: str):\n self.id_imdb = id_imdb \n self.title = title \n self.yearr = yearr \n self.description = description \n self.directors = directors \n self.stars = stars \n self.genres = genres \n self.image = image \n\n #Representacion en \"str\" del objeto de tipo \"Pelicula\"\n def __str__(self):\n return f\"\"\"\\nID de la Película: {self.id_imdb}\\nTitulo de la pelicula: {self.title}\\nAño de emision: {self.yearr}\\nDescripción: {self.description}\\nDirectores: {self.directors}\\nActores: {self.stars}\\nGeneros: {self.genres}\\nPoster: {self.image}\\n\\n\"\"\"\n \n def __eq__(self, movie):\n \n if movie.id_imdb != self.id_imdb:\n print(movie.id_imdb, \"no es igual a\", self.id_imdb)\n return False\n\n if movie.yearr != self.yearr:\n print(movie.yearr, \"no es igual a\", self.yearr)\n return False\n\n if movie.description != self.description:\n print(movie.description, \"no es igual a\", self.description)\n return False\n\n if movie.directors != self.directors:\n print(movie.directors, \"no es igual a\", self.directors)\n return False\n\n if movie.stars != self.stars:\n print(movie.stars, \"no es igual a\", self.stars)\n return False\n\n if movie.genres != self.genres:\n print(movie.genres, \"no es igual a\", self.genres)\n return False\n\n if movie.image != self.image:\n print(movie.image, \"no es igual a\", self.image)\n return False\n\nif __name__ == \"__main__\":\n pass","repo_name":"Geeorgge/IMDB_API","sub_path":"Movie.py","file_name":"Movie.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"35794531778","text":"#!/usr/bin/env python3\n# -*- coding : utf-8 -*-\n#\n\nimport time\nimport re\n#import sys\n#print(sys.path)\nfrom pynq import Overlay\nfrom pynq import PL\nfrom pynq import MMIO\n\nfpgadir = 'fpga-data/'\nfirm = 'rvmon.mot'\n#dump = True\ndump = False\n\nprint('** Load \"design_1.bit\" to Overlay')\nOL = Overlay(fpgadir + 'design_1.bit', download=True)\n#if not OL.is_loaded():\n# OL.download()\n\n# get clock frequency from hardware configuration file\nprint(\"PL clock frequency\")\nfreq = {}\nclkname = {'s00_axi_aclk':'rv32core', 'M00_AXI_ACLK':'tfacc'}\nwith open(fpgadir + 'design_1.hwh', 'r') as f:\n for line in f:\n if 'CLKFREQUENCY=' in line:\n for clk, block in clkname.items():\n if clk in line:\n freq[block] = int(re.search(r'CLKFREQUENCY=\"\\d+', line).group()[14:])\n print(\" %-8s : %5.1f MHz\" % (block, freq[block] / 1e6))\n\n#for k in PL.ip_dict.keys():\n# if k.startswith('tfacc'): print(k, PL.ip_dict[k])\n# if k.startswith('s00'): print(k, PL.ip_dict[k])\n\n#adr_base = PL.ip_dict[\"tfacc_cpu_v1_0_0/s00_axi\"]['phys_addr']\n#adr_range = PL.ip_dict[\"tfacc_cpu_v1_0_0/s00_axi\"]['addr_range']\nadr_base = PL.ip_dict[\"tfacc_cpu_v1_0_0\"]['phys_addr']\nadr_range = PL.ip_dict[\"tfacc_cpu_v1_0_0\"]['addr_range']\n\nprint(\"base:%x range:%x\"%(adr_base, adr_range))\n#mmio = MMIO(adr_base, adr_range)\n#for a in range(6):\n# mmio.write(a*4, a+1)\n#for a in range(6):\n# print(\"adr:%x %x\"%(a*4, mmio.read(a*4)))\n\nprint('*** Load \"%s\" to processor memory'%(firm))\nimport numpy as np\n\nreset_reg = 0x80\nfreq_reg = 0xf0\n\nmmio = MMIO(adr_base, adr_range)\n\nmmio.write(reset_reg, 0)\t# reset cpu\n\n#sfile = \"fpga-data/rvmon.mot\"\nsfile = fpgadir + firm\n\nbuf = np.zeros(32768, dtype=int)\n\nwith open(sfile, 'r') as f:\n recs = f.readlines()\n\nladr = 0\n\nfor rec in recs:\n rec = rec.strip()\n sr = rec[0:2]\n if sr == 'S3' :\n nb = int(rec[2:4], 16) - 5\n addr = int(rec[5:12], 16)\n# print(\"nb:%d addr:%x\"%(nb,addr))\n for i in range(nb):\n buf[addr+i] = int(rec[12+i*2:12+i*2+2], 16)\n# print(\"%02x\"%int(rec[i:i+2], 16))\n ladr = max(ladr, addr+i)\n\nfor i in range(0,ladr+4,4):\n# if i % 16 == 0: print(\"\\n%04x : \"%i, end='')\n# wd = buf[i]<<24 | buf[i+1]<<16 | buf[i+2]<<8 | buf[i+3] # Big endian\n wd = buf[i+3]<<24 | buf[i+2]<<16 | buf[i+1]<<8 | buf[i+0] # Little endian\n# print(\"%08x \"%wd, end='')\n mmio.write(i, int(wd))\n\nif dump:\n for i in range(0,ladr+4,4):\n if i % 16 == 0: print(\"\\n%04x : \"%i, end='')\n rd = mmio.read(i)\n print(\"%08x \"%rd, end='')\n print()\n\n\nmmio.write(freq_reg, freq['rv32core'])\t# clock freq(Hz) @ 0xf0\n\nmmio.write(reset_reg, 1)\t# release reset\n\n\n\n","repo_name":"shin-yamashita/6th-AI-Edge-Contest","sub_path":"tfacc_load.py","file_name":"tfacc_load.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"41"} +{"seq_id":"5313506853","text":"#!/usr/bin/env python2\n# coding:utf-8\n\nimport os\nimport sys\nimport time\nimport threading\n\nif __name__ == '__main__':\n current_path = os.path.dirname(os.path.abspath(__file__))\n root_path = os.path.abspath( os.path.join(current_path, os.pardir, os.pardir, os.pardir))\n data_path = os.path.abspath(os.path.join(root_path, os.pardir, os.pardir, 'data'))\n data_gae_proxy_path = os.path.join(data_path, 'x_tunnel')\n python_path = os.path.abspath( os.path.join(root_path, 'python27', '1.0'))\n\n noarch_lib = os.path.abspath( os.path.join(python_path, 'lib', 'noarch'))\n sys.path.append(noarch_lib)\n\n if sys.platform == \"win32\":\n win32_lib = os.path.abspath( os.path.join(python_path, 'lib', 'win32'))\n sys.path.append(win32_lib)\n elif sys.platform.startswith(\"linux\"):\n linux_lib = os.path.abspath( os.path.join(python_path, 'lib', 'linux'))\n sys.path.append(linux_lib)\n elif sys.platform == \"darwin\":\n darwin_lib = os.path.abspath( os.path.join(python_path, 'lib', 'darwin'))\n sys.path.append(darwin_lib)\n extra_lib = \"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python\"\n sys.path.append(extra_lib)\n\n\nfrom front import front\nfrom xlog import getLogger\nxlog = getLogger(\"heroku_front\")\nxlog.set_buffer(2000)\n\nimport connect_control\n\n\ndef get():\n start_time = time.time()\n content, status, response = front.request(\"GET\", \"scan1.xx-net.com\", path=\"/wait?time=5\")\n time_cost = time.time() - start_time\n xlog.info(\"GET cost:%f\", time_cost)\n xlog.info(\"status:%d content:%s\", status, content)\n\n\ndef pall():\n for _ in range(10):\n threading.Thread(target=loop).start()\n\n\ndef loop():\n while connect_control.keep_running:\n get()\n time.sleep(0)\n\n xlog.info(\"Exiting heroku_front module...\")\n front.stop()\n\n\nif __name__ == '__main__':\n import traceback\n\n try:\n get()\n except Exception:\n traceback.print_exc(file=sys.stdout)\n except KeyboardInterrupt:\n front.stop()\n sys.exit()\n","repo_name":"klsfct/a-web-proxy-tool","sub_path":"code/default/x_tunnel/local/heroku_front/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"41"} +{"seq_id":"72329271164","text":"'''\nThe output should be:\n100\n'''\n\n# the bar variable had the value set as a string instead of an integer as variable foo contains and integer. \n# So I made bar an integer by adding brackets and putting int infront of it.\nfoo = 20\nbar = int('80')\nprint(foo + bar)","repo_name":"Techgrounds-Cloud-9/cloud-9-Ephraim52","sub_path":"06_Project_Docs/Code/Python/bonus exercise 2.py","file_name":"bonus exercise 2.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"13852992556","text":"from tempest.api.monitoring import base\nfrom tempest_lib import exceptions as lib_exc\nfrom tempest import test\nfrom tempest_lib.common.utils import data_utils\nfrom tempest.common import waiters\nimport datetime\nimport json\nfrom tempest.common import ssh\nfrom tempest import config\nimport time\nCONF = config.CONF\n\nclass MonitoringCinderDiagnosticsTestJSON(base.BaseMonitoringTest):\n _interface = 'json'\n\n @classmethod\n def setUpClass(cls):\n super(MonitoringCinderDiagnosticsTestJSON, cls).setUpClass()\n\n @test.attr(type=\"gate\")\n def test_bad_3par_credentials(self):\n metric_name = \"cinderDiagnostics.credentials\"\n error_injection_name =\"bad_3par_credential\"\n self._test_cinder_diagnostics(metric_name, error_injection_name);\n \n @test.attr(type=\"gate\")\n def test_bad_3par_cpg(self):\n metric_name = \"cinderDiagnostics.CPG\"\n error_injection_name =\"bad_3par_cpg\"\n self._test_cinder_diagnostics(metric_name, error_injection_name);\n \n @test.attr(type=\"gate\")\n def test_missing_package_3parclient(self):\n metric_name = \"cinderDiagnostics.3par\"\n error_injection_name =\"missing_package_3parclient\"\n self._test_cinder_diagnostics(metric_name, error_injection_name);\n \n @test.attr(type=\"gate\")\n def test_bad_3par_iscsi_ips(self):\n metric_name = \"cinderDiagnostics.iSCSI\"\n error_injection_name =\"bad_3par_iscsi_ips\"\n self._test_cinder_diagnostics(metric_name, error_injection_name);\n \n @test.attr(type=\"gate\")\n def test_bad_3par_ws_url(self):\n metric_name = \"cinderDiagnostics.WS\"\n error_injection_name =\"bad_3par_ws_url\"\n self._test_cinder_diagnostics(metric_name, error_injection_name);\n \n # FC does not work on the vagrant environment , need to skip the testcases \n #@test.attr(type=\"gate\")\n def _test_missing_package_sg3utils(self):\n metric_name = \"cinderDiagnostics.sg3utils\"\n error_injection_name =\"available_package_sg3utils\"\n \n self.manager = self.os\n #self.adm_manager= self.os_adm\n self.image = CONF.compute.image_ref\n self.flavor = CONF.compute.flavor_ref\n \n #extra_specs = {\"volume_backend_name\":\"3PAR-THEVERSE\"}\n #self.adm_manager.volume_types_client.create_volume_type(name='3PAR-THEVERSE', extra_specs=extra_specs)\n \n # Step 1: create a volume \n name = data_utils.rand_name(\"volume\")\n volume = self.manager.volumes_client.create_volume(\n display_name=name, volume_type='3PAR-THEVERSE')\n self.manager.volumes_client.wait_for_volume_status(volume['id'],\n 'available')\n # Test normal case for successful connection on first try\n client = ssh.Client(CONF.cinder_diagnostics.cinder_ssh_ip, CONF.cinder_diagnostics.cinder_ssh_user, CONF.cinder_diagnostics.cinder_ssh_password, timeout=30)\n sshconnection = client._get_ssh_connection(sleep=1)\n try:\n # Setup sftp connection and transmit this script\n sftp = sshconnection.open_sftp()\n sftp.put(\"ErrorInjection.py\", \"ErrorInjection.py\")\n sftp.close()\n client.exec_command(\"python ErrorInjection.py --missing_package_sg3utils\")\n sshconnection.close()\n except IndexError:\n pass\n \n # Step 2: create vm instance\n vm_name = data_utils.rand_name(\"instance\")\n \n server = self.manager.servers_client.create_server(\n vm_name, self.image, self.flavor)\n server_id = server['id']\n waiters.wait_for_server_status(self.manager.servers_client, server_id,\n 'ACTIVE')\n # Step 3: attach and detach volume to vm\n self.manager.servers_client.attach_volume(server_id,\n volume['id'],\n '/dev/vdc')\n self.manager.volumes_client.wait_for_volume_status(volume['id'],\n 'in-use')\n self.manager.volumes_client.detach_volume(volume['id'])\n self.manager.volumes_client.wait_for_volume_status(volume['id'], 'available')\n \n # Step 5: delete volume\n self.manager.volumes_client.delete_volume(volume['id'])\n self.manager.volumes_client.wait_for_resource_deletion(volume['id'])\n \n # Step 4: delete vm\n self.manager.servers_client.delete_server(server_id)\n self.manager.servers_client.wait_for_server_termination(server_id)\n self._test_cinder_diagnostics(metric_name, error_injection_name);\n \n # common for all testcases \n def _test_cinder_diagnostics(self, metric_name, error_injection_name):\n \n \n m_starttime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n m_starttime = m_starttime.replace(' ', 'T') + 'Z'\n # Test case to check if new notification is created successfully.\n notification_name = data_utils.rand_name('notification-')\n notification_type = 'EMAIL'\n # Replace below email with valid email address as required.\n u_address = 'root@localhost'\n response = self.monitoring_client.create_notification(name=notification_name, type=notification_type, address=u_address)\n self.assertEqual(notification_name, response['name'])\n notification_id = response['id']\n # Delete notification\n \n \n #alarm_def_name = metric_name\n alarm_def_name = data_utils.rand_name('test_monasca_alarm_definition')\n expression = '%s > 0' % (metric_name)\n severity = 'HIGH'\n body = self.monitoring_client.create_alarm_definition(name=alarm_def_name, expression=expression, severity=severity)\n self.assertEqual(alarm_def_name, body['name'])\n alarm_def_id = body['id']\n self.assertEqual(expression, body['expression'])\n \n m_statistics = 'count'\n m_endtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n m_endtime = m_endtime.replace(' ', 'T') + 'Z'\n body = self.monitoring_client.metric_statistics(name=metric_name, dimensions='service:cinder',\n statistics=m_statistics, end_time=m_endtime, merge_metrics='true')\n self.assertEqual('200', body.response['status'])\n response = json.loads(body.data)\n \n # Test normal case for successful connection on first try\n client = ssh.Client(CONF.cinder_diagnostics.cinder_ssh_ip, CONF.cinder_diagnostics.cinder_ssh_user, CONF.cinder_diagnostics.cinder_ssh_password, timeout=100)\n sshconnection = client._get_ssh_connection(sleep=1)\n try:\n # Setup sftp connection and transmit this script\n sftp = sshconnection.open_sftp()\n sftp.put(\"ErrorInjection.py\", \"ErrorInjection.py\")\n sftp.close()\n except IndexError:\n pass\n client.exec_command(\"python ErrorInjection.py --\"+error_injection_name)\n \n isMetricAvailable = True\n for i in range(0, 30):\n metricFields = {'name': metric_name}\n #metricFields['timestamp'] = int((time.time()*1000))\n body = self.monitoring_client.list_metric(metricFields)\n self.assertEqual('200', body.response['status'])\n response = json.loads(body.data)\n if len(response['elements']) < 1 :\n isMetricAvailable = False\n \n isMeasurementsFound = False\n isAlarmFound = False\n isStateChangeToAlarm = False \n \n for i in range(0, 30):\n m_statistics = 'count'\n m_endtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n m_endtime = m_endtime.replace(' ', 'T') + 'Z'\n body = self.monitoring_client.metric_statistics(name=metric_name, dimensions='service:cinder',\n statistics=m_statistics,start_time=m_starttime, end_time=m_endtime, merge_metrics='true')\n self.assertEqual('200', body.response['status'])\n response = json.loads(body.data)\n if len(response['elements']) > 0 :\n if len(response['elements'][0]['statistics']) == 1:\n isMeasurementsFound = True ;\n break \n \n for i in range(0, 60):\n body = self.monitoring_client.list_alarms(alarm_definition_id=alarm_def_id)\n if len(body['elements']) > 0:\n isAlarmFound = True\n if body['elements'][0]['state'] == 'ALARM' :\n isStateChangeToAlarm = True\n break \n time.sleep(3) \n \n self.monitoring_client.delete_notification(notification_id)\n self.monitoring_client.delete_alarm_definition(alarm_def_id) \n \n if not isMetricAvailable :\n self.fail(\"No metric found \" + metric_name )\n if not isMeasurementsFound and not isStateChangeToAlarm :\n self.fail(\"No measurements found for \" + metric_name ) \n if not isAlarmFound :\n self.fail(\"No alarm found for \" + metric_name )\n if not isStateChangeToAlarm :\n self.fail(\"No state change to ALARM for metric \" + metric_name )\n ","repo_name":"hpe-storage/diags","sub_path":"tempest/test_cinder_diagnostics.py","file_name":"test_cinder_diagnostics.py","file_ext":"py","file_size_in_byte":9409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"2825103427","text":"#!/usr/bin/env python\nimport ROOT\nfrom optparse import OptionParser\n\ndef findBins(array, var):\n size = len(array)\n bin = \"dump\";\n for i in xrange(size-1):\n low = array[i]\n hi = array[i+1]\n if (low <= var and hi > var):\n bin = str(low)+\"To\"+str(hi)\n \n return bin;\n\ndef main(options):\n \n var1s = []\n for v in options.var1Bins.split(\",\"):\n var1s.append(float(v))\n var2s = []\n for v in options.var2Bins.split(\",\"):\n var2s.append(float(v))\n\n inFile = ROOT.TFile(options.input)\n inFile.cd(options.directory)\n fDir = inFile.Get(options.directory)\n fChain = fDir.Get(\"fitter_tree\")\n\n histos = dict()\n\n def fixForPDFusage(hist) :\n # Remove any negative-weighted bins, and\n # apply a small value uniformly to gurantee no zero bins\n for b in range(hist.GetNbinsX()+1) :\n if ( hist.GetBinContent(b) <= 0. ) :\n hist.SetBinContent(b, 0.0001)\n\n for binVar1 in xrange(len(var1s)-1):\n for binVar2 in xrange(len(var2s)-1):\n histNameSt = \"hMass_%s_bin%d__%s_bin%d\" % (options.var1Name, binVar1, options.var2Name, binVar2)\n hp = histNameSt+\"_Pass\"\n hf = histNameSt+\"_Fail\"\n (minMass, maxMass) = map(float, options.massWindow.split(\",\"))\n histos[hp] = ROOT.TH1D(hp, hp, 120, minMass, maxMass)\n histos[hf] = ROOT.TH1D(hf, hf, 120, minMass, maxMass)\n \n binning = \"mcTrue == 1 && \"+options.var1Name +\">\"+str(var1s[binVar1])+\" && \"+options.var1Name +\"<\"+str(var1s[binVar1+1])+\" && \"+options.var2Name +\">\"+str(var2s[binVar2])+\" && \"+options.var2Name +\"<\"+str(var2s[binVar2+1])\n if options.conditions :\n for condition in options.conditions.split(',') :\n binning += \" && %s==1\" % condition\n cuts = \"(\" + binning + \" && \"+options.idprobe+\"==1\"+\")*\"+options.weightVarName\n fChain.Draw(\"mass>>\"+histos[hp].GetName(), cuts, \"goff\")\n cuts = \"(\" + binning + \" && \"+options.idprobe+\"==0\"+\")*\"+options.weightVarName\n fChain.Draw(\"mass>>\"+histos[hf].GetName(), cuts, \"goff\")\n\n fixForPDFusage(histos[hp])\n fixForPDFusage(histos[hf])\n #hpassInt = histos[hp].Integral()\n #hfailInt = histos[hf].Integral()\n #print hpassInt, hfailInt, hpassInt/(hpassInt+hfailInt)\n \n outFile = ROOT.TFile(options.output, \"RECREATE\")\n for k in histos:\n histos[k].Write()\n outFile.Close()\n\n\nif __name__ == \"__main__\": \n parser = OptionParser()\n parser.add_option(\"-i\", \"--input\", default=\"../TnPTree_mc.root\", help=\"Input filename\")\n parser.add_option(\"-o\", \"--output\", default=\"mc_templates.root\", help=\"Output filename\")\n parser.add_option(\"-d\", \"--directory\", default=\"GsfElectronToRECO\", help=\"Directory with fitter_tree\")\n parser.add_option(\"\", \"--idprobe\", default=\"passingMedium\", help=\"String identifying ID WP to measure\")\n parser.add_option(\"\", \"--conditions\", default=\"\", help=\"String identifying conditions on Tag and Probe\")\n parser.add_option(\"\", \"--var1Bins\", default=\"20,30,40,50,200\", help=\"Binning to use in var1\")\n parser.add_option(\"\", \"--var2Bins\", default=\"0.0,1.0,1.4442,1.566,2.0,2.5\", help=\"Binning to use in var2\")\n parser.add_option(\"\", \"--var1Name\", default=\"probe_sc_eta\", help=\"Variable1 branch name\")\n parser.add_option(\"\", \"--var2Name\", default=\"probe_sc_et\", help=\"Variable2 branch name\")\n parser.add_option(\"\", \"--weightVarName\", default=\"totWeight\", help=\"Weight variable branch name\")\n parser.add_option(\"\", \"--massWindow\", default=\"60,120\", help=\"Mass window to generate template for\")\n\n (options, arg) = parser.parse_args()\n \n main(options)\n","repo_name":"nsmith-/DiBosonTP","sub_path":"scripts/getTemplatesFromMC.py","file_name":"getTemplatesFromMC.py","file_ext":"py","file_size_in_byte":3767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"28736326852","text":"\"\"\"\n 1.\n Создать файл file_practice.txt\n Записать в него строку 'Starting practice with files'\n Файл должен заканчиваться пустой строкой\n \"\"\"\n\nfile = open('../file_practice.txt', 'w')\nfile.write('Starting practice with files\\n')\nfile.close()\n\n\"\"\"\n 2.\n Прочесть первые 5 символов файла и вывести содержимое в верхнем регистре\n Затем прочесть весь файл от начала до конца, вывести содержимое на экран\n\"\"\"\n\nfile = open('../file_practice.txt')\ndata = file.readline(5).upper()\nprint(data)\ndata = file.seek(0)\nprint(file.read())\nfile.close()\n\n\"\"\"\n 3.\n Прочесть файл files/text.txt\n В тексте заменить все буквы 'i' на 'e', если 'i' большее кол-во,\n иначе - заменить все буквы 'e' на 'i'\n Полученный текст дописать в файл file_practice.txt\n\"\"\"\n\nf = open('../files_text.txt', 'w')\nf.write('Proin laoreet dui vel libero dapibus vehicula vitae eget turpis.\\n'\n 'Nam non eros eu elit posuere posuere id ac turpis.\\n'\n 'Quisque nec orci blandit, lobortis felis non, eleifend felis.\\n'\n 'Vivamus at odio at lacus viverra luctus et ut mauris.\\n'\n 'Etiam vehicula nibh eu quam feugiat tempus.\\n')\nf.close()\n\nf = open('../files_text.txt')\ndata1 = f.read()\nprint(data1)\n\ne = i = 0\nfor let in data1:\n if let == 'i':\n i += 1\n elif let == 'e':\n e += 1\nprint(e, i)\n\nif i < e:\n data_rep = data1.replace('i', 'e')\n print(data_rep)\nelse:\n data_rep = data1.replace('e', 'i')\n print(data_rep)\n\nfile = open('../file_practice.txt', 'a')\nfile.write(data_rep)\nf.close()\nfile.close()\n\n\"\"\"\n 4.\n Если в файле file_practice.txt четное количество элементов\n - файл должен заканчиваться строкой 'the end', иначе - строкой 'bye'\n Прочесть весь файл и вывести содержимое\n\"\"\"\n\nwith open('../file_practice.txt') as f:\n num = len(f.read())\n with open('../file_practice.txt', 'a') as file:\n if num % 2 != 0:\n file.write('bye')\n else:\n file.write('the end')\nf.close()\nfile.close()\n\nwith open('../file_practice.txt') as f:\n print(f.read())\nf.close()\n\n\"\"\"\n 5.\n В средину файла file_practice.txt вставить строку \" *some inserted text* \"\n (средина - имеется в виду средина текста)\n\"\"\"\n\n\nwith open('../file_practice.txt', 'r+') as file:\n file.seek(len(file.read()) // 2)\n file.write(' *some inserted text* ')\n file.close()\n","repo_name":"YarKoniukhov/itea","sub_path":"hw6/hw6.1.py","file_name":"hw6.1.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"16356432886","text":"from datetime import datetime\nimport json\nimport os\n\nfrom django.db import transaction\nfrom django.shortcuts import render, redirect, HttpResponse\nfrom django.template.loader import render_to_string\nfrom django.conf import settings\n\nfrom weasyprint import HTML\nimport requests\nfrom requests.auth import HTTPBasicAuth\n\nfrom .forms import InvoiceForm\nfrom .models import Invoice\n\ndef create_invoice(request):\n if request.method == 'POST':\n error_msg = ''\n request_data = request.POST\n with transaction.atomic():\n form = InvoiceForm(request_data)\n if form.is_valid():\n\n invoice_obj = form.save()\n\n template = render_to_string(\n 'invoice.html', {'invoice_description': request_data.get('invoice_description')})\n HTML(string=template).write_pdf(target=f\"{request_data.get('invoice_description')}.pdf\")\n f = open(f\"{request_data.get('invoice_description')}.pdf\", 'rb')\n\n auth = HTTPBasicAuth(username='admin', password='admin')\n payload = {\"language\":\"en\",\"fileName\":f\"{request_data.get('invoice_description')}.pdf\",\"folderId\":4 }\n\n files = { \n 'document': (None, json.dumps(payload), 'application/json'),\n 'content': (os.path.basename(settings.BASE_DIR), f, 'application/octet-stream')\n }\n \n headers = {'Content-Type': 'multipart/form-data'}\n res = requests.post(\n 'http://localhost:8080/services/rest/document/create', \n headers=headers, \n files=files, \n auth=auth\n )\n os.remove(f\"{request_data.get('invoice_description')}.pdf\")\n if res.status_code == 200:\n logical_doc_id = res.json().get('id')\n invoice_obj.logical_doc_id = logical_doc_id\n invoice_obj.save()\n return redirect('list_invoices')\n else:\n invoice_obj.delete()\n error_msg = res.text\n if not error_msg:\n error_msg = 'something went wrong'\n return render(request, 'create_invoice.html', {'form': form, 'error_msg': error_msg}) \n else:\n error_msg = 'Invalid entries'\n return render(request, 'create_invoice.html', {'form': form, 'error_msg': error_msg})\n form = InvoiceForm()\n return render(request, 'create_invoice.html', {'form': form})\n\ndef list_invoices(request):\n invoices = Invoice.objects.all()\n return render(request, 'list_invoices.html', {'invoices': invoices})\n\ndef get_invoice_doc(request):\n logical_doc_id = request.GET.get('logical_doc_id')\n auth = HTTPBasicAuth(username='admin', password='admin')\n res = requests.get(\n f\"http://localhost:8080/services/rest/document/getContent?docId={logical_doc_id}\",\n auth=auth\n )\n invoice = Invoice.objects.get(logical_doc_id=logical_doc_id)\n response = HttpResponse(res.content, content_type='application/pdf')\n response['Content-Disposition'] = f'inline;filename={invoice.invoice_description}_{logical_doc_id}.pdf'\n return response\n","repo_name":"ivar644/logicaldoc","sub_path":"invoice/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"5300390411","text":"from math import ceil\r\nnum_transn = int(input('Enter the number of transactions:\\t').strip())\r\nsupport_percent = float(input('Enter minimum support %:\\t').strip())\r\nconfidence_percent = float(input('Enter minimum confidence %:\\t').strip())\r\nrecords, items = [], []\r\nsupport_count = ceil(0.01 * num_transn * support_percent)\r\nfor transn in range(num_transn):\r\n records.append(sorted(input('Enter the items for transaction ' +\r\n str(transn + 1)+':\\t').strip().split()))\r\n items = set(list(items) + records[transn])\r\nc = [(item, len([True for record in records if item in record]))\r\n for item in items]\r\noverlap = 0\r\nwhile True:\r\n c = [item for item in c if item[1] >= support_count]\r\n c_new = []\r\n for i in range(len(c)):\r\n for j in range(i+1, len(c)):\r\n if c[i][0][:overlap] == c[j][0][:overlap] and all(any(all(item in candidate[0] for item in subset) for candidate in c) for subset in [[x for x in set(c[i][0]+c[j][0]) if x != y] for y in set(c[i][0]+c[j][0])]):\r\n c_new.append((sorted(set(c[i][0]+c[j][0])), len(\r\n [True for record in records if all(item in record for item in set(c[i][0]+c[j][0]))])))\r\n if not c_new:\r\n break\r\n c = c_new[:]\r\n overlap += 1\r\n\r\n\r\ndef rule_generate(l):\r\n equation = []\r\n for rotations in range(len(l)):\r\n for sep in range(len(l) - 1):\r\n equation.append((l[:sep + 1], l[sep + 1:]))\r\n l = l[1:] + l[:1]\r\n return equation\r\n\r\n\r\nprint('The strong association rules are:')\r\nfor candidate in c:\r\n for left, right in rule_generate(candidate[0]):\r\n if candidate[1]/len([True for record in records if all(item in record for item in left)]) >= (0.01 * confidence_percent):\r\n print(left, '=>', right)\r\n","repo_name":"abhinay170402/codes","sub_path":"apriori.py","file_name":"apriori.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"11585400565","text":"from tkinter import Tk, Label, Button, Toplevel, StringVar, Entry, messagebox, Frame, END, Scrollbar, Y, RIGHT\nfrom tkinter import Checkbutton, IntVar, BooleanVar, Text, INSERT\n\nfrom functools import partial\nimport tkinter as tk\nfrom tkinter.ttk import Separator, Style, Combobox, Treeview\nfrom time import sleep\nfrom snapFood import *\n\nmydb = SnapFoodDB()\n\n\nstyle = Style()\nstyle.configure(\"mystyle.Treeview\", highlightthickness=0, bd=0, font=('Calibri', 11)) # Modify the font of the body\nstyle.configure(\"mystyle.Treeview.Heading\", font=('Calibri', 13,'bold')) # Modify the font of the headings\nstyle.layout(\"mystyle.Treeview\", [('mystyle.Treeview.treearea', {'sticky': 'nswe'})]) # Remove the borders\n \n\nclass Application:\n def __init__(self, master):\n self.username = \"\"\n self.password = \"\"\n # self.db_cursor = mydb.cursor()\n self.master = master\n master.title(\"Snapp Food\")\n\n #Bring the window to the center of screen\n windowWidth = master.winfo_reqwidth()\n windowHeight = master.winfo_reqheight()\n # print(\"Width\",windowWidth,\"Height\",windowHeight)\n positionRight = int(master.winfo_screenwidth()/2 - windowWidth/2)\n positionDown = int(master.winfo_screenheight()/2 - windowHeight/2)\n # Positions the window in the center of the page.\n master.geometry(\"+{}+{}\".format(positionRight, positionDown))\n\n #Set Number of rows and columns\n self.master.rowconfigure(5)\n self.master.columnconfigure(5)\n\n self.makeMainWindow()\n \n\n # def loadingPage(self):\n # # loader = Tk()\n # # loader.title(\"loading\")\n # # root.attributes('-alpha', 1.0)\n\n def makeMainWindow(self):\n \n self.master.geometry(\"300x200\")\n\n self.master.title(\"Account Login\")\n \n Label(self.master,text=\"Select Your Choice\", bg=\"blue\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n Button(self.master,text=\"Login\", height=\"2\", width=\"30\", command = self.loginPage).pack()\n Label(text=\"\").pack()\n Button(self.master, text=\"Register\", height=\"2\", width=\"30\", command=self.registerPage).pack()\n \n closeButton = Button(self.master, text=\"Exit\", command=self.master.quit, width=\"200\", height=\"2\")\n closeButton.pack()\n \n def loginPage(self):\n self.login_screen = Tk()\n self.login_screen.title(\"Login\")\n self.login_screen.geometry(\"300x250\")\n Label(self.login_screen, text=\"Please enter details below to login\").pack()\n Label(self.login_screen, text=\"\").pack()\n\n\n username_verify = StringVar()\n password_verify = StringVar()\n\n\n Label(self.login_screen, text=\"Phone Numbers * \").pack()\n username_login_entry = Entry(self.login_screen, textvariable=username_verify)\n username_login_entry.pack()\n Label(self.login_screen, text=\"\").pack()\n Label(self.login_screen, text=\"Password * \").pack()\n password_login_entry = Entry(self.login_screen, textvariable=password_verify, show= '*')\n password_login_entry.pack()\n Label(self.login_screen, text=\"\").pack()\n Button(self.login_screen, text=\"Login\", width=10, height=1, command = partial(self.loginVerify, username_login_entry, password_login_entry)).pack()\n \n\n def loginVerify(self, username_login_entry, password_login_entry):\n # self.db_cursor.execute(\"SELECT userid, password FROM USER WHERE userid=\\'{}\\'\".format(username_login_entry.get()))\n \n data = mydb.login(username_login_entry.get())\n self.user_id = data[0][2]\n self.phone_number = username_login_entry.get()\n #check whether user_id exists or not\n if (len(data) != 0 and data[0][1] == password_login_entry.get()):\n \n self.dashboardPage()\n else:\n messagebox.showinfo('Username/Password incorrect', 'your username of password is incorrect')\n\n\n def registerPage(self):\n self.register_screen = Toplevel(self.master)\n self.register_screen.title(\"Register\")\n self.register_screen.geometry(\"300x450\")\n\n \n\n Label(self.register_screen, text=\"Please enter details below\", bg=\"blue\").pack()\n Label(self.register_screen, text=\"\").pack()\n\n #phonenumber\n Label(self.register_screen, text=\"Phone Number * \").pack()\n phone_number_entry = Entry(self.register_screen)\n phone_number_entry.pack()\n #password\n Label(self.register_screen, text=\"Password * \").pack()\n password_entry = Entry(self.register_screen,show='*')\n password_entry.pack()\n #repeat password\n Label(self.register_screen, text=\"Password * \").pack()\n repeat_password_entry = Entry(self.register_screen,show='*')\n repeat_password_entry.pack()\n #firstname\n Label(self.register_screen, text=\"First Name * \").pack()\n firstname_entry = Entry(self.register_screen)\n firstname_entry.pack()\n #lastname\n Label(self.register_screen, text=\"Last Name * \").pack()\n lastname_entry = Entry(self.register_screen)\n lastname_entry.pack() \n #email address\n Label(self.register_screen, text=\"Email Address * \").pack()\n email_entry = Entry(self.register_screen)\n email_entry.pack()\n\n Label(self.register_screen, text=\"\").pack()\n Button(self.register_screen, text=\"Register\", width=10, height=1, bg=\"blue\", command = partial(self.registerUser,\n phone_number_entry ,password_entry, repeat_password_entry, firstname_entry, lastname_entry, email_entry)).pack()\n\n\n\n def registerUser(self ,phone_number_entry, password_entry, repeat_password_entry, firstname_entry, lastname_entry, email_entry):\n #insert into database \n if (password_entry.get() == repeat_password_entry.get()):\n mydb.registerUser( phone_number_entry.get(), password_entry.get(),firstname_entry.get(), lastname_entry.get(), email_entry.get())\n Label(self.register_screen, text=\"Register was Seccesful\").pack()\n else:\n messagebox.showinfo('Repeat password again', 'your repeated password doesn\\'n match your entered password, Try Again')\n\n\n\n def dashboardPage(self):\n self.master.destroy\n self.login_screen.destroy\n self.dashboard = Tk()\n self.dashboard.title(\"User Dashboard\")\n self.dashboard.geometry(\"300x350\")\n\n Label(self.dashboard, text=\"Select Your Choice\", bg=\"blue\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n Button(self.dashboard,text=\"Profile\", height=\"2\", width=\"30\", command = self.profilePage).pack()\n Label(text=\"\").pack()\n Button(self.dashboard,text=\"Restaurants\", height=\"2\", width=\"30\", command=self.restaurantsPage).pack()\n Label(text=\"\").pack()\n Button(self.dashboard,text=\"Order\", height=\"2\", width=\"30\", command=self.orderPage).pack()\n Button(self.dashboard,text=\"Search\", height=\"2\", width=\"30\", command=self.searchFoodOrShop).pack()\n Button(self.dashboard,text=\"Charge your wallet\", height=\"2\", width=\"30\", command=self.chargeWallet).pack()\n \n closeButton = Button(self.dashboard, text=\"Exit\", command=self.dashboard.destroy, width=\"200\", height=\"2\")\n closeButton.pack()\n\n def chargeWallet(self):\n def charging(charge_wallet_entry):\n mydb.charging(self.user_id, int(charge_wallet_entry.get()))\n self.charge_wallet_screen = Tk()\n self.charge_wallet_screen.title(\"charging\")\n Label(self.charge_wallet_screen, text=\"Enter A number to charge your wallet\", bg=\"blue\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n Label(self.charge_wallet_screen, text=\"Just Numbers\")\n charge_wallet_entry = Entry(self.charge_wallet_screen)\n charge_wallet_entry.pack()\n Button(self.charge_wallet_screen, text=\"Charge My Wallet\", command=partial(charging, charge_wallet_entry)).pack()\n\n \n\n def searchFoodOrShop(self):\n self.search_screen = Tk()\n self.search_screen.title(\"Search page\")\n Label(self.search_screen, text=\"Search By Shops\", bg=\"Green\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n Label(self.search_screen, text=\"Search part of a name\").pack()\n shop_name_entry = Entry(self.search_screen)\n shop_name_entry.pack()\n Label(self.search_screen, text=\"Choose a city to find shops at that city\").pack()\n city_combo = Combobox(self.search_screen)\n cities = mydb.showAllCity()\n self.number_of_cities = len(cities)\n cities_list = []\n \n for i in cities:\n cities_list.append(i[1])\n cities_list.append(\"None\")\n city_combo['values']= cities_list\n city_combo.pack()\n city_combo.current(len(cities))\n # city_id = mydb.addCity(city_combo.get())\n Label(self.search_screen, text=\"Enter Min Bill Value:\").pack()\n min_bill_entry = Entry(self.search_screen)\n min_bill_entry.pack()\n Button(self.search_screen, text=\"Search\", command=partial(self.showRestaurantsBySearch, city_combo, shop_name_entry, min_bill_entry)).pack()\n Label(self.search_screen, text=\"Search By Foods\", bg=\"Green\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n Label(self.search_screen, text=\"Enter a Low Boundery for price\").pack()\n price_l_entry = Entry(self.search_screen)\n price_l_entry.pack()\n Label(self.search_screen, text=\"Enter a High Boundery for price\").pack()\n price_h_entry = Entry(self.search_screen)\n price_h_entry.pack()\n \n Label(self.search_screen, text=\"Search part of a food name\").pack()\n food_name_entry = Entry(self.search_screen)\n food_name_entry.pack()\n Label(self.search_screen, text=\"Enter your desire discount\").pack()\n discount_entry = Entry(self.search_screen)\n discount_entry.pack()\n Label(self.search_screen, text=\"Choose a catogory for you desire food\").pack()\n cat_combo = Combobox(self.search_screen)\n catogries = mydb.showAllCategory()\n self.number_of_catogry = len(catogries)\n catogri_list = []\n print (catogries)\n for i in catogries:\n catogri_list.append(str(i[0])+ \" \"+ i[1])\n catogri_list.append(\"None\")\n cat_combo['values']= catogri_list\n cat_combo.pack()\n cat_combo.current(len(catogries)) \n Button(self.search_screen, text=\"Search\", command=partial(self.showFoods, cat_combo, price_l_entry, price_h_entry, food_name_entry, discount_entry)).pack()\n\n def showFoods(self, cat_cambo, price_l_entry, price_h_entry, food_name_entry, discount_entry):\n self.search_food_screen = Tk()\n self.search_food_screen.title(\"Foods\")\n price_l = price_l_entry.get()\n if (price_l_entry.get() == \"\"):\n price_l = None\n price_h = price_h_entry.get()\n if (price_h_entry.get() == \"\"):\n price_h = None\n food_name = food_name_entry.get()\n if (food_name_entry.get() == \"\"):\n food_name = None\n discount = discount_entry.get()\n if (discount_entry.get() == \"\"):\n discount = None\n cat_id = -1\n if (cat_cambo.get()==\"None\"):\n cat_id = None\n else:\n cat_id = cat_cambo.get()[0]\n print (price_l)\n print (price_h)\n print (food_name)\n print (discount)\n print (cat_id)\n foods = mydb.searchFood(price_l, price_h, food_name, discount, cat_id)\n if (len(foods) != 0):\n Label(self.search_food_screen, text=\"Result for your search\", bg=\"red\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n tree=Treeview(self.search_food_screen,style=\"mystyle.Treeview\")\n tree[\"columns\"]=(\"one\",\"two\",\"three\", \"four\", \"five\", \"six\")\n #set tree columns\n tree.column(\"#0\", width=150, minwidth=150, stretch=tk.NO)\n tree.column(\"one\", width=400, minwidth=200)\n tree.column(\"two\", width=80, minwidth=50, stretch=tk.YES)\n tree.column(\"three\", width=80, minwidth=50, stretch=tk.YES)\n tree.column(\"four\", width=80, minwidth=50, stretch=tk.YES)\n tree.column(\"five\", width=80, minwidth=50, stretch=tk.YES)\n tree.column(\"six\", width=80, minwidth=50, stretch=tk.YES)\n #set tree's heading\n tree.heading(\"#0\", text=\"Name\",anchor=tk.W)\n tree.heading(\"one\", text=\"Price\",anchor=tk.W)\n tree.heading(\"two\", text=\"About\",anchor=tk.W)\n tree.heading(\"three\", text=\"Category\",anchor=tk.W)\n tree.heading(\"four\", text=\"Image\",anchor=tk.W)\n tree.heading(\"five\", text=\"Discount\",anchor=tk.W)\n tree.heading(\"six\", text=\"Resturant\",anchor=tk.W)\n tree.pack()\n for i in range(len(foods)):\n tree.insert(\"\", i+1, text=foods[i][1], values=(foods[i][2], foods[i][3], foods[i][5],0, foods[i][4], foods[i][6]))\n tree.bind(\"\", partial(self.OnDoubleClickOnFood,tree, foods))\n\n\n\n def showRestaurantsBySearch(self, city_combo, shop_name_entry, min_bill_entry):\n city_id = -1\n if (city_combo.get() == \"None\"):\n city_id = None\n else:\n city_id = mydb.addCity(city_combo.get())\n min_bill = min_bill_entry.get()\n if (min_bill_entry.get() == \"\"):\n min_bill = None\n shop_name = shop_name_entry.get()\n if (shop_name_entry.get() == \"\"):\n shop_name = None\n\n resturants = mydb.searchShop(city_id, shop_name, min_bill)\n # print (resturants)\n self.searched_resturant_screen = Tk()\n self.searched_resturant_screen.title(\"Results\")\n tree=Treeview(self.searched_resturant_screen,style=\"mystyle.Treeview\")\n tree[\"columns\"]=(\"one\",\"two\",\"three\", \"four\")\n #set tree columns\n tree.column(\"#0\", width=270, minwidth=270, stretch=tk.NO)\n tree.column(\"one\", width=150, minwidth=150, stretch=tk.NO)\n tree.column(\"two\", width=400, minwidth=200)\n tree.column(\"three\", width=80, minwidth=50, stretch=tk.YES)\n tree.column(\"four\", width=80, minwidth=50, stretch=tk.YES)\n #set tree's heading\n tree.heading(\"#0\",text=\"Name\",anchor=tk.W)\n tree.heading(\"one\", text=\"About\",anchor=tk.W)\n tree.heading(\"two\", text=\"min bill value\",anchor=tk.W)\n tree.heading(\"three\", text=\"address\",anchor=tk.W)\n tree.heading(\"four\", text=\"Rate\",anchor=tk.W)\n list_of_resturant_in_treeview = []\n for i in range(len(resturants)):\n rate = mydb.calculateRate(resturants[i][0])\n resturant_in_treeview = tree.insert(\"\", i+1, text=resturants[i][1], values=(resturants[i][2], resturants[i][3], \n self.make_address_str(resturants[i][4]), \"--\" if rate[0][0] == None else rate[0][0]))\n list_of_resturant_in_treeview.append(resturant_in_treeview)\n # for resturant in list_of_resturant_in_treeview:\n # index = list_of_resturant_in_treeview.index(resturant)\n # shop_id = resturants[index][0]\n # shop_foods = mydb.showFoodsOfShop(shop_id)\n \n tree.pack(side=tk.TOP,fill=tk.X)\n tree.bind(\"\", partial(self.OnDoubleClick,tree, resturants))\n \n def profilePage(self):\n def showAddress():\n self.current_address_screen = Tk()\n addresses = mydb.showUserAddress(self.user_id)\n # print (addresses)\n print (addresses)\n for i in range(len(addresses)):\n # print (addresses[i])\n Label(self.current_address_screen, text=\"Address #\"+str(i+1)+\":\").pack()\n address_str = \"\"\n address_str+=addresses[i][0] + \", \"\n for j in range(2,6):\n address_str += addresses[i][j] + \", \"\n Label(self.current_address_screen, text=address_str).pack()\n Button(self.current_address_screen, text=\"Delete this address\",command=partial(self.deleteAddress, addresses[i][1])).pack()\n self.profile = Tk()\n self.profile.title(\"User Profile\")\n self.profile.geometry(\"700x1000\")\n \n \n \"\"\"\n in this section we will show the user his/her information and he or she can change it \n ##########################################################3\n \"\"\"\n Label(self.profile, text=\"Your information\", bg=\"red\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n user_information = mydb.showUser(self.user_id)\n print (user_information)\n # Show your firstname and edit\n Label(self.profile, text=\"You FirstName:\").pack()\n firstname_entry = Entry(self.profile)\n firstname_entry.pack()\n firstname_entry.insert(END, user_information[0][1])\n # Show your lastname and edit\n Label(self.profile, text=\"You Lastname:\").pack()\n lastname_entry = Entry(self.profile)\n lastname_entry.pack()\n lastname_entry.insert(END, user_information[0][2])\n # Show your phone number and edit\n Label(self.profile, text=\"You Phone Number:\").pack()\n phone_number_entry = Entry(self.profile)\n phone_number_entry.pack()\n phone_number_entry.insert(END, user_information[0][3])\n # Show your email address and edit\n Label(self.profile, text=\"You email address:\").pack()\n email_address_entry = Entry(self.profile)\n email_address_entry.pack()\n email_address_entry.insert(END, user_information[0][4])\n # Show your password and edit\n Label(self.profile, text=\"You Password:\").pack()\n password_entry = Entry(self.profile)\n password_entry.pack()\n password_entry.insert(END, user_information[0][5])\n # Change button\n self.user_id = user_information[0][0]\n Button(self.profile,text=\"Change my information\", height=\"2\", width=\"30\", command=partial(self.updateUserInformation, user_information[0][0],\n firstname_entry, lastname_entry, phone_number_entry, email_address_entry, password_entry)).pack()\n # print (email_address_entry.get())\n sep1= Separator(self.profile, orient=tk.HORIZONTAL)\n sep1.pack(anchor=\"nw\", fill=tk.X, pady=4)\n \"\"\"\n ########################################################## \n \"\"\"\n \n \"\"\"\n in this section we will show the user address\n ##########################################################3\n \"\"\"\n Label(self.profile, text=\"Address Management\", bg=\"red\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n show_address_button = Button(self.profile, text=\"Show Current added address\", command=showAddress)\n show_address_button.pack()\n \n add_address_button = Button(self.profile, text=\"Add Address\", command=self.addAddress)\n add_address_button.pack()\n \n edit_address_button = Button(self.profile, text=\"Edit Exists Address\", command=self.editAddresses)\n edit_address_button.pack()\n \"\"\"\n ########################################################## \n \"\"\"\n \n def deleteAddress(self, address_id):\n # print (address_id)\n mydb.deletAddress(address_id)\n\n\n def editAddresses(self):\n def updateAddress(i, x_entry, y_entry,city_combo, street_entry, alley_entry, plaque_entry, address_text_entry):\n\n x = x_entry.get()\n if (x_entry.get() == \"\"):\n x = None\n y = y_entry.get()\n\n if (y_entry.get() == \"\"):\n y = None\n \n if (city_combo.get() == \"None\"):\n city_id = None\n else :\n city_id = int(city_combo.get()[0])\n\n street = street_entry.get()\n if (street_entry.get()==\"\"):\n street = None\n \n alley = alley_entry.get()\n if (alley_entry.get()==\"\"):\n alley = None\n\n plaque = plaque_entry.get()\n if (plaque_entry.get() == \"\"):\n plaque = None\n \n address_text = address_text_entry.get()\n if (address_text_entry==\"\"):\n address_text = None\n mydb.updateAddress(i, x, y, city_id, street, alley, plaque, address_text)\n addresses = mydb.showUserAddress(self.user_id)\n print (addresses)\n self.edit_address_screen = Tk()\n self.edit_address_screen.title(\"Edit Address\")\n for i in range(len(addresses)):\n # print (i)\n # print (type(i))\n Label(self.edit_address_screen, text=\"Address#\"+str(i+1)).pack()\n # show x\n Label(self.edit_address_screen, text=\"Address x:\").pack()\n x_entry = Entry(self.edit_address_screen)\n x_entry.pack()\n # Show y\n Label(self.edit_address_screen, text=\"Address y:\").pack()\n y_entry = Entry(self.edit_address_screen)\n y_entry.pack()\n # Show city\n Label(self.edit_address_screen, text=\"Choose your city, if not please select None\").pack()\n city_combo = Combobox(self.edit_address_screen)\n cities = mydb.showAllCity()\n cities_list = []\n cities_list.append(\"None\")\n \n for city in cities:\n cities_list.append(str(city[0]) + \" \" +city[1])\n \n city_combo['values']= cities_list\n city_combo.pack()\n city_combo.current(0)\n # Show Street\n Label(self.edit_address_screen, text=\"Address Street:\").pack()\n street_entry = Entry(self.edit_address_screen)\n street_entry.pack()\n # Show Alley\n Label(self.edit_address_screen, text=\"Address Alley:\").pack()\n alley_entry = Entry(self.edit_address_screen)\n alley_entry.pack()\n # Show Plaque\n Label(self.edit_address_screen, text=\"Address plaque:\").pack()\n plaque_entry = Entry(self.edit_address_screen)\n plaque_entry.pack()\n # Show Address text\n Label(self.edit_address_screen, text=\"Address Text:\").pack()\n address_text_entry = Entry(self.edit_address_screen)\n address_text_entry.pack()\n # Change button\n Button(self.edit_address_screen,text=\"Change my information\", height=\"2\", width=\"30\", command=\n partial(updateAddress, addresses[i][1], x_entry, y_entry,city_combo, street_entry, alley_entry, plaque_entry, address_text_entry)).pack()\n # print (email_address_entry.get())\n\n\n\n def addAddress(self):\n def addNewAddress():\n mydb.addAddress(x_entry.get(), y_entry.get(), self.user_id, mydb.addCity(city_combo.get()), street_entry.get()\n ,alley_entry.get(), plaque_entry.get(), other_information_entry.get())\n self.add_address_screen = Tk()\n self.add_address_screen.title(\"Adding new address\")\n self.add_address_screen.geometry(\"700x500\")\n Label(self.add_address_screen, text=\"First select your city and then\").pack()\n city_combo = Combobox(self.add_address_screen)\n cities = mydb.showAllCity()\n cities_list = []\n for i in cities:\n cities_list.append(i[1])\n city_combo['values']= cities_list\n city_combo.pack()\n Label(self.add_address_screen, text=\"X:\").pack()\n x_entry = Entry(self.add_address_screen)\n x_entry.pack()\n Label(self.add_address_screen, text=\"Y:\").pack()\n y_entry = Entry(self.add_address_screen)\n y_entry.pack()\n Label(self.add_address_screen, text=\"Street:\").pack()\n street_entry = Entry(self.add_address_screen)\n street_entry.pack()\n Label(self.add_address_screen, text=\"Alley:\").pack()\n alley_entry = Entry(self.add_address_screen)\n alley_entry.pack()\n Label(self.add_address_screen, text=\"Plaque:\").pack()\n plaque_entry = Entry(self.add_address_screen)\n plaque_entry.pack()\n Label(self.add_address_screen, text=\"Other information:\").pack()\n other_information_entry = Entry(self.add_address_screen)\n other_information_entry.pack()\n add_address_button = Button(self.add_address_screen, text=\"Add This New Address\", command=addNewAddress)\n add_address_button.pack()\n \n\n\n def updateUserInformation(self, user_id,firstname_entry, lastname_entry, phone_number_entry, email_address_entry, password_entry):\n try:\n mydb.updateUserProfile(user_id, firstname_entry.get(),lastname_entry.get(), phone_number_entry.get(), email_address_entry.get(), password_entry.get()) \n except:\n print (\"can't change the information\")\n Label(self.profile, text=\"Changed seccussful\").pack()\n\n\n\n def OnDoubleClick(self, tree,resturants, event):\n item = tree.identify('item',event.x,event.y)\n resturant_name = tree.item(item,\"text\")\n resturant_id = -1 \n for res in resturants:\n if (res[1] == resturant_name):\n resturant_id = res[0]\n # print (resturant_id)\n foods = mydb.showFoodsOfShop(resturant_id)\n self.menu_screen = Tk()\n self.menu_screen.title(resturant_name+\" Menu\")\n if (len(foods) != 0):\n \n Label(self.menu_screen, text=\"Resturant Menu\", bg=\"red\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n tree=Treeview(self.menu_screen,style=\"mystyle.Treeview\")\n tree[\"columns\"]=(\"one\",\"two\",\"three\", \"four\", \"five\")\n #set tree columns\n tree.column(\"#0\", width=150, minwidth=150, stretch=tk.NO)\n tree.column(\"one\", width=400, minwidth=200)\n tree.column(\"two\", width=80, minwidth=50, stretch=tk.YES)\n tree.column(\"three\", width=80, minwidth=50, stretch=tk.YES)\n tree.column(\"four\", width=80, minwidth=50, stretch=tk.YES)\n tree.column(\"five\", width=80, minwidth=50, stretch=tk.YES)\n #set tree's heading\n tree.heading(\"#0\", text=\"Name\",anchor=tk.W)\n tree.heading(\"one\", text=\"Price\",anchor=tk.W)\n tree.heading(\"two\", text=\"About\",anchor=tk.W)\n tree.heading(\"three\", text=\"Category\",anchor=tk.W)\n tree.heading(\"four\", text=\"Image\",anchor=tk.W)\n tree.heading(\"five\", text=\"Discount\",anchor=tk.W)\n tree.pack()\n for i in range(len(foods)):\n tree.insert(\"\", i+1, text=foods[i][3], values=(foods[i][1], foods[i][2], mydb.showCategoryName(foods[i][6])[0][0], foods[i][5], foods[i][4]))\n tree.bind(\"\", partial(self.OnDoubleClickOnFood,tree, foods))\n\n ######################################\n ######################################\n ######################################\n #LAST FOOD FORM THIS RESTURANT\n ######################################\n ######################################\n ######################################\n last_foods = mydb.showOrderByShop(self.user_id, resturant_id)\n last_foods = list(dict.fromkeys(last_foods))\n # print (last_foods)\n Label(self.menu_screen, text=\"Last orders from this resturant\", bg=\"red\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n tree=Treeview(self.menu_screen,style=\"mystyle.Treeview\")\n tree[\"columns\"]=(\"one\",\"two\",\"three\", \"four\", \"five\")\n #set tree columns\n tree.column(\"#0\", width=150, minwidth=150, stretch=tk.NO)\n tree.column(\"one\", width=400, minwidth=200)\n tree.column(\"two\", width=80, minwidth=50, stretch=tk.YES)\n tree.column(\"three\", width=80, minwidth=50, stretch=tk.YES)\n tree.column(\"four\", width=80, minwidth=50, stretch=tk.YES)\n tree.column(\"five\", width=80, minwidth=50, stretch=tk.YES)\n #set tree's heading\n tree.heading(\"#0\", text=\"Name\",anchor=tk.W)\n tree.heading(\"one\", text=\"Price\",anchor=tk.W)\n tree.heading(\"two\", text=\"About\",anchor=tk.W)\n tree.heading(\"three\", text=\"Category\",anchor=tk.W)\n tree.heading(\"four\", text=\"Image\",anchor=tk.W)\n tree.heading(\"five\", text=\"Discount\",anchor=tk.W)\n tree.pack()\n for i in range(len(last_foods)):\n tree.insert(\"\", i+1, text=last_foods[i][3], values=(last_foods[i][1], last_foods[i][2], mydb.showCategoryName(last_foods[i][6])[0][0], last_foods[i][5], last_foods[i][4]))\n tree.bind(\"\", partial(self.OnDoubleClickOnFood,tree, last_foods))\n \n def OnDoubleClickOnFood(self, tree,foods, event):\n item = tree.identify('item',event.x,event.y)\n food_name = tree.item(item,\"text\")\n food_id = -1\n for food in foods:\n if (food[1] == food_name):\n food_id = food[0]\n break\n #Add the food to cart\n self.cart_id = mydb.addFoodToCart(food_id, self.user_id)\n\n \n\n def showRestaurants(self, all_variables, all_address):\n\n address_id = -1\n for variable in all_variables:\n if (variable.get()):\n index = all_variables.index(variable)\n address_id = all_address[index][1]\n self.address_id = address_id\n resturants = mydb.searchShopByLocation(int(address_id), 100)\n # print (resturants)\n self.searched_resturant_screen = Tk()\n self.searched_resturant_screen.title(\"Results\")\n tree=Treeview(self.searched_resturant_screen,style=\"mystyle.Treeview\")\n tree[\"columns\"]=(\"one\",\"two\",\"three\", \"four\")\n #set tree columns\n tree.column(\"#0\", width=270, minwidth=270, stretch=tk.NO)\n tree.column(\"one\", width=150, minwidth=150, stretch=tk.NO)\n tree.column(\"two\", width=400, minwidth=200)\n tree.column(\"three\", width=400, minwidth=200, stretch=tk.YES)\n tree.column(\"four\", width=80, minwidth=50, stretch=tk.YES)\n\n #set tree's heading\n tree.heading(\"#0\",text=\"Name\",anchor=tk.W)\n tree.heading(\"one\", text=\"About\",anchor=tk.W)\n tree.heading(\"two\", text=\"min bill value\",anchor=tk.W)\n tree.heading(\"three\", text=\"address\",anchor=tk.W)\n tree.heading(\"four\", text=\"rate\",anchor=tk.W)\n list_of_resturant_in_treeview = []\n for i in range(len(resturants)):\n rate = mydb.calculateRate(resturants[i][0])[0][0]\n resturant_in_treeview = tree.insert(\"\", i+1, text=resturants[i][1], values=(resturants[i][2], resturants[i][3], self.make_address_str(resturants[i][4]), \"-\" if rate== None else rate))\n list_of_resturant_in_treeview.append(resturant_in_treeview)\n tree.pack(side=tk.TOP,fill=tk.X)\n tree.bind(\"\", partial(self.OnDoubleClick,tree, resturants))\n\n \n def restaurantsPage(self): \n self.address_selection_screen = Tk()\n self.address_selection_screen.title(\"Your addresses\")\n self.address_selection_screen.geometry(\"700x500\")\n Label(self.address_selection_screen, text=\"Choose an address to find the nearest resturant to you\", bg=\"yellow\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n all_address = mydb.showUserAddress(self.user_id)\n # print (all_address)\n all_variables = []\n\n list_of_address_str = []\n for address in all_address:\n address_str = \"\"\n for part in address[1:-2]:\n address_str += str(part) + \", \"\n list_of_address_str.append(address_str)\n vari = IntVar(self.address_selection_screen)\n all_variables.append(vari)\n Checkbutton(self.address_selection_screen, text=address_str, variable=vari).pack() \n Button(self.address_selection_screen, text=\"Submit\", command=partial(self.showRestaurants, all_variables, all_address) ).pack()\n\n\n def make_address_str(self, address_id):\n address_info = mydb.showAddress(address_id)\n address_info = address_info[0]\n address_str = address_info[0] + \", \"\n # print (address_info)\n for i in range(2,6):\n address_str += address_info[i] + \", \"\n # print (address_str)\n return address_str\n\n def make_foods_str(self, foods_list):\n food_str_dict = {}\n for food in foods_list:\n food_str = mydb.showFoods([food])[0][3]\n if food_str in food_str_dict.keys():\n food_str_dict[food_str] += 1\n else:\n food_str_dict[food_str] = 1\n\n return_str = \"\"\n for food_name in list(food_str_dict.keys()):\n return_str += food_name + \": \"\n return_str += str(food_str_dict[food_name]) + \" \"\n return return_str\n\n def saveComment(self, order_id, comment_entry, rate_entry):\n mydb.addComment(order_id, rate_entry.get(), comment_entry.get())\n\n\n def orderPage(self):\n def OnDoubleClickOnOrder(tree, orders_list, event):\n item = tree.identify('item',event.x,event.y)\n order_number = tree.item(item,\"text\")\n \n order_id = orders_list [int(order_number[-1]) - 1]\n self.order_comment_page = Tk()\n self.order_comment_page.title(\"Comment\")\n Label(self.order_comment_page, text=\"Comment on this order\", bg=\"yellow\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n Label(self.order_comment_page, text=\"Your comment:\").pack()\n comment_entry = Entry(self.order_comment_page)\n comment_entry.pack()\n Label(self.order_comment_page, text=\"Your rating to this order(from 0 to 100):\").pack()\n rate_entry = Entry(self.order_comment_page)\n rate_entry.pack()\n Button(self.order_comment_page, text=\"comment this\", command=partial(self.saveComment, order_id, comment_entry, rate_entry)).pack()\n\n\n \n\n def showHistoryOfOrders():\n self.history_of_orders_screen = Tk()\n self.history_of_orders_screen.title(\"Hisotry of orders\")\n Label(self.history_of_orders_screen, text=\"History of orders, click on them to comment\", bg=\"yellow\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n tree=Treeview(self.history_of_orders_screen, style=\"mystyle.Treeview\")\n tree[\"columns\"]=(\"one\",\"two\",\"three\")\n #set tree columns\n tree.column(\"#0\", width=270, minwidth=270, stretch=tk.NO)\n tree.column(\"one\", width=150, minwidth=150, stretch=tk.NO)\n tree.column(\"two\", width=400, minwidth=200)\n tree.column(\"three\", width=80, minwidth=50, stretch=tk.YES)\n #set tree's heading\n tree.heading(\"#0\",text=\"Order#\",anchor=tk.W)\n tree.heading(\"one\", text=\"Total Price\",anchor=tk.W)\n tree.heading(\"two\", text=\"Address\",anchor=tk.W)\n tree.heading(\"three\", text=\"Foods\",anchor=tk.W)\n history_of_orders = mydb.showBuyHistory(self.user_id)\n invoic_dict = {}\n for history in history_of_orders:\n if ((history[0],history[1],history[2]) in invoic_dict.keys()):\n invoic_dict[(history[0],history[1],history[2])].append(history[3])\n else:\n invoic_dict[(history[0],history[1],history[2])] = []\n invoic_dict[(history[0],history[1],history[2])].append(history[3])\n \n # print (type(list(invoic_dict.keys())))\n # print (invoic_dict)\n\n tree.pack(side=tk.TOP,fill=tk.X)\n orders_list = []\n for key in invoic_dict.keys():\n orders_list.append(key[0])\n for i in range(len(list(invoic_dict.keys()))):\n address_id = list(invoic_dict.keys())[i][2]\n foods_list = invoic_dict[list(invoic_dict.keys())[i]]\n print (foods_list)\n tree.insert(\"\", i+1, text=\"Order#\"+str(i+1), values=(list(invoic_dict.keys())[i][1], self.make_address_str(address_id), self.make_foods_str(foods_list)))\n # resturant_in_treeview = tree.insert(\"\", i+1, text=resturants[i][1], values=(resturants[i][2], resturants[i][3], make_address_str(resturants[i][4])))\n # list_of_resturant_in_treeview.append(resturant_in_treeview)\n tree.bind(\"\", partial(OnDoubleClickOnOrder,tree, orders_list))\n \n \n def finilizeCart(discount_code):\n # print (self.address_id)\n self.ivoice_id = mydb.finalizeCart(self.user_id, self.address_id, discount_code.get())\n\n def showAllOrders():\n self.all_orders_screen = Tk()\n self.all_orders_screen.title(\"All Orders\")\n all_history = mydb.showAllHistory(self.user_id)\n print (all_history)\n Label(self.all_orders_screen, text=\"All your orders\", bg=\"yellow\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n tree=Treeview(self.all_orders_screen, style=\"mystyle.Treeview\")\n tree[\"columns\"]=(\"one\",\"two\",\"three\", \"four\")\n #set tree columns\n tree.column(\"#0\", width=270, minwidth=270, stretch=tk.NO)\n tree.column(\"one\", width=150, minwidth=150, stretch=tk.NO)\n tree.column(\"two\", width=400, minwidth=200)\n tree.column(\"three\", width=80, minwidth=50, stretch=tk.YES)\n tree.column(\"four\", width=80, minwidth=50, stretch=tk.YES)\n #set tree's heading\n tree.heading(\"#0\",text=\"Order#\",anchor=tk.W)\n tree.heading(\"one\", text=\"Total Price\",anchor=tk.W)\n tree.heading(\"two\", text=\"Address\",anchor=tk.W)\n tree.heading(\"three\", text=\"Status\",anchor=tk.W)\n tree.heading(\"four\", text=\"Foods\",anchor=tk.W)\n invoic_dict = {}\n print(all_history)\n for history in all_history:\n if ((history[0],history[1],history[2], history[4]) in invoic_dict.keys()):\n invoic_dict[(history[0],history[1],history[2], history[4])].append(history[3])\n else:\n invoic_dict[(history[0],history[1],history[2], history[4])] = []\n invoic_dict[(history[0],history[1],history[2], history[4])].append(history[3])\n \n # print (type(list(invoic_dict.keys())))\n print (invoic_dict)\n\n tree.pack(side=tk.TOP,fill=tk.X)\n orders_list = []\n for key in invoic_dict.keys():\n orders_list.append(key[0])\n for i in range(len(list(invoic_dict.keys()))):\n address_id = list(invoic_dict.keys())[i][2]\n foods_list = invoic_dict[list(invoic_dict.keys())[i]]\n print (foods_list)\n tree.insert(\"\", i+1, text=\"Order#\"+str(i+1), values=(list(invoic_dict.keys())[i][1], self.make_address_str(address_id),list(invoic_dict.keys())[i][3] ,self.make_foods_str(foods_list)))\n # resturant_in_treeview = tree.insert(\"\", i+1, text=resturants[i][1], values=(resturants[i][2], resturants[i][3], make_address_str(resturants[i][4])))\n # list_of_resturant_in_treeview.append(resturant_in_treeview)\n\n\n self.order_screen = Tk()\n self.order_screen.title(\"Orders Page\")\n Label(self.order_screen, text=\"Finilize your Cart\", bg=\"red\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n Label(self.order_screen, text=\"enter your discount code if you have one\").pack()\n discount_code = Entry(self.order_screen)\n discount_code.pack()\n Button(self.order_screen,text=\"Buy your Cart\", height=\"2\", width=\"30\", command=partial(finilizeCart, discount_code)).pack()\n Label(self.order_screen, text=\"Your Orders History (Compeleted)\", bg=\"red\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n Button(self.order_screen,text=\"history of orders\", height=\"2\", width=\"30\", command=showHistoryOfOrders).pack()\n Label(self.order_screen, text=\"Your All Orders\", bg=\"red\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(text=\"\").pack()\n Button(self.order_screen,text=\"All Orders\", height=\"2\", width=\"30\", command=showAllOrders).pack()\n\nroot = Tk()\nmy_gui = Application(root)\nroot.mainloop()","repo_name":"miladbarooni/SnapFoodDB","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":41008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"34151288700","text":"class Solution:\n def findPeakElement(self, nums: List[int]) -> int:\n left, right = 0, len(nums)-1\n while left <= right: \n mid = (left + right) // 2\n cen = nums[mid]\n bef = nums[mid-1] if mid-1 >= 0 else -float('inf')\n aft = nums[mid+1] if mid+1 < len(nums) else -float('inf')\n if bef < cen and cen > aft: \n return mid\n elif bef < cen and cen < aft:\n left = mid + 1\n elif bef > cen and cen < aft:\n left = mid + 1\n else:\n right = mid - 1\n ","repo_name":"Roha-Lee/Algorithm-Study","sub_path":"LeetCode/Algorithm_II/Day2/162_find_peek_element.py","file_name":"162_find_peek_element.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"42123437167","text":"import os\nfrom pathlib import Path\n\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\n\nENVIRONMENT = os.environ.get('ENVIRONMENT')\n\nSECRET_KEY = os.environ.get('SECRET_KEY')\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\n\nALLOWED_HOSTS = ['twitter-clone-ben.herokuapp.com', 'localhost', '127.0.0.1']\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'whitenoise.runserver_nostatic',\n 'django.contrib.staticfiles',\n 'django.contrib.sites',\n \n # THIRD-PARTY\n 'crispy_forms',\n 'notifications',\n 'allauth',\n 'allauth.account',\n 'allauth.socialaccount',\n 'allauth.socialaccount.providers.google',\n \n # LOCAL\n 'users.apps.UsersConfig',\n 'pages.apps.PagesConfig',\n 'tweets.apps.TweetsConfig',\n]\n\n\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'twitter_project.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [ BASE_DIR / 'templates' ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'twitter_project.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/3.2/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': 'postgres',\n 'USER': 'postgres',\n 'PASSWORD': 'postgres',\n 'HOST': 'db',\n 'PORT': 5432\n }\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/3.2/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/3.2/howto/static-files/\n\nSTATIC_ROOT = BASE_DIR / 'staticfiles'\nSTATIC_URL = '/static/'\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n\n# Default primary key field type\n# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field\n\nDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'\n\nAUTH_USER_MODEL = 'users.CustomUser'\n\nACCOUNT_EMAIL_REQUIRED = True\n\n# django-allauth config\nSITE_ID = 1\n\nSOCIALACCOUNT_AUTO_SIGNUP = False\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'allauth.account.auth_backends.AuthenticationBackend',\n)\n\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\nLOGIN_REDIRECT_URL = 'home'\nLOGOUT_REDIRECT_URL = 'home'\n\nCRISPY_TEMPLATE_PACK = 'bootstrap4'\n\nSOCIALACCOUNT_PROVIDERS = {\n 'google': {\n 'SCOPE': [\n 'profile',\n 'email',\n ],\n 'AUTH_PARAMS': {\n 'access_type': 'online',\n }\n }\n}\n\nif os.environ.get('ENVIRONMENT') is not None:\n SECURE_BROWSER_XSS_FILTER = True\n X_FRAME_OPTIONS = 'DENY'\n SECURE_SSL_REDIRECT = True\n SECURE_HSTS_SECONDS = 3600\n SECURE_HSTS_INCLUDE_SUBDOMAINS = True\n SECURE_HSTS_PRELOAD = True\n SECURE_CONTENT_TYPE_NOSNIFF = True\n SESSION_COOKIE_SECURE = True\n CSRF_COOKIE_SECURE = True\n SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\nelse:\n DEBUG = True\n \nimport dj_database_url\ndb_from_env = dj_database_url.config(conn_max_age=500) \nDATABASES['default'].update(db_from_env)","repo_name":"bengy3d/Twitter_Clone_Django","sub_path":"twitter_project/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"12168840123","text":"class Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n na = []\n for n in nums:\n na.append(n**2)\n \n # n = len(nums)\n # for i in range(n-1):\n # for j in range(0,n- i - 1):\n # if na[j] > na[j + 1]:\n # na[j], na[j + 1] = na[j + 1], na[j]\n # return na\n return sorted(na)\n \n ","repo_name":"jasonz23/LeetCode-submissions","sub_path":"977-squares-of-a-sorted-array/977-squares-of-a-sorted-array.py","file_name":"977-squares-of-a-sorted-array.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"32060666518","text":"import os\nimport time\nfrom datetime import datetime\nfrom itertools import islice\nfrom pathlib import Path\n\nimport gurobipy\nimport networkx as nx\nfrom matplotlib import pyplot as plt\n\n\ndef print_flow(cost: float, flow: dict, merged: bool, max_values_printed=20):\n \"\"\"Print at most `max_values_printed` of the flow `flow`, together with its value `cost` (or its value before it\n was merged, in the case of `merged=True`).\"\"\"\n print(\"---------------------------------------------\")\n # Merging antiparallel flows will typically reduce the cost slightly. As `cost` is the cost\n # of the unmerged flow it will then be a slight overapproximation of the cost of the merged flow.\n print(f\"Obtained solution of value {'at most' if merged else ''} {cost}:\")\n for name, value in islice(flow.items(), max_values_printed):\n print(f\"\\t{name}: {value}\")\n if len(flow) > max_values_printed:\n print(f\"\\t... ({len(flow) - max_values_printed} more elements)\")\n print(\"---------------------------------------------\")\n\n\ndef plot_flow(flow: dict, G: nx.Graph):\n \"\"\"Plot `flow` as a heatmap on the graph `G` that it acts.\"\"\"\n for i in range(G.graph[\"k\"]):\n Gi = nx.DiGraph()\n edge_intensity, edge_use = [], {}\n for u, v, attr in G.edges(data=True):\n ui, vi = f\"{u}'{i}\", f\"{v}'{i}\"\n if f\"x_{(ui, vi)}\" in flow:\n Gi.add_edge(u, v)\n edge_use[(u, v)] = flow[f\"x_{(ui, vi)}\"] / attr[\"u\"]\n edge_intensity.append(edge_use[(u, v)])\n else:\n Gi.add_edge(v, u)\n edge_use[(v, u)] = flow[f\"x_{(vi, ui)}\"] / attr[\"u\"]\n edge_intensity.append(edge_use[(v, u)])\n node_color = [\"#008000\" if \"c\" in G.nodes[node] or \"cr\" in G.nodes[node] else \"#1f78b4\" for node in Gi.nodes]\n edge_labels = {edge: f\"{round(use * 100)}%\" for edge, use in edge_use.items()}\n plt.title(f\"Edge utilization (teal = 0%, pink = 100%) at time-step {i + 1},\\n\"\n f\"with source nodes marked in green\")\n # G is used over Gi for positioning as this makes for a much more nicely and evenly spread-out graph\n pos = nx.spring_layout(G)\n if len(Gi.nodes) < 20:\n nx.draw_networkx(Gi, pos, node_color=node_color,\n edge_cmap=plt.get_cmap(\"cool\"), edge_color=edge_intensity, edge_vmin=0, edge_vmax=1)\n nx.draw_networkx_edge_labels(Gi, pos, edge_labels=edge_labels, font_size=8)\n else:\n nx.draw_networkx(Gi, pos, node_size=50, with_labels=False, node_color=node_color,\n edge_cmap=plt.get_cmap(\"cool\"), edge_color=edge_intensity, edge_vmin=0, edge_vmax=1)\n safe_savefig(\"output/algorithm\", f\"{time.time()}.pdf\")\n plt.show()\n\n\ndef plot_graph(graph: nx.Graph | nx.DiGraph):\n \"\"\"Save and show a plot of `graph`.\"\"\"\n nx.draw_networkx(graph)\n safe_savefig(\"output/algorithm\", f\"{graph.graph['name']}_{time.time()}.pdf\")\n plt.show()\n\n\ndef safe_savefig(outdir: str, filename: str):\n \"\"\"Create `outdir` if it doesn't exist. Then save the current pyplot figure to `Path(outdir) / filename`.\"\"\"\n os.makedirs(outdir, exist_ok=True)\n plt.savefig(Path(outdir) / filename, bbox_inches='tight')\n\n\ndef safe_savemodel(outdir: str, model: gurobipy.Model):\n \"\"\"Create `outdir` if it doesn't exist. Then save `model` to `Path(outdir) / \"model.lp\"`.\"\"\"\n os.makedirs(outdir, exist_ok=True)\n model.write(f\"{outdir}/model.lp\")\n\n\ndef print_with_seconds_elapsed_since(text_before: str, start_time: datetime):\n print(f\"{text_before}{(datetime.now()-start_time).total_seconds():.2} seconds.\")\n","repo_name":"JaHeRoth/SimplifiedDOPFSolver","sub_path":"algorithm/outputting.py","file_name":"outputting.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"7331028459","text":"from matplotlib import pyplot as plt\nimport pandas as pd\nimport seaborn as sns\n\n\n# fig1\ndf = pd.read_csv(\"WorldCupMatches.csv\")\n\n# DataFrame添加列\ndf[\"Total Goals\"] = df[\"Home Team Goals\"] + df[\"Away Team Goals\"]\nprint(df.head(10))\nsns.set_style(\"whitegrid\")\nsns.set_context(\"poster\", font_scale=0.6)\nf, ax = plt.subplots(figsize=(12, 7))\n# ax = sns.barplot(data=df, x=\"Year\", y=\"Total Goals\")\nax = sns.barplot(data=df, x=\"Year\", y=\"Total Goals\")\nax.set_title(\"Goals in each match\")\n\n# plt.show()\n\n# fig2\ndf_goals = pd.read_csv(\"goals.csv\")\nprint(df_goals.head())\nsns.set_context(\"notebook\", font_scale=1.25)\nsns.set_palette(\"Spectral\")\nf,ax2 = plt.subplots(figsize=(12, 7))\nax2 = sns.boxplot(x=df_goals[\"year\"], y=df_goals[\"goals\"])\nax2.set_title(\"Goals\")\n\nplt.show()\n","repo_name":"gzj1000xp/py_study","sub_path":"seaborn&numpy/worldcup.py","file_name":"worldcup.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"23572336462","text":"\n\n\ndef index(i: int, exp: int) -> int:\n return int((i/exp) % 10)\n\n\n\n\n\n\ndef counting_sort(array: list, n: int, exp: int) -> list:\n\n count = [0] * (10+1)\n\n for j in range(n):\n count[index(array[j], exp)] += 1\n\n for i in range(1, 10+1):\n count[i] += count[i-1]\n\n out = [None] * n\n for j in range(n-1, -1, -1):\n out[count[index(array[j], exp)]-1] = array[j]\n count[index(array[j], exp)] -= 1\n\n\n return out\n\n\n\n\n\n\ndef radix_sort(array: list) -> None:\n\n maximum_num = max(array)\n\n exp = 1\n while maximum_num/exp > 0:\n res = counting_sort(array, len(array), exp)\n for i in range(len(array)):\n array[i] = res[i]\n exp *= 10\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n\n print(\"\\n\\n ---------------- \\n\")\n print(\"a simple test:\\n\")\n \n\n array = [2, 10, 44, 0, 1, 23, 11, 77, 50, 100, 7, 16, 2, 11]\n print(f\"before sort: {array}\")\n\n radix_sort(array)\n print(f\"after sort: {array}\")\n\n\n print(\"\\n ---------------- \\n\\n\")","repo_name":"MmahdiM79/Algorithms-and-Data-structures","sub_path":"Algorithms/radix sort/radix_sort.py","file_name":"radix_sort.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"41"} +{"seq_id":"15248532173","text":"from . import Constants\n\n\ndef get_rotated_coordinate(coor, rotation):\n \"\"\"\n Rotate the coordinate by the given rotation.\n Args:\n coor: the coordinate x, y tuple\n rotation: the angle in degrees\n Returns:\n the rotated coordinates\n \"\"\"\n # handles negative angles\n rotation = (rotation + 360) % 360\n if rotation not in Constants.POSSIBLE_ROTATIONS:\n raise ValueError('unusable rotation angle \"%s\"'%str(rotation))\n # determine the number of degrees to rotate\n cos_r, sin_r = {\n 0: (1, 0), 90: (0, 1), 180: (-1, 0), 270: (0, -1),\n }[rotation]\n x, y = coor\n return x * cos_r + y * sin_r, -x * sin_r + y * cos_r\n","repo_name":"marcnewlin/gnuradio-web","sub_path":"grc-dev/gnuradio/grc/gui_qt/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"41"} +{"seq_id":"6290552512","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('contact', views.contact, name = 'contact'),\n path('search', views.search, name = 'search'),\n path(\"signup\", views.signup, name='signup'),\n path(\"login\", views.loginPage, name='login'),\n path(\"logout\", views.logoutPage, name='logout'),\n path(\"postComment/\", views.postComment, name = 'postComment'), \n]","repo_name":"karan20210/BlogZy","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"72505462844","text":"import time\nfrom sqlalchemy import select\n\nimport src.sqlalchemy.models as models\nfrom src.sqlalchemy.base import Base\nfrom src.core.db import scoped_session\n\n\nclass Annotation(Base):\n \n def __init__(self, db: scoped_session) -> None:\n super().__init__(db)\n\n def find_or_create_annotation(self, device_id: int, session_id: int) -> models.Annotation:\n \"\"\"\n Description:\n * Finds or creates an annotation for a given device_id.\n \n Args:\n * device_id (int): The device_id to find or create an annotation for.\n * session_id (int): The session_id to find or create an annotation for.\n \n Returns:\n * annotation (Annotation): The annotation for the given device_id.\n \"\"\"\n\n # Tries to find the annotation record for the given device_id\n statement = (\n select(models.Annotation).where(\n (models.Annotation.session_id == session_id) &\n (models.Annotation.device_id == device_id))\n )\n annotation = self.db.execute(statement).all()\n\n # If not found, creates a new annotation record\n if annotation is None or len(annotation) < 1:\n annotation = models.Annotation(\n session_id=session_id,\n device_id=device_id,\n )\n\n self.db.add(annotation)\n self.db.flush()\n\n else:\n # The db will return a list of tuples with the first element being the annotation record\n annotation = annotation[0][0]\n\n return annotation\n \n def find_annotation_segment(self, device_id: int, session_id: int, start_event: int) -> models.AnnotationSegment:\n \"\"\"\n Description:\n * Finds an annotation segment for a given device_id and start_event.\n\n Args:\n * device_id (int): The device_id to find the annotation segment for.\n * session_id (int): The session_id to find the annotation segment for.\n * start_event (int): The start_event to find the annotation segment for.\n\n Returns:\n * segment (AnnotationSegment): The annotation segment for the given device_id and start_event.\n \"\"\"\n annotation = self.find_or_create_annotation(device_id, session_id)\n\n statement = (\n select(models.AnnotationSegment).where(\n (models.AnnotationSegment.annotation_id == annotation.id) &\n (models.AnnotationSegment.event_start == start_event)\n )\n )\n segment = self.db.execute(statement).all()\n\n if segment is None or len(segment) < 1:\n segment = models.AnnotationSegment(\n annotation_id=annotation.id,\n event_start=start_event,\n event_end=start_event + 20\n )\n\n self.db.add(segment)\n self.db.flush()\n else:\n # The db will return a list of tuples with the first element being the annotation record\n segment = segment[0][0]\n\n return segment\n \n def find_or_create_annotation_segment(self, annotation_id: int, start_event: int, end_event: int) -> models.AnnotationSegment:\n \"\"\"\n Description:\n * Finds or creates an annotation segment for a given annotation_id.\n\n Args:\n * annotation_id (int): The annotation_id to find or create an annotation segment for.\n * start_event (int): The start_event to find or create an annotation segment for.\n * end_event (int): The end_event to find or create an annotation segment for.\n\n Returns:\n * segment (AnnotationSegment): The annotation segment for the given annotation_id.\n \"\"\"\n\n statement = (\n select(models.AnnotationSegment).where(models.AnnotationSegment.annotation_id == annotation_id)\n )\n segment = self.db.execute(statement).all()\n \n segment = models.AnnotationSegment(\n annotation_id=annotation_id,\n event_start=start_event,\n event_end=end_event\n )\n\n self.db.add(segment)\n self.db.flush()\n\n return segment\n \n def upsert_annotation_record(self, type: models.AnnotationType, session_id: int, device_id: int, value: str, start_event: int) -> models.AnnotationRecord:\n \"\"\"\n Description:\n * Upsert an annotation record into the database.\n \n Args:\n * type (AnnotationType): The type of annotation record to upsert.\n * session_id (int): The session_id to upsert the annotation record for.\n * device_id (int): The device_id to upsert the annotation record for.\n * value (str): The value of the annotation record to upsert.\n * start_event (int): The start_event of the annotation record to upsert.\n\n Returns:\n * ann_rec (AnnotationRecord): The new annotation record that was upsert into the database.\n \"\"\"\n # Finds the annotation segment for the given device_id and start_event\n annotation_segment = self.find_annotation_segment(device_id, session_id, start_event)\n ann_rec = models.AnnotationRecord(\n segment_id=annotation_segment.id,\n type=type,\n value=value,\n time=int(time.time())\n )\n\n # Upsert the new annotation into the database\n self.db.merge(ann_rec)\n self.db.flush() \n return ann_rec\n","repo_name":"PatriciaBota/kubesense-perf","sub_path":"results_emotiphai/src/sqlalchemy/annotation.py","file_name":"annotation.py","file_ext":"py","file_size_in_byte":4915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"34151829390","text":"class Solution:\n def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:\n m = len(dungeon)\n n = len(dungeon[0])\n DP_mtx = [[-1e8 for _ in range(n+1)] for _ in range(m+1)]\n \n for j in range(n-1, -1, -1):\n for i in range(m-1, -1, -1):\n value = max(DP_mtx[i+1][j], DP_mtx[i][j+1])\n value = value if not value == -1e8 else 0 \n value += dungeon[i][j]\n value = 0 if value > 0 else value\n DP_mtx[i][j] = value\n if DP_mtx[0][0] >= 0:\n return 1\n else:\n return abs(DP_mtx[0][0]) + 1\n \n \n ","repo_name":"Roha-Lee/Algorithm-Study","sub_path":"LeetCode/DayChallenges/DayChallenge_2021_Oct/174_dungeon_game.py","file_name":"174_dungeon_game.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"32026137674","text":"import os\n\nimport numpy as np\nimport torch\nfrom PIL import Image\nimport subprocess\n\nfrom PNG_SVG_Conversion.png_svg_converter import Raster2SVG_Converter\n\ndef create_icons(model_dir , img_input_dir, img_output_dir):\n \"\"\"\n Function to run an image to image translation and png to svg conversion on all images in the specified input directiory.\n\n Parameters:\n -----------\n model_dir: str\n the specified path to the pretrained model.\n img_input_dir: str\n the specified path to the input directory containing all images.\n img_output_dir: str\n the specified path to the output directory to which the images and svgs are to be saved to.\n \"\"\"\n try:\n # Change paths since directory is changed down below\n img_input_dir = os.path.join(\"..\", img_input_dir)\n img_output_dir = os.path.join(\"..\", img_output_dir)\n\n # Folder name\n folder_name = img_input_dir.split(\"\\\\\")[-1]\n\n # Change directory to CycleGAN location\n os.chdir(\"pytorch-CycleGAN-and-pix2pix/\")\n\n # Set GPU\n gpu_id = 0 if torch.cuda.is_available() else -1\n\n print(\"[Image2Icon]: Running\")\n\n # Iterate through different model save states\n for file in os.listdir(model_dir):\n # Get filename\n filename = os.fsdecode(file)\n if filename.endswith(\".pth\"):\n # Get epoch from filename\n epoch = filename.split(\"_\")[0] \n\n # Define command for CycleGAN\n command = f\"python test.py --dataroot \\\"{img_input_dir}\\\" --name Objects2Icons --model test --results_dir \\\"{img_output_dir}\\\\{folder_name}\\\" --epoch {epoch} --no_dropout --gpu_ids {gpu_id}\"\n \n # Run command \n p = subprocess.run(command, shell=True, capture_output=True)\n\n # Print error code if existent\n if p.returncode != 0:\n print( 'Command:', p.args)\n print( 'exit status:', p.returncode )\n print( 'stdout:', p.stdout.decode() )\n print( 'stderr:', p.stderr.decode() )\n \n print(\"[Image2Icon]: Finished\")\n\n # Create SVG2PNG converter\n converter = Raster2SVG_Converter(vtracer_path=\"..\\\\PNG_SVG_Conversion/vtracer_path.txt\")\n\n # Set checkpoint image directory\n checkpoint_img_dir = os.path.join(img_output_dir, folder_name, \"Objects2Icons\")\n\n print(\"[PNG2SVG]: Running\")\n\n # Iterate through previously translated images\n for image in os.listdir(img_input_dir):\n imagename, format = os.fsdecode(image).split(\".\")\n\n # Iterate though different folders \n for checkpoint in os.listdir(checkpoint_img_dir):\n checkpointname = os.fsdecode(checkpoint)\n\n # Run SVG2PNG conversion\n converter.convert_raster2svg ( \n # your full local input file path\n # input_image_path = os.path.abspath(f\"{img_output_dir}/{folder_name}/Objects2Icons/{checkpointname}/images/{imagename}_fake.{format}\"),\n input_image_path = os.path.abspath(os.path.join(img_output_dir, folder_name, \"Objects2Icons\", checkpointname, \"images\", f\"{imagename}_fake.{format}\")),\n\n # your full local output folder \n # output_folder = os.path.abspath(f\"{img_output_dir}/{folder_name}/SVGs\"),\n output_folder = os.path.abspath(os.path.join(img_output_dir, folder_name, \"SVGs\")),\n \n # filename without .svg extension\n output_filename = imagename + f\"_{checkpointname}\"\n )\n\n print(\"[PNG2SVG]: Finished\")\n \n finally:\n # Change directory back to the beginning state\n os.chdir(\"../\")\n \n\n \n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"aldietri/LogoAI","sub_path":"utils/Icon_Creator_Function.py","file_name":"Icon_Creator_Function.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"38701310806","text":"import logging\n\nfrom picross_solver import Solver\nfrom picross_solver.objects import Field\n\n\ndef test_solver_small():\n # Test with Pictopix's 1st level\n column_constraints = [[0], [1,1], [1,1], [5], [0]]\n row_constraints = [[3], [1], [3], [1], [1]]\n \n newState = Field(column_values=column_constraints,\n row_values=row_constraints)\n \n mySolver = Solver(newState)\n \n num = mySolver.solve()\n print(f\"{num} iterations\")\n print_solved(mySolver)\n \ndef test_solver_big_spin():\n # Test with Pictopix's 83rd level (page 6, 8th, 15x15 \"Flora\" theme)\n # Using SPIN algorithm (should be slower)\n column_constraints = [[2], [2,3], [4,2], [7,2], [4,5], [4,4,2], [4,7], [2,6], [2,5], [4,2,2], [4,8], [4,2,4], [6,3], [4], [2]]\n row_constraints = [[0],[2,2],[4,4],[4,4],[5,5],[2,4,3],[5,1,5],[6,5],[6,2],[5,2],[2,3,3],[2,4,3],[2,8],[2,5],[2]]\n \n mySolver = Solver.from_constraints(column_constraints, row_constraints)\n \n num = mySolver.solve(algo=Solver.SPIN)\n print(f\"{num} iterations\")\n print_solved(mySolver)\n \ndef test_solver_big_spinmem():\n # Test with Pictopix's 83rd level (page 6, 8th, 15x15 \"Flora\" theme)\n # Using SPINMEM algorithm (should be faster, specially for bigger grids)\n column_constraints = [[2], [2,3], [4,2], [7,2], [4,5], [4,4,2], [4,7], [2,6], [2,5], [4,2,2], [4,8], [4,2,4], [6,3], [4], [2]]\n row_constraints = [[0],[2,2],[4,4],[4,4],[5,5],[2,4,3],[5,1,5],[6,5],[6,2],[5,2],[2,3,3],[2,4,3],[2,8],[2,5],[2]]\n \n mySolver = Solver.from_constraints(column_constraints, row_constraints)\n \n num = mySolver.solve()\n print(f\"{num} iterations\")\n print_solved(mySolver)\n \n \n \ndef print_solved(solver:Solver):\n print()\n print(\"################################################\")\n print(\"SOLVED\")\n print(\"################################################\")\n print(solver)\n print(\"################################################\")\n\nif __name__ == \"__main__\":\n # logging.basicConfig(level=logging.INFO)\n # test_solver_big_spin()\n # test_solver_big_spinmem()\n # time_mem = timeit.timeit(\"test_solver_big_spinmem()\", setup=\"from __main__ import test_solver_big_spinmem\", number=100)/100\n # time_normal = timeit.timeit(\"test_solver_big_spin()\", setup=\"from __main__ import test_solver_big_spin\", number=100)/100\n # print(time_mem)\n # print(time_normal)\n \n # test_solver_small()\n # test_solver_big_spin()\n test_solver_big_spinmem()\n","repo_name":"albertoparadisllop/PicrossSolver","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"4055151658","text":"import sys\ninput = sys.stdin.readline\n\nQ = int(input())\nQuery = [int(input()) for _ in range(Q)]\n\nfor N in Query:\n if N == 1:\n print(-1)\n else:\n ans = \"2\" + \"9\"*(N-1)\n print(ans)","repo_name":"wattaihei/ProgrammingContest","sub_path":"Codeforces/CGR07/probA.py","file_name":"probA.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"26781049069","text":"import sys\n\nneon = [\n '####.##.##.####', # 0\n '..#..#..#..#..#', # 1\n '###..#####..###', # 2\n '###..####..####', # 3\n '#.##.####..#..#', # 4\n '####..###..####', # 5\n '####..####.####', # 6\n '###..#..#..#..#', # 7\n '####.#####.####', # 8\n '####.####..####'] # 9\n\ndef checkAvailnumbers(index):\n availNumbers = []\n for i in range(10): # 0 ~ 9\n avail = True\n for j in range(15):\n if arrNumber[index][j] == neon[i][j]:\n continue\n\n if not (arrNumber[index][j] == '.' and neon[i][j] == '#'):\n avail = False\n break\n\n if avail:\n availNumbers.append(i)\n\n return availNumbers\n\ndef checkTotalavg():\n answer = 0\n\n for i in range(N):\n availArr = checkAvailnumbers(i)\n \n if not availArr:\n return -1\n\n answer += 10**(N-i-1) * sum(availArr)/len(availArr)\n\n return answer\n\ndef changeInputtoNumber():\n for _ in range(5):\n inputString = sys.stdin.readline().rstrip()\n for i in range(len(inputString)):\n if (i + 1) % 4 != 0:\n arrNumber[(i+1)//4].append(inputString[i])\n\nN = int(sys.stdin.readline())\narrNumber = [[] for _ in range(N)]\n\nchangeInputtoNumber()\nprint(checkTotalavg())","repo_name":"SeoHyungjun/Coding_Test","sub_path":"baekjun/solved.ac/level/gold/gold5/스타트링크 타워/스타트링크타워.py","file_name":"스타트링크타워.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"20927983155","text":"import os\nimport pandas as pd \nimport shutil\nfrom tqdm import tqdm\n\npath = 'ECGDataDenoised'\ndf = pd.read_excel('Diagnostics.xlsx', index_col='FileName')\n\nif not os.path.exists(path):\n raise FileNotFoundError(\"Extract ECGDataDenoised.zip\")\n\nif os.path.exists(\"Data\"):\n shutil.rmtree(\"Data\")\nos.mkdir(\"Data\")\nos.mkdir(\"Data/AF\")\nos.mkdir(\"Data/NORMAL\")\n\nfiles = []\ncount = 0\n# r=root, d=directories, f = files\nfor r, d, f in os.walk(path):\n for file in tqdm(f):\n if '.csv' in file:\n name = file[:-4]\n # print(name)\n rhy = df.loc[name, 'Rhythm']\n if rhy in ['AF', 'AFIB']:\n shutil.move(os.path.join(r, file), f'Data/AF/{file}')\n else:\n shutil.move(os.path.join(r, file), f'Data/NORMAL/{file}')\n files.append(os.path.join(r, file))\n count+= 1\n # print(count)\n \nshutil.rmtree(path)","repo_name":"12lholt/MSAI349","sub_path":"group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"30563807765","text":"print(\"Hello World\")\n# python doesn't reuired types declaration\na=1\nb=2.1\na2=\"fff\"\nc=False\ne=None\nname=input(\"enter u name\")\nprint(f\"Hello ,{name}\")\n# condtion in python\n# indentation is required on python\na=34\nif a<50:\n print(\"Good\")\nelif a==90:\n print(\"none\")\nelse:\n print(\"very good\")","repo_name":"Tinsa123/Hello","sub_path":"27-05-2022/python_basics.py","file_name":"python_basics.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"1587829852","text":"from unittest import TestCase, main\nfrom sample.models.smarty.us_street_address_input import USAddressInput\n\n\nclass TestUSAddressInput(TestCase):\n def test_is_valid_input_id(self):\n valid_address = USAddressInput(input_id=\"a\" * 36, street=\"\")\n invalid_address = USAddressInput(input_id=\"a\" * 37, street=\"\")\n self.assertTrue(valid_address.is_valid())\n self.assertFalse(invalid_address.is_valid())\n\n def test_is_valid_street(self):\n valid_address = USAddressInput(street=\"a\" * 50)\n invalid_address = USAddressInput(street=\"a\" * 51)\n self.assertTrue(valid_address.is_valid())\n self.assertFalse(invalid_address.is_valid())\n\n def test_is_valid_street2(self):\n valid_address = USAddressInput(street2=\"a\" * 50, street=\"\")\n invalid_address = USAddressInput(street2=\"a\" * 51, street=\"\")\n self.assertTrue(valid_address.is_valid())\n self.assertFalse(invalid_address.is_valid())\n\n def test_is_valid_secondary(self):\n valid_address = USAddressInput(secondary=\"a\" * 50, street=\"\")\n invalid_address = USAddressInput(secondary=\"a\" * 51, street=\"\")\n self.assertTrue(valid_address.is_valid())\n self.assertFalse(invalid_address.is_valid())\n\n def test_is_valid_city(self):\n valid_address = USAddressInput(city=\"a\" * 64, street=\"\")\n invalid_address = USAddressInput(city=\"a\" * 65, street=\"\")\n self.assertTrue(valid_address.is_valid())\n self.assertFalse(invalid_address.is_valid())\n\n def test_is_valid_state(self):\n valid_address = USAddressInput(state=\"a\" * 32, street=\"\")\n invalid_address = USAddressInput(state=\"a\" * 33, street=\"\")\n self.assertTrue(valid_address.is_valid())\n self.assertFalse(invalid_address.is_valid())\n\n def test_is_valid_zipcode(self):\n valid_address = USAddressInput(zipcode=\"a\" * 16, street=\"\")\n invalid_address = USAddressInput(zipcode=\"a\" * 17, street=\"\")\n self.assertTrue(valid_address.is_valid())\n self.assertFalse(invalid_address.is_valid())\n\n def test_is_valid_lastline(self):\n valid_address = USAddressInput(lastline=\"a\" * 64, street=\"\")\n invalid_address = USAddressInput(lastline=\"a\" * 65, street=\"\")\n self.assertTrue(valid_address.is_valid())\n self.assertFalse(invalid_address.is_valid())\n\n def test_is_valid_addressee(self):\n valid_address = USAddressInput(addressee=\"a\" * 64, street=\"\")\n invalid_address = USAddressInput(addressee=\"a\" * 65, street=\"\")\n self.assertTrue(valid_address.is_valid())\n self.assertFalse(invalid_address.is_valid())\n\n def test_is_valid_urbanization(self):\n valid_address = USAddressInput(urbanization=\"a\" * 64, street=\"\")\n invalid_address = USAddressInput(urbanization=\"a\" * 65, street=\"\")\n self.assertTrue(valid_address.is_valid())\n self.assertFalse(invalid_address.is_valid())\n\n def test_is_valid_match(self):\n valid_address = USAddressInput(match=\"a\" * 8, street=\"\")\n invalid_address = USAddressInput(match=\"a\" * 9, street=\"\")\n self.assertTrue(valid_address.is_valid())\n self.assertFalse(invalid_address.is_valid())\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"pfeiferj/empora-code-sample","sub_path":"tests/models/smarty/test_us_street_address_input.py","file_name":"test_us_street_address_input.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"43289796954","text":"\"\"\"\n第二轮:自我介绍,题是面经里的,给定两个单词,问第二个单词能否通过交换第一个单词中两个字母得到 Follow up:能否通过交换至多n次得到\nANS : https://www.careercup.com/question?id=6464130037841920\n\nPage 3\n\n\"\"\"\nfrom collections import defaultdict\nclass Solution:\n def metaWord(self, word1, word2):\n \"\"\"\n Only one swap solution\n \"\"\"\n if word1 == word2 or len(word1)!= len(word2):\n return False\n diffnum = 0\n wd1, wd2 = '', ''\n for idx, ch in enumerate(word1):\n if ch != word2[idx]:\n diffnum += 1\n if diffnum > 2:\n return False\n wd1 += ch\n wd2 += word2[idx]\n return diffnum == 2 and wd1 == wd2[::-1]\n\n\n def metaWordMultipleSwap(self, word1, word2):\n \"\"\"\n Check if can swap at most n times to make word2 be word1\n n = len(word1)\n \"\"\"\n def checkSwappable(s1, s2, startidx):\n for i in range(startidx, len(s1)):\n if s1[i] != s2[i]:\n chins2idx = self.char2swapidx.get(s1[i], set())\n if chins2idx:\n for idx in chins2idx:\n print(s2, i)\n print(s1, idx)\n if idx > i:# and s2[i] == s1[idx]:\n chins2idx.discard(idx)\n chins2idx.add(i)\n self.char2swapidx[s2[i]].discard(i)\n self.char2swapidx[s2[i]].add(idx)\n if checkSwappable(s1, s2[:i] + s2[idx] + s2[i+1:idx]+s2[i]+s2[idx+1:], i+1):\n return True\n chins2idx.add(idx)\n chins2idx.discard(i)\n self.char2swapidx[s2[i]].add(i)\n self.char2swapidx[s2[i]].discard(idx)\n else:\n return False\n return s1==s2\n\n\n if word1 == word2 or len(word1) != len(word2):\n return False\n self.char2swapidx = defaultdict(lambda : set())\n for idx, ch in enumerate(word1):\n if ch != word2[idx]:\n self.char2swapidx[word2[idx]].add(idx)\n return checkSwappable(word1, word2, 0)\n\n\n\n\ns = Solution()\nword1, word2 = 'abc', 'bca'\n#print(s.metaWord(word1, word2))\nprint(s.metaWordMultipleSwap(word1, word2))","repo_name":"llgeek/leetcode","sub_path":"Google_interview/MetaWord.py","file_name":"MetaWord.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"33895840922","text":"import numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef run_pca(data):\n # Assuming you have the data in a NumPy array called 'data'\n covariance_matrix = np.cov(data.T)\n eigenvalues, eigenvectors = np.linalg.eig(covariance_matrix)\n n_components = np.count_nonzero(eigenvalues)\n\n # Sort the eigenvalues in descending order\n eigenvalues_sorted = np.sort(eigenvalues)[::-1]\n # Plot the eigenvalues\n fig = plt.figure(figsize=(10, 6))\n plt.plot(range(1, len(eigenvalues) + 1), eigenvalues_sorted, marker='o', linestyle='-', color='b')\n plt.xlabel('Component')\n plt.xlim(0, 20)\n plt.ylabel('Eigenvalue')\n plt.title('Eigenvalues of Covariance Matrix')\n plt.grid(True)\n fig.show()\n fig.savefig('Eigenvalues of Covariance Matrix.png')\n\n from sklearn.decomposition import PCA\n import pandas as pd\n\n n_components = 4\n # Instantiate the PCA object with the desired number of components\n pca = PCA(n_components=n_components)\n\n # Fit the data to the PCA model\n pca.fit(data)\n\n # Transform the data to the lower-dimensional space\n data_transformed = pca.transform(data)\n\n # Create a DataFrame to store the transformed data\n column_names = ['PC{}'.format(i + 1) for i in range(n_components)]\n df_transformed = pd.DataFrame(data_transformed, columns=column_names)\n\n # The resulting DataFrame 'df_transformed' contains the transformed data\n # with the specified number of components (in this case, 2 components)\n\n explained_variance_ratio = pca.explained_variance_ratio_\n print(explained_variance_ratio)\n return df_transformed\n","repo_name":"barmilman/IML_Hackathon","sub_path":"code/pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"6320212356","text":"from openpyxl import Workbook\n\nwb = Workbook()\n\n# grab the active worksheet\nws = wb.active\n\n# Data can be assigned directly to cells\n# ws['A1'] = \"Mervin is a Python Expert\"\n# wb.save(\"C:\\\\Mervin\\\\write_excel.xlsx\") # The workbook is to be saved and not the ws kindly note\n\nfor i in range(1,11):\n for j in range(1,6):\n ws.cell(row=i, column=j).value = i+j\n\nwb.save(\"C:\\\\Mervin\\\\write_excel.xlsx\")","repo_name":"MeHar-DS/Pycode","sub_path":"fileIO_demo/write_xlsx_demo.py","file_name":"write_xlsx_demo.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"4145428148","text":"\n\nfrom sys import stdin\n\ndef main():\n n = int(stdin.readline())\n skill_list = [int(x) for x in stdin.readline().split()]\n min_skill = min(skill_list)\n\n # create a list of tuples of each skill and the number of students\n # with that skill\n skill_counts = []\n for i in range(min_skill, max(skill_list) + 1):\n skill_counts.append((i, skill_list.count(i)))\n\n # sort the skill counts by the number of students with that skill\n skill_counts.sort(key=lambda x: x[1])\n\n # find the minimum number of students needed to form a team\n # of each skill level\n min_students = 0\n for i, count in skill_counts:\n if count <= n:\n min_students += (n - count)\n n = count\n else:\n min_students += n\n break\n\n print(min_students)\n\nmain()","repo_name":"gabriele-tombesi/codex_optimal_proj","sub_path":"Completions/davinci_runs/test/test_T0.5_k2_1000/intro-questions.txt_dir/4186/first_pys/solution_1.py","file_name":"solution_1.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"41"} +{"seq_id":"26778444890","text":"f = open('day1_input.txt', 'r')\ninput_data = [int(x) for x in f]\n\nsum_condition = 2020\n\n\ndef get_product(data):\n for x in data:\n data_sans_x = [num for num in data if num != x]\n for y in data_sans_x:\n data_sans_x_y = [num for num in data_sans_x if num != y]\n for z in data_sans_x_y:\n if (x + y + z) == sum_condition:\n answer = x * y * z\n return answer\n\n\nif __name__ == \"__main__\":\n print(get_product(input_data))\n","repo_name":"buchmayne/advent_of_code","sub_path":"2020/day1/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"15841367570","text":"import requests\nfrom PIL import Image\nimport math\nfrom pyproj import Transformer\nimport os\nimport osgeo_utils.gdal_merge\nimport sys\n\nclass BasemapExtractor:\n\n\n def __init__(self, perimeter, zoom_level, outdir, tiles_url, tiles_url_end='.png', highdpi=True, mosaic=True):\n \"\"\"Set the perimter you want to extract in form of rectangle by giving a tuple with 4 coordinates\n in epsg_3857 (west, north, east, south). Set the zoom level you want. Set the directory where to save the image.\n Give the URL of the tiles source (WMTS, XYZ), the part before the zoom level. Give the URL end (@2x, format, key)\n Set mosaic to false if you don't want to mosaic the tiles together, default is True \n \"\"\"\n transformer = Transformer.from_crs(3857, 4326)\n\n self.perimeter = (\n transformer.transform(perimeter[0], perimeter[1])[1],\n transformer.transform(perimeter[0], perimeter[1])[0],\n transformer.transform(perimeter[2], perimeter[3])[1],\n transformer.transform(perimeter[2], perimeter[3])[0]\n )\n\n self.zoom_level = zoom_level\n self.outdir = outdir\n self.tiles_url = tiles_url\n self.tiles_url_end = tiles_url_end\n self.highdpi = highdpi\n self.mosaic = mosaic\n\n\n def get_tiles_id(self):\n \"\"\"Get the 4 ids of border tiles. Return a tuple with border id (left, up, right, bottom)\"\"\"\n\n n = 2.0 ** self.zoom_level\n tile_left_id = int((self.perimeter[0] + 180.0) / 360.0 * n)\n tile_right_id = int((self.perimeter[2] + 180.0) / 360.0 * n)\n\n lat_rad = math.radians(self.perimeter[1])\n tile_up_id = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n)\n lat_rad = math.radians(self.perimeter[3])\n tile_bottom_id = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n)\n\n return (tile_left_id, tile_up_id, tile_right_id, tile_bottom_id)\n\n\n def get_tiles_number(self):\n \"\"\"Return the number of tiles needed to cover the perimeter.\"\"\"\n \n # /!\\ the tiles id goes from top to bottom in the Y axis\n # That's why it's LowerLeft - UpperRight for the Y axis\n tiles_number = (self.get_tiles_id()[2] - self.get_tiles_id()[0] + 1) * (self.get_tiles_id()[3] - self.get_tiles_id()[1] + 1)\n print(f\"\\nNumber of tiles covering the perimeter : {tiles_number}\\n\")\n return tiles_number\n\n\n def tileid_2_coodrinates(self, tileid_x, tileid_y):\n \"\"\"Take 2 arguments : tile id in X and Y. Return the coordinates in epsg:3857 of corner for worldfile\"\"\"\n n = 2.0 ** self.zoom_level\n lon_deg = tileid_x / n * 360.0 - 180.0\n lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * tileid_y / n)))\n lat_deg = math.degrees(lat_rad)\n transformer = Transformer.from_crs(4326, 3857)\n return transformer.transform(lat_deg, lon_deg)\n\n\n def download_tiles(self):\n \"\"\"Download necessary tiles to cover the perimeter. Transform them into RGB JPEG 95% compression.\n Write the World File for each tile\"\"\"\n\n # Ask the user if he wants to continue, knowing the number of tiles to download\n tiles_total = self.get_tiles_number()\n if input(\"Press Enter to continue or anything else to stop : \") != \"\":\n return\n\n count = 0\n\n for x_coord in range(self.get_tiles_id()[0], self.get_tiles_id()[2]+1):\n for y_coord in range(self.get_tiles_id()[1], self.get_tiles_id()[3]+1):\n\n # Download the tiles from the WMTS API ENDPOINT\n with open(self.outdir + '/' + str(x_coord) + '_' + str(y_coord) + '.png', \"wb\") as file:\n response = requests.get(self.tiles_url + '/' + str(self.zoom_level) + '/' + str(x_coord) + '/' + str(y_coord) + self.tiles_url_end)\n file.write(response.content)\n \n print(f\"Downloaded Tile : {x_coord}_{y_coord}\") \n\n # Transform the file into RGB Image\n img = Image.open(self.outdir + '/' + str(x_coord) + '_' + str(y_coord) + '.png')\n imgRGB = img.convert('RGB')\n imgRGB.save(self.outdir + '/' + str(x_coord) + '_' + str(y_coord) + '.jpg', format='JPEG', subsampling=0, quality=95)\n os.remove(self.outdir + '/' + str(x_coord) + '_' + str(y_coord) + '.png')\n\n print(f\"Converted to RGB Tile : {x_coord}_{y_coord}\")\n\n # Write the World File\n if self.highdpi:\n resolution = round(78271.515/(2**self.zoom_level), 4)\n else:\n resolution = round(78271.515/(2**self.zoom_level)*2, 4)\n pixel_x = self.tileid_2_coodrinates(x_coord, y_coord)[0] + (resolution/2)\n pixel_y = self.tileid_2_coodrinates(x_coord, y_coord)[1] - (resolution/2)\n\n with open(self.outdir + '/' + str(x_coord) + '_' + str(y_coord) + '.jgw', 'w') as jgw: \n jgw.write(str(resolution) + '\\n')\n jgw.write('0\\n')\n jgw.write('0\\n')\n jgw.write('-' + str(resolution) + '\\n')\n jgw.write(str(pixel_x) + '\\n')\n jgw.write(str(pixel_y) + '\\n')\n \n print(f\"Created World File for the Tile : {x_coord}_{y_coord}\")\n count += 1\n print(f\"{round((count/tiles_total)*100, 2)} %\\n\")\n \n\n def mosaic_tiles(self):\n \"\"\"Mosaic the tiles together. Uses the GDAL library. Must be installed sperately\"\"\"\n \n # First create a mosaic for each row of tiles \n for x_coord in range(self.get_tiles_id()[0], self.get_tiles_id()[2]+1):\n optfile = open(self.outdir + '/optfile.txt', 'w')\n \n for y_coord in range(self.get_tiles_id()[1], self.get_tiles_id()[3]+1):\n optfile.write(self.outdir + '/' + str(x_coord) + '_' + str(y_coord) + '.jpg' + ' ')\n\n optfile.close()\n \n osgeo_utils.gdal_merge.main(['gdal_merge.py', '-o', self.outdir + '/' + str(x_coord) + '.tif', '-co', 'TFW=YES', '-co', 'TILED=YES', '-co', 'COMPRESS=LZW', '-co', 'PREDICTOR=2', '--optfile', self.outdir + '/optfile.txt'])\n\n # Then mosaic the row mosaics together in a single file\n with open(self.outdir + '/optfile.txt', 'w') as optfile:\n \n for x_coord in range(self.get_tiles_id()[0], self.get_tiles_id()[2]+1):\n optfile.write(self.outdir + '/' + str(x_coord) + '.tif' + ' ')\n \n osgeo_utils.gdal_merge.main(['gdal_merge.py', '-o', self.outdir + '/Mosaic.tif', '-co', 'TFW=YES', '-co', 'TILED=YES', '-co', 'COMPRESS=LZW', '-co', 'PREDICTOR=2', '--optfile', self.outdir + '/optfile.txt'])\n os.remove(self.outdir + '/optfile.txt')\n\n for x_coord in range(self.get_tiles_id()[0], self.get_tiles_id()[2]+1):\n os.remove(self.outdir + '/' + str(x_coord) + '.tif')\n os.remove(self.outdir + '/' + str(x_coord) + '.tfw')\n\n for x_coord in range(self.get_tiles_id()[0], self.get_tiles_id()[2]+1):\n for y_coord in range(self.get_tiles_id()[1], self.get_tiles_id()[3]+1):\n os.remove(self.outdir + '/' + str(x_coord) + '_' + str(y_coord) + '.jpg')\n os.remove(self.outdir + '/' + str(x_coord) + '_' + str(y_coord) + '.jgw')\n\n\ndef main(*args):\n\n for arg in args:\n\n if arg.split(\"=\")[0] == \"perimeter\":\n boundingbox = arg.split(\"=\")[1]\n perimeter = tuple(map(int, boundingbox.split(',')))\n\n elif arg.split(\"=\")[0] == \"outdir\":\n outdir = arg.split(\"=\")[1]\n \n elif arg.split(\"=\")[0] == \"tiles_url\":\n tiles_url = arg.split(\"=\")[1]\n\n elif arg.split(\"=\")[0] == \"key\":\n tiles_url_end = '@2x.png?key=' + arg.split(\"=\")[1]\n\n elif arg.split(\"=\")[0] == \"zoom_level\":\n zoom_level = int(arg.split(\"=\")[1])\n\n basemap = BasemapExtractor(perimeter=perimeter, zoom_level=zoom_level, outdir=outdir, tiles_url=tiles_url, tiles_url_end=tiles_url_end)\n basemap.download_tiles()\n basemap.mosaic_tiles()\n\nif __name__ == \"__main__\":\n main(*sys.argv[1:])\n \n ","repo_name":"benoitregamey/basemap-image","sub_path":"BasemapExtractor.py","file_name":"BasemapExtractor.py","file_ext":"py","file_size_in_byte":8304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"788743667","text":"# Problem Statement: https://practice.geeksforgeeks.org/problems/merge-k-sorted-linked-lists/1\n\n#User function Template for python3\n'''\n\tYour task is to merge the given k sorted\n\tlinked lists into one list and return\n\tthe the new formed linked list class.\n\n\tFunction Arguments:\n\t arr is a list containing the n linkedlist head pointers\n\t n is an integer value\n \n node class:\n \nclass Node:\n def __init__(self,x):\n self.data = x\n self.nxt = None\n'''\nclass Solution:\n #Function to merge K sorted linked list.\n def mergeKLists(self,arr,K):\n # code here\n # return head of merged list\n l=[]\n for i in arr:\n temp = i\n while temp:\n l.append(temp.data)\n temp = temp.next\n l.sort()\n head = Node(l[0])\n str = head\n for i in range(1,len(l)):\n node = Node(l[i])\n str.next=node\n str = node\n return head\n\n#{ \n# Driver Code Starts\n#Initial Template for Python 3\n\nclass Node:\n def __init__(self,x):\n self.data=x\n self.next=None\n\nclass LinkedList:\n def __init__(self):\n self.head=None\n self.tail=None\n \n def add(self,x):\n if self.head is None:\n self.head=Node(x)\n self.tail=self.head\n else:\n self.tail.next=Node(x)\n self.tail=self.tail.next\n \ndef printList(head):\n walk = head\n while walk:\n print(walk.data, end=' ')\n walk=walk.next\n print()\n\nif __name__==\"__main__\":\n for _ in range(int(input())):\n n=int(input())\n line=[int(x) for x in input().strip().split()]\n \n heads=[]\n index=0\n \n for i in range(n):\n size=line[index]\n index+=1\n \n newList = LinkedList()\n \n for _ in range(size):\n newList.add(line[index])\n index+=1\n \n heads.append(newList.head)\n \n merged_list = Solution().mergeKLists(heads,n)\n printList(merged_list)\n\n# } Driver Code Ends","repo_name":"yashitanamdeo/geeks-for-geeks","sub_path":"Medium/merge_k_sorted_linked_lists.py","file_name":"merge_k_sorted_linked_lists.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"33"} +{"seq_id":"32918418399","text":"from manim import *\n\nclass Start(Scene):\n def construct(self):\n \n ax = Axes(axis_config={\"include_ticks\":False})\n\n a = np.array([2,2,0])\n b = np.array([4,-1,0])\n t_a = MathTex(r\"a\")\n t_b = MathTex(r\"b\")\n\n f_1 = MathTex(r\"\\| a \\| = \\sqrt{x_a^2 + y_a^2}\")\n f_2 = MathTex(r\"\\| b \\| = \\sqrt{x_b^2 + y_b^2}\")\n f_3 = MathTex(r\"a \\cdot b = x_a x_b + y_a y_b\")\n f_4 = MathTex(r\"a \\cdot b = \\|a\\|\\|b\\| \\cos \\theta\")\n\n x_a = np.array([2,0,0])\n y_a = np.array([0,2,0])\n x_b = np.array([4,0,0])\n y_b = np.array([0,-1,0])\n\n aa = Vector(a)\n bb = Vector(b)\n\n line_1 = DashedLine(aa.get_end(), x_a )\n line_2 = DashedLine(aa.get_end(), y_a )\n line_3 = DashedLine(bb.get_end(), x_b )\n line_4 = DashedLine(bb.get_end(), y_b )\n\n label_a = aa.coordinate_label()\n label_b = bb.coordinate_label()\n\n angle = Angle(aa, bb, other_angle=True, radius=1)\n # angle.add_updater(lambda m, dt: m.become(Angle(ax.x_axis, aa)))\n # angle.update()\n\n self.add(ax, aa, bb)\n\n self.add(t_a.next_to(aa.get_center(), UL, buff=SMALL_BUFF))\n self.add(t_b.next_to(bb.get_center(), DL, buff=SMALL_BUFF))\n\n self.play(Write(label_a), Write(label_b))\n self.add(line_1, line_2, line_3, line_4)\n\n self.play(Write(f_1.to_edge(UL, buff=LARGE_BUFF)))\n self.play(Write(f_2.next_to(f_1, DOWN)))\n self.play(Write(f_3.next_to(f_2, DOWN)))\n\n self.play(Write(f_4.to_edge(DL, buff=LARGE_BUFF)))\n\n self.play(Write(angle))\n\n self.wait(10)\n\nclass Cosine(Scene):\n def construct(self):\n\n ax = Axes()\n \n a = np.array([2,3,0])\n b = np.array([3,1,0])\n\n aa = Vector(a)\n bb = Vector(b)\n\n angle_a = Angle(aa, ax.x_axis, other_angle=True, radius=0.5)\n angle_a.add_updater(lambda m: m.become(Angle(aa, ax.x_axis, other_angle=True, radius=0.5)))\n\n angle_b = Angle(bb, ax.x_axis, other_angle=True, radius=0.7)\n angle_b.add_updater(lambda m: m.become(Angle(bb, ax.x_axis, other_angle=True, radius=0.7)))\n\n r_a = np.linalg.norm(a)\n r_b = np.linalg.norm(b)\n\n theta_a = np.arccos(a[0]/r_a)\n theta_b = np.arccos(b[0]/r_b)\n\n\n\n self.add(ax) \n\n self.play(Write(aa))\n self.play(Write(angle_a))\n \n self.play(Write(bb))\n self.play(Write(angle_b))\n\n self.play(bb.animate.rotate(-theta_b, about_point=bb.get_start()))\n self.play(aa.animate.rotate(-theta_a, about_point=aa.get_start()))\n\n \n \n self.wait()\n\n\nclass DotProduct(Scene):\n def construct(self):\n\n plane = NumberPlane()\n # self.add(plane)\n \n vt = ValueTracker(-1)\n line_0 = Line(ORIGIN, [3, 0, 0]).set_color(YELLOW)\n # line_1 = Line(ORIGIN, [0, 1, 0]).add_updater(lambda m: m.become(Line(ORIGIN, [-2*np.sin(vt.get_value()), 2*np.cos(vt.get_value()), 0]).set_color(BLUE)))\n line_1 = Line(ORIGIN, [0, 1, 0]).add_updater(lambda m: self.my_fun(m, vt))\n proj = Line(ORIGIN, line_1.get_end()).add_updater(lambda m: self.my_proj(m, line_1, vt))\n angle = Angle(line_0, line_1).add_updater(lambda m: m.become(Angle(line_0, line_1)))\n\n number = DecimalNumber(0, color=RED).to_corner().add_updater(lambda m: self.my_num(m, line_1))\n\n self.add(line_0, line_1, angle, proj, number)\n self.play(vt.animate.set_value(10), run_time=20, rate_func=linear)\n\n def my_fun(self, mob, vt):\n\n return mob.become(Line(ORIGIN, [-2*np.sin(vt.get_value()), 2*np.cos(vt.get_value()), 0]).set_color(BLUE))\n \n def my_num(self, m, line_1):\n a = line_1.get_end()\n b = np.array([3,0,0])\n tmp = a * np.dot(a,b)/np.dot(a,a)\n tmp = b * np.dot(a,b)/np.dot(b,b)\n\n return m.set_value(np.dot(a,b))\n \n def my_proj(self, mob, line_1, vt):\n a = line_1.get_end()\n b = np.array([3,0,0])\n tmp = a * np.dot(a,b)/np.dot(a,a)\n tmp = b * np.dot(a,b)/np.dot(b,b)\n return mob.become(Line(line_1.get_end(), tmp))","repo_name":"Joocheol/Transformer","sub_path":"dotproduct.py","file_name":"dotproduct.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"39869225070","text":"#!/usr/bin/python3\nfrom models.base_model import Base\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import (sessionmaker, scoped_session)\nfrom os import getenv\nfrom models.user import User\nfrom models.amenity import Amenity\nfrom models.city import City\nfrom models.place import Place\nfrom models.review import Review\nfrom models.state import State\n\"\"\"\nThis is the greatest db_storage module\n\"\"\"\n\n\nclass DBStorage:\n __engine = None\n __session = None\n __Session = None\n\n def __init__(self):\n \"\"\"\n initializes engine\n \"\"\"\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(\n getenv('HBNB_MYSQL_USER'),\n getenv('HBNB_MYSQL_PWD'),\n getenv('HBNB_MYSQL_HOST'),\n getenv('HBNB_MYSQL_DB')))\n self.__models_available = {\"User\": User,\n \"Amenity\": Amenity, \"City\": City,\n \"Place\": Place, \"Review\": Review,\n \"State\": State}\n if getenv('HBNB_MYSQL_ENV', 'not') == 'test':\n Base.metadata.drop_all(self.__engine)\n\n def all(self, cls=None):\n \"\"\"\n returns a dictionary of all the class objects\n \"\"\"\n orm_objects = {}\n if cls:\n for k in self.__session.query(self.__models_available[cls]):\n orm_objects[k.__dict__['id']] = k\n else:\n for i in self.__models_available.values():\n j = self.__session.query(i).all()\n if j:\n for k in j:\n orm_objects[k.__dict__['id']] = k\n return orm_objects\n\n def new(self, obj):\n \"\"\"\n adds a new obj to the session\n \"\"\"\n self.__session.add(obj)\n\n def save(self):\n \"\"\"\n saves the objects fom the current session\n \"\"\"\n self.__session.commit()\n\n def get(self, cls, id):\n \"\"\"\n retrieves an object\n \"\"\"\n if cls is None:\n return None\n else:\n for k in self.__session.query(self.__models_available[cls]):\n if k.__dict__['id'] == id:\n return k\n\n def count(self, cls=None):\n \"\"\"\n returns the number of objects in\n storage matching the given class name\n \"\"\"\n if cls is None:\n return len(self.all())\n elif self.__models_available.get(cls):\n d = self.all()\n return len(self.all(cls))\n\n def delete(self, obj=None):\n \"\"\"\n deletes an object from the current session\n \"\"\"\n if obj is not None:\n self.__session.delete(obj)\n\n def reload(self):\n \"\"\"\n WARNING!!!! I'm not sure if Base.metadata.create_all needs to\n be in the init method\n \"\"\"\n Base.metadata.create_all(self.__engine)\n self.__session = scoped_session(sessionmaker(bind=self.__engine, expire_on_commit=False))\n\n def close(self):\n \"\"\"\n close a session\n \"\"\"\n self.__session.remove()\n","repo_name":"jtt-berkeley/AirBnB_clone_v3","sub_path":"models/engine/db_storage.py","file_name":"db_storage.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"72488905694","text":"\nimport math\nfrom wrappers import Turtle\n\ndef draw(canvas):\n t1 = Turtle(canvas)\n t1.cls()\n\n \"\"\"\n # test towards (towardsXY)\n # these kinds of tests should be done using pyunit\n tt = Turtle(canvas)\n for i in range(0, 370, 10):\n tt.pu()\n tt.lt(i)\n tt.fd(100)\n print \"angle: %f, t1 towards tt: %f, tt towards t1: %f\" % (i, t1.towards(tt), tt.towards(t1))\n tt.bk(100)\n tt.rt(i)\n \"\"\"\n\n # test the distance calculation\n t1.left(45)\n t1.forward(100 * math.sqrt(2))\n\n t2 = Turtle(canvas)\n t2.forward(100)\n d = t2.distance(t1)\n # should display 100\n t2.write(\"%f\" % d)\n\n # test the odometer reading\n t1.resetOdometer()\n t1.resumeOdometer()\n t1.polygon(4, 100)\n t1.write(\"odometer: %f\" % t1.getOdometer())\n","repo_name":"ceprio/xl_vb2py","sub_path":"vb2py/PythonCard/samples/turtle/scripts/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"33"} +{"seq_id":"1681121665","text":"def my_soln(s, k):\r\n d = set()\r\n for ind in range(len(s)):\r\n if ind+k<=len(s):\r\n w = s[ind:ind+k]\r\n d.add(w)\r\n \r\n else:\r\n break\r\n \r\n return len(d)==2**k\r\n # if len(d)!=2**k:\r\n # return False\r\n # else:\r\n # return True","repo_name":"anoubhav/LeetCode-Solutions","sub_path":"Contests/Biweekly 27/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"71246227613","text":"# -*- coding: utf-8 -*-\nimport array\nimport datetime\nimport io\nimport itertools\nimport logging\nimport pkgutil\nimport os\nimport unittest\nimport shutil\nimport sys\n\nimport h5py\nimport numpy\n\nfrom nionswift_plugin.DM_IO import parse_dm3\nfrom nionswift_plugin.DM_IO import dm3_image_utils\n\nfrom nion.data import Calibration\nfrom nion.data import DataAndMetadata\n\n\nclass TestDM3ImportExportClass(unittest.TestCase):\n\n def check_write_then_read_matches(self, data, func, _assert=True):\n # we confirm that reading a written element returns the same value\n s = io.BytesIO()\n header = func(s, outdata=data)\n s.seek(0)\n if header is not None:\n r, hy = func(s)\n else:\n r = func(s)\n if _assert:\n self.assertEqual(r, data)\n return r\n\n def test_dm_read_struct_types(self):\n s = io.BytesIO()\n types = [2, 2, 2]\n parse_dm3.dm_read_struct_types(s, outtypes=types)\n s.seek(0)\n in_types, headerlen = parse_dm3.dm_read_struct_types(s)\n self.assertEqual(in_types, types)\n\n def test_simpledata(self):\n self.check_write_then_read_matches(45, parse_dm3.dm_types[parse_dm3.get_dmtype_for_name('long')])\n self.check_write_then_read_matches(2**30, parse_dm3.dm_types[parse_dm3.get_dmtype_for_name('uint')])\n self.check_write_then_read_matches(34.56, parse_dm3.dm_types[parse_dm3.get_dmtype_for_name('double')])\n\n def test_read_string(self):\n data = \"MyString\"\n ret = self.check_write_then_read_matches(data, parse_dm3.dm_types[parse_dm3.get_dmtype_for_name('array')], False)\n self.assertEqual(data, dm3_image_utils.fix_strings(ret))\n\n def test_array_simple(self):\n dat = array.array('b', [0]*256)\n self.check_write_then_read_matches(dat, parse_dm3.dm_types[parse_dm3.get_dmtype_for_name('array')])\n\n def test_array_struct(self):\n dat = parse_dm3.structarray(['h', 'h', 'h'])\n dat.raw_data = array.array('b', [0, 0] * 3 * 8) # two bytes x 3 'h's x 8 elements\n self.check_write_then_read_matches(dat, parse_dm3.dm_types[parse_dm3.get_dmtype_for_name('array')])\n\n def test_tagdata(self):\n for d in [45, 2**30, 34.56, array.array('b', [0]*256)]:\n self.check_write_then_read_matches(d, parse_dm3.parse_dm_tag_data)\n\n def test_tagroot_dict(self):\n mydata = {}\n self.check_write_then_read_matches(mydata, parse_dm3.parse_dm_tag_root)\n mydata = {\"Bob\": 45, \"Henry\": 67, \"Joe\": 56}\n self.check_write_then_read_matches(mydata, parse_dm3.parse_dm_tag_root)\n\n def test_tagroot_dict_complex(self):\n mydata = {\"Bob\": 45, \"Henry\": 67, \"Joe\": {\n \"hi\": [34, 56, 78, 23], \"Nope\": 56.7, \"d\": array.array('I', [0] * 32)}}\n self.check_write_then_read_matches(mydata, parse_dm3.parse_dm_tag_root)\n\n def test_tagroot_list(self):\n # note any strings here get converted to 'H' arrays!\n mydata = []\n self.check_write_then_read_matches(mydata, parse_dm3.parse_dm_tag_root)\n mydata = [45, 67, 56]\n self.check_write_then_read_matches(mydata, parse_dm3.parse_dm_tag_root)\n\n def test_struct(self):\n # note any strings here get converted to 'H' arrays!\n mydata = tuple()\n f = parse_dm3.dm_types[parse_dm3.get_dmtype_for_name('struct')]\n self.check_write_then_read_matches(mydata, f)\n mydata = (3, 4, 56.7)\n self.check_write_then_read_matches(mydata, f)\n\n def test_image(self):\n im = array.array('h')\n if sys.version < '3':\n im.fromstring(numpy.random.bytes(64))\n else:\n im.frombytes(numpy.random.bytes(64))\n im_tag = {\"Data\": im,\n \"Dimensions\": [23, 45]}\n s = io.BytesIO()\n parse_dm3.parse_dm_tag_root(s, outdata=im_tag)\n s.seek(0)\n ret = parse_dm3.parse_dm_tag_root(s)\n self.assertEqual(im_tag[\"Data\"], ret[\"Data\"])\n self.assertEqual(im_tag[\"Dimensions\"], ret[\"Dimensions\"])\n self.assertTrue((im_tag[\"Data\"] == ret[\"Data\"]))\n\n def test_data_write_read_round_trip(self):\n def db_make_directory_if_needed(directory_path):\n if os.path.exists(directory_path):\n if not os.path.isdir(directory_path):\n raise OSError(\"Path is not a directory:\", directory_path)\n else:\n os.makedirs(directory_path)\n\n class numpy_array_type:\n def __init__(self, shape, dtype):\n self.data = numpy.ones(shape, dtype)\n def __enter__(self):\n return self\n def __exit__(self, exc_type, exc_value, traceback):\n pass\n\n class h5py_array_type:\n def __init__(self, shape, dtype):\n current_working_directory = os.getcwd()\n self.__workspace_dir = os.path.join(current_working_directory, \"__Test\")\n db_make_directory_if_needed(self.__workspace_dir)\n self.f = h5py.File(os.path.join(self.__workspace_dir, \"file.h5\"), \"a\")\n self.data = self.f.create_dataset(\"data\", data=numpy.ones(shape, dtype))\n def __enter__(self):\n return self\n def __exit__(self, exc_type, exc_value, traceback):\n self.f.close()\n shutil.rmtree(self.__workspace_dir)\n\n array_types = numpy_array_type, h5py_array_type\n dtypes = (numpy.float32, numpy.float64, numpy.complex64, numpy.complex128, numpy.int16, numpy.uint16, numpy.int32, numpy.uint32)\n shape_data_descriptors = (\n ((6,), DataAndMetadata.DataDescriptor(False, 0, 1)), # spectrum\n ((6, 4), DataAndMetadata.DataDescriptor(False, 1, 1)), # 1d collection of spectra\n ((6, 8, 10), DataAndMetadata.DataDescriptor(False, 2, 1)), # 2d collection of spectra\n ((6, 4), DataAndMetadata.DataDescriptor(True, 0, 1)), # sequence of spectra\n ((6, 4), DataAndMetadata.DataDescriptor(False, 0, 2)), # image\n ((6, 4, 2), DataAndMetadata.DataDescriptor(False, 1, 2)), # 1d collection of images\n ((6, 5, 4, 2), DataAndMetadata.DataDescriptor(False, 2, 2)), # 2d collection of images. not possible?\n ((6, 8, 10), DataAndMetadata.DataDescriptor(True, 0, 2)), # sequence of images\n )\n for version in (3, 4):\n for array_type in array_types:\n for dtype in dtypes:\n for shape, data_descriptor_in in shape_data_descriptors:\n for signal_type in ((None, \"eels\") if data_descriptor_in.datum_dimension_count ==1 else (None,)):\n # print(f\"--- {array_type} {dtype} {shape} {data_descriptor_in} {signal_type}\")\n s = io.BytesIO()\n with array_type(shape, dtype) as a:\n data_in = a.data\n dimensional_calibrations_in = list()\n for index, dimension in enumerate(shape):\n dimensional_calibrations_in.append(Calibration.Calibration(1.0 + 0.1 * index, 2.0 + 0.2 * index, \"µ\" + \"n\" * index))\n intensity_calibration_in = Calibration.Calibration(4, 5, \"six\")\n metadata_in = dict()\n if signal_type:\n metadata_in.setdefault(\"hardware_source\", dict())[\"signal_type\"] = signal_type\n xdata_in = DataAndMetadata.new_data_and_metadata(data_in, data_descriptor=data_descriptor_in, dimensional_calibrations=dimensional_calibrations_in, intensity_calibration=intensity_calibration_in, metadata=metadata_in)\n dm3_image_utils.save_image(xdata_in, s, version)\n s.seek(0)\n xdata = dm3_image_utils.load_image(s)\n self.assertTrue(numpy.array_equal(data_in, xdata.data))\n self.assertEqual(data_descriptor_in, xdata.data_descriptor)\n self.assertEqual(tuple(dimensional_calibrations_in), tuple(xdata.dimensional_calibrations))\n self.assertEqual(intensity_calibration_in, xdata.intensity_calibration)\n\n def test_rgb_data_write_read_round_trip(self):\n for version in (3, 4):\n s = io.BytesIO()\n data_in = (numpy.random.randn(6, 4, 3) * 255).astype(numpy.uint8)\n data_descriptor_in = DataAndMetadata.DataDescriptor(False, 0, 2)\n dimensional_calibrations_in = [Calibration.Calibration(1, 2, \"nm\"), Calibration.Calibration(2, 3, u\"µm\")]\n intensity_calibration_in = Calibration.Calibration(4, 5, \"six\")\n metadata_in = {\"abc\": None, \"\": \"\", \"one\": [], \"two\": {}, \"three\": [1, None, 2]}\n xdata_in = DataAndMetadata.new_data_and_metadata(data_in, data_descriptor=data_descriptor_in, dimensional_calibrations=dimensional_calibrations_in, intensity_calibration=intensity_calibration_in, metadata=metadata_in)\n dm3_image_utils.save_image(xdata_in, s, version)\n s.seek(0)\n xdata = dm3_image_utils.load_image(s)\n self.assertTrue(numpy.array_equal(data_in, xdata.data))\n self.assertEqual(data_descriptor_in, xdata.data_descriptor)\n\n def test_calibrations_write_read_round_trip(self):\n for version in (3, 4):\n s = io.BytesIO()\n data_in = numpy.ones((6, 4), numpy.float32)\n data_descriptor_in = DataAndMetadata.DataDescriptor(False, 0, 2)\n dimensional_calibrations_in = (Calibration.Calibration(1.1, 2.1, \"nm\"), Calibration.Calibration(2, 3, u\"µm\"))\n intensity_calibration_in = Calibration.Calibration(4.4, 5.5, \"six\")\n metadata_in = dict()\n xdata_in = DataAndMetadata.new_data_and_metadata(data_in, data_descriptor=data_descriptor_in, dimensional_calibrations=dimensional_calibrations_in, intensity_calibration=intensity_calibration_in, metadata=metadata_in)\n dm3_image_utils.save_image(xdata_in, s, version)\n s.seek(0)\n xdata = dm3_image_utils.load_image(s)\n self.assertEqual(tuple(dimensional_calibrations_in), tuple(xdata.dimensional_calibrations))\n self.assertEqual(intensity_calibration_in, xdata.intensity_calibration)\n\n def test_data_timestamp_write_read_round_trip(self):\n for version in (3, 4):\n s = io.BytesIO()\n data_in = numpy.ones((6, 4), numpy.float32)\n data_descriptor_in = DataAndMetadata.DataDescriptor(False, 0, 2)\n dimensional_calibrations_in = [Calibration.Calibration(1.1, 2.1, \"nm\"), Calibration.Calibration(2, 3, u\"µm\")]\n intensity_calibration_in = Calibration.Calibration(4.4, 5.5, \"six\")\n metadata_in = dict()\n timestamp_in = datetime.datetime(2013, 11, 18, 14, 5, 4, 0)\n timezone_in = \"America/Los_Angeles\"\n timezone_offset_in = \"-0700\"\n xdata_in = DataAndMetadata.new_data_and_metadata(data_in, data_descriptor=data_descriptor_in, dimensional_calibrations=dimensional_calibrations_in, intensity_calibration=intensity_calibration_in, metadata=metadata_in, timestamp=timestamp_in, timezone=timezone_in, timezone_offset=timezone_offset_in)\n dm3_image_utils.save_image(xdata_in, s, version)\n s.seek(0)\n xdata = dm3_image_utils.load_image(s)\n self.assertEqual(timestamp_in, xdata.timestamp)\n self.assertEqual(timezone_in, xdata.timezone)\n self.assertEqual(timezone_offset_in, xdata.timezone_offset)\n\n def test_metadata_write_read_round_trip(self):\n for version in (3, 4):\n s = io.BytesIO()\n data_in = numpy.ones((6, 4), numpy.float32)\n data_descriptor_in = DataAndMetadata.DataDescriptor(False, 0, 2)\n dimensional_calibrations_in = [Calibration.Calibration(1, 2, \"nm\"), Calibration.Calibration(2, 3, u\"µm\")]\n intensity_calibration_in = Calibration.Calibration(4, 5, \"six\")\n metadata_in = {\n \"abc\": 1, \"def\": \"abc\",\n \"efg\": {\n \"one\": 1, \"two\": \"TWO\",\n \"three\": [3, 4, 5], \"threef\": [3.0, 4.0, 5.0],\n \"four\": (32, 32), \"fourf\": (33.0, 34.0),\n \"six\": ((1, 2), (3, 4)), \"sixf\": ((1.0, 2.0), (3.0, 4.0)),\n \"seven\": [[1, 2], [3, 4]], \"sevenf\": [[1.0, 2.0], [3.0, 4.0]],\n # the following will not work until there is a schema or other type hinting to distinguish\n # this from the \"six\" case.\n # \"eight\": (1, 2, 3, 4), \"eightf\": (1.0, 2.0, 3.0, 4.0),\n }\n }\n xdata_in = DataAndMetadata.new_data_and_metadata(data_in, data_descriptor=data_descriptor_in, dimensional_calibrations=dimensional_calibrations_in, intensity_calibration=intensity_calibration_in, metadata=metadata_in)\n dm3_image_utils.save_image(xdata_in, s, version)\n s.seek(0)\n xdata = dm3_image_utils.load_image(s)\n self.assertEqual(metadata_in, xdata.metadata)\n\n def test_metadata_difficult_types_write_read_round_trip(self):\n for version in (3, 4):\n s = io.BytesIO()\n data_in = numpy.ones((6, 4), numpy.float32)\n data_descriptor_in = DataAndMetadata.DataDescriptor(False, 0, 2)\n dimensional_calibrations_in = [Calibration.Calibration(1, 2, \"nm\"), Calibration.Calibration(2, 3, u\"µm\")]\n intensity_calibration_in = Calibration.Calibration(4, 5, \"six\")\n metadata_in = {\"abc\": None, \"\": \"\", \"one\": [], \"two\": {}, \"three\": [1, None, 2]}\n xdata_in = DataAndMetadata.new_data_and_metadata(data_in, data_descriptor=data_descriptor_in, dimensional_calibrations=dimensional_calibrations_in, intensity_calibration=intensity_calibration_in, metadata=metadata_in)\n dm3_image_utils.save_image(xdata_in, s, version)\n s.seek(0)\n xdata = dm3_image_utils.load_image(s)\n metadata_expected = {\"one\": [], \"two\": {}, \"three\": [1, 2]}\n self.assertEqual(metadata_expected, xdata.metadata)\n\n def test_metadata_export_large_integer(self):\n for version in (3, 4):\n s = io.BytesIO()\n data_in = numpy.ones((6, 4), numpy.float32)\n data_descriptor_in = DataAndMetadata.DataDescriptor(False, 0, 2)\n dimensional_calibrations_in = [Calibration.Calibration(1, 2, \"nm\"), Calibration.Calibration(2, 3, u\"µm\")]\n intensity_calibration_in = Calibration.Calibration(4, 5, \"six\")\n metadata_in = {\"abc\": 999999999999}\n xdata_in = DataAndMetadata.new_data_and_metadata(data_in, data_descriptor=data_descriptor_in, dimensional_calibrations=dimensional_calibrations_in, intensity_calibration=intensity_calibration_in, metadata=metadata_in)\n dm3_image_utils.save_image(xdata_in, s, version)\n s.seek(0)\n xdata = dm3_image_utils.load_image(s)\n metadata_expected = {\"abc\": 999999999999}\n self.assertEqual(metadata_expected, xdata.metadata)\n\n def test_signal_type_round_trip(self):\n for version in (3, 4):\n s = io.BytesIO()\n data_in = numpy.ones((12,), numpy.float32)\n data_descriptor_in = DataAndMetadata.DataDescriptor(False, 0, 1)\n dimensional_calibrations_in = [Calibration.Calibration(1, 2, \"eV\")]\n intensity_calibration_in = Calibration.Calibration(4, 5, \"e\")\n metadata_in = {\"hardware_source\": {\"signal_type\": \"EELS\"}}\n xdata_in = DataAndMetadata.new_data_and_metadata(data_in, data_descriptor=data_descriptor_in, dimensional_calibrations=dimensional_calibrations_in, intensity_calibration=intensity_calibration_in, metadata=metadata_in)\n dm3_image_utils.save_image(xdata_in, s, version)\n s.seek(0)\n xdata = dm3_image_utils.load_image(s)\n metadata_expected = {'hardware_source': {'signal_type': 'EELS'}, 'Meta Data': {'Format': 'Spectrum', 'Signal': 'EELS'}}\n self.assertEqual(metadata_expected, xdata.metadata)\n\n def test_reference_images_load_properly(self):\n shape_data_descriptors = (\n ((3,), DataAndMetadata.DataDescriptor(False, 0, 1)), # spectrum\n ((3, 2), DataAndMetadata.DataDescriptor(False, 1, 1)), # 1d collection of spectra\n ((3, 4, 5), DataAndMetadata.DataDescriptor(False, 2, 1)), # 2d collection of spectra\n ((3, 2), DataAndMetadata.DataDescriptor(True, 0, 1)), # sequence of spectra\n ((3, 2), DataAndMetadata.DataDescriptor(False, 0, 2)), # image\n ((4, 3, 2), DataAndMetadata.DataDescriptor(False, 1, 2)), # 1d collection of images\n ((3, 4, 5), DataAndMetadata.DataDescriptor(True, 0, 2)), # sequence of images\n )\n for (shape, data_descriptor), version in itertools.product(shape_data_descriptors, (3, 4)):\n dimensional_calibrations = list()\n for index, dimension in enumerate(shape):\n dimensional_calibrations.append(Calibration.Calibration(1.0 + 0.1 * index, 2.0 + 0.2 * index, \"µ\" + \"n\" * index))\n intensity_calibration = Calibration.Calibration(4, 5, \"six\")\n data = numpy.arange(numpy.prod(shape), dtype=numpy.float32).reshape(shape)\n\n name = f\"ref_{'T' if data_descriptor.is_sequence else 'F'}_{data_descriptor.collection_dimension_count}_{data_descriptor.datum_dimension_count}.dm{version}\"\n\n # import pathlib\n # xdata = DataAndMetadata.new_data_and_metadata(data, dimensional_calibrations=dimensional_calibrations, intensity_calibration=intensity_calibration, data_descriptor=data_descriptor)\n # file_path = pathlib.Path(__file__).parent / \"resources\" / name\n # with file_path.open('wb') as f:\n # dm3_image_utils.save_image(xdata, f, version)\n\n try:\n s = io.BytesIO(pkgutil.get_data(__name__, f\"resources/{name}\"))\n xdata = dm3_image_utils.load_image(s)\n self.assertAlmostEqual(intensity_calibration.scale, xdata.intensity_calibration.scale, 6)\n self.assertAlmostEqual(intensity_calibration.offset, xdata.intensity_calibration.offset, 6)\n self.assertEqual(intensity_calibration.units, xdata.intensity_calibration.units)\n for c1, c2 in zip(dimensional_calibrations, xdata.dimensional_calibrations):\n self.assertAlmostEqual(c1.scale, c2.scale, 6)\n self.assertAlmostEqual(c1.offset, c2.offset, 6)\n self.assertEqual(c1.units, c2.units)\n self.assertEqual(data_descriptor, xdata.data_descriptor)\n self.assertTrue(numpy.array_equal(data, xdata.data))\n # print(f\"{name} {data_descriptor} PASS\")\n except Exception as e:\n print(f\"{name} {data_descriptor} FAIL\")\n raise\n\n def disabled_test_specific_file(self):\n file_path = \"/path/to/test.dm3\"\n with open(file_path, \"rb\") as f:\n xdata = dm3_image_utils.load_image(f)\n # file_path = \"/path/to/test-new.dm3\"\n # with open(file_path, \"wb\") as f:\n # dm3_image_utils.save_image(xdata, f, 3)\n\nif __name__ == \"__main__\":\n logging.getLogger().setLevel(logging.DEBUG)\n unittest.main()\n","repo_name":"nion-software/nionswift-io","sub_path":"nionswift_plugin/DM_IO/test/dm3parser_test.py","file_name":"dm3parser_test.py","file_ext":"py","file_size_in_byte":19676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"74163325535","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom torch.autograd import Variable\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1, is_last=False):\n super(BasicBlock, self).__init__()\n self.is_last = is_last\n self.conv1 = nn.Conv2d(\n in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False\n )\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(\n planes, planes, kernel_size=3, stride=1, padding=1, bias=False\n )\n self.bn2 = nn.BatchNorm2d(planes)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion * planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(\n in_planes,\n self.expansion * planes,\n kernel_size=1,\n stride=stride,\n bias=False,\n ),\n nn.BatchNorm2d(self.expansion * planes),\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.bn2(self.conv2(out))\n out += self.shortcut(x)\n preact = out\n out = F.relu(out)\n if self.is_last:\n return out, preact\n else:\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, in_planes, planes, stride=1, is_last=False):\n super(Bottleneck, self).__init__()\n self.is_last = is_last\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(\n planes, planes, kernel_size=3, stride=stride, padding=1, bias=False\n )\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(\n planes, self.expansion * planes, kernel_size=1, bias=False\n )\n self.bn3 = nn.BatchNorm2d(self.expansion * planes)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion * planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(\n in_planes,\n self.expansion * planes,\n kernel_size=1,\n stride=stride,\n bias=False,\n ),\n nn.BatchNorm2d(self.expansion * planes),\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = F.relu(self.bn2(self.conv2(out)))\n out = self.bn3(self.conv3(out))\n out += self.shortcut(x)\n preact = out\n out = F.relu(out)\n if self.is_last:\n return out, preact\n else:\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, block, num_blocks, in_channel=3, zero_init_residual=False):\n super(ResNet, self).__init__()\n self.in_planes = 64\n\n self.conv1 = nn.Conv2d(\n in_channel, 64, kernel_size=3, stride=1, padding=1, bias=False\n )\n self.bn1 = nn.BatchNorm2d(64)\n self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)\n self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)\n self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)\n self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode=\"fan_out\", nonlinearity=\"relu\")\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n # Zero-initialize the last BN in each residual branch,\n # so that the residual branch starts with zeros, and each residual block behaves\n # like an identity. This improves the model by 0.2~0.3% according to:\n # https://arxiv.org/abs/1706.02677\n if zero_init_residual:\n for m in self.modules():\n if isinstance(m, Bottleneck):\n nn.init.constant_(m.bn3.weight, 0)\n elif isinstance(m, BasicBlock):\n nn.init.constant_(m.bn2.weight, 0)\n\n def _make_layer(self, block, planes, num_blocks, stride):\n strides = [stride] + [1] * (num_blocks - 1)\n layers = []\n for i in range(num_blocks):\n stride = strides[i]\n layers.append(block(self.in_planes, planes, stride))\n self.in_planes = planes * block.expansion\n return nn.Sequential(*layers)\n\n def forward(self, x, layer=100):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = self.avgpool(out)\n out = torch.flatten(out, 1)\n return out\n\n\ndef resnet18(**kwargs):\n return ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)\n\n\ndef resnet34(**kwargs):\n return ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)\n\n\ndef resnet50(**kwargs):\n return ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)\n\n\ndef resnet101(**kwargs):\n return ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)\n\n\nmodel_dict = {\n \"resnet18\": [resnet18, 512],\n \"resnet34\": [resnet34, 512],\n \"resnet50\": [resnet50, 2048],\n \"resnet101\": [resnet101, 2048],\n}\n\n\nclass LinearBatchNorm(nn.Module):\n \"\"\"Implements BatchNorm1d by BatchNorm2d, for SyncBN purpose\"\"\"\n\n def __init__(self, dim, affine=True):\n super(LinearBatchNorm, self).__init__()\n self.dim = dim\n self.bn = nn.BatchNorm2d(dim, affine=affine)\n\n def forward(self, x):\n x = x.view(-1, self.dim, 1, 1)\n x = self.bn(x)\n x = x.view(-1, self.dim)\n return x\n\n\nclass ResNet_Model(nn.Module):\n \"\"\"encoder + classifier\"\"\"\n\n def __init__(self, name=\"resnet50\", num_classes=10):\n super(ResNet_Model, self).__init__()\n model_fun, dim_in = model_dict[name]\n self.encoder = model_fun()\n self.fc = nn.Linear(dim_in, num_classes)\n\n def forward(self, x):\n return self.fc(self.encoder(x))\n\n\nclass LinearClassifier(nn.Module):\n \"\"\"Linear classifier\"\"\"\n\n def __init__(self, name=\"resnet50\", num_classes=10):\n super(LinearClassifier, self).__init__()\n _, feat_dim = model_dict[name]\n self.fc = nn.Linear(feat_dim, num_classes)\n\n def forward(self, features):\n return self.fc(features)\n\n\nif torch.cuda.is_available():\n device = torch.device(\"cuda\")\nelse:\n device = torch.device(\"cpu\")\n\n\nclass PerturbationTool:\n def __init__(\n self,\n seed=0,\n epsilon=0.03137254901,\n num_steps=20,\n step_size=0.00784313725,\n dataset=\"c10\",\n ):\n self.epsilon = epsilon\n self.num_steps = num_steps\n self.step_size = step_size\n self.dataset = dataset\n self.seed = seed\n np.random.seed(seed)\n\n def random_noise(self):\n if self.dataset == \"c10\" or \"svhn\":\n noise_shape = [10, 3, 32, 32]\n elif self.dataset == \"c100\":\n noise_shape = [100, 3, 32, 32]\n elif self.dataset == \"imagenet100\":\n noise_shape = [100, 3, 224, 224]\n else:\n print(\"Error: Unexpected dataset\")\n random_noise = (\n torch.FloatTensor(*noise_shape)\n .uniform_(-self.epsilon, self.epsilon)\n .to(device)\n )\n\n return random_noise\n\n def min_min_attack(\n self,\n images,\n labels,\n model,\n optimizer,\n criterion,\n random_noise=None,\n ):\n if random_noise is None:\n random_noise = (\n torch.FloatTensor(*images.shape)\n .uniform_(-self.epsilon, self.epsilon)\n .to(device)\n )\n\n perturb_img = Variable(images.data + random_noise, requires_grad=True)\n perturb_img = Variable(torch.clamp(perturb_img, 0, 1), requires_grad=True)\n eta = random_noise\n for _ in range(self.num_steps):\n opt = torch.optim.SGD([perturb_img], lr=1e-2)\n opt.zero_grad()\n model.zero_grad()\n if isinstance(criterion, torch.nn.CrossEntropyLoss):\n if hasattr(model, \"classify\"):\n model.classify = True\n logits = model(perturb_img)\n loss = criterion(logits, labels)\n else:\n logits, loss = criterion(model, perturb_img, labels, optimizer)\n perturb_img.retain_grad()\n loss.backward()\n eta = self.step_size * perturb_img.grad.data.sign() * (-1)\n perturb_img = Variable(perturb_img.data + eta, requires_grad=True)\n eta = torch.clamp(\n perturb_img.data - images.data, -self.epsilon, self.epsilon\n )\n perturb_img = Variable(images.data + eta, requires_grad=True)\n perturb_img = Variable(torch.clamp(perturb_img, 0, 1), requires_grad=True)\n\n return perturb_img, eta\n\n def min_max_attack(\n self,\n images,\n labels,\n model,\n optimizer,\n criterion,\n random_noise=None,\n ):\n if random_noise is None:\n random_noise = (\n torch.FloatTensor(*images.shape)\n .uniform_(-self.epsilon, self.epsilon)\n .to(device)\n )\n\n perturb_img = Variable(images.data + random_noise, requires_grad=True)\n perturb_img = Variable(torch.clamp(perturb_img, 0, 1), requires_grad=True)\n eta = random_noise\n for _ in range(self.num_steps):\n opt = torch.optim.SGD([perturb_img], lr=1e-3)\n opt.zero_grad()\n model.zero_grad()\n if isinstance(criterion, torch.nn.CrossEntropyLoss):\n logits = model(perturb_img)\n loss = criterion(logits, labels)\n else:\n logits, loss = criterion(model, perturb_img, labels, optimizer)\n loss.backward()\n\n eta = self.step_size * perturb_img.grad.data.sign()\n perturb_img = Variable(perturb_img.data + eta, requires_grad=True)\n eta = torch.clamp(\n perturb_img.data - images.data, -self.epsilon, self.epsilon\n )\n perturb_img = Variable(images.data + eta, requires_grad=True)\n perturb_img = Variable(torch.clamp(perturb_img, 0, 1), requires_grad=True)\n\n return perturb_img, eta\n\n def _patch_noise_extend_to_img(\n self, noise, image_size=[3, 32, 32], patch_location=\"center\"\n ):\n c, h, w = image_size[0], image_size[1], image_size[2]\n mask = np.zeros((c, h, w), np.float32)\n x_len, y_len = noise.shape[1], noise.shape[1]\n\n if patch_location == \"center\" or (h == w == x_len == y_len):\n x = h // 2\n y = w // 2\n elif patch_location == \"random\":\n x = np.random.randint(x_len // 2, w - x_len // 2)\n y = np.random.randint(y_len // 2, h - y_len // 2)\n else:\n raise (\"Invalid patch location\")\n\n x1 = np.clip(x - x_len // 2, 0, h)\n x2 = np.clip(x + x_len // 2, 0, h)\n y1 = np.clip(y - y_len // 2, 0, w)\n y2 = np.clip(y + y_len // 2, 0, w)\n if type(noise) is np.ndarray:\n pass\n else:\n mask[:, x1:x2, y1:y2] = noise.cpu().numpy()\n return ((x1, x2, y1, y2), torch.from_numpy(mask).to(device))\n","repo_name":"lafeat/apbench","sub_path":"attack/basic/em_utils.py","file_name":"em_utils.py","file_ext":"py","file_size_in_byte":11748,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"33"} +{"seq_id":"8674298346","text":"from fastai.torch_core import to_np\nfrom fastrenewables.tabular.learner import fast_prediction as fast_prediction_mlp\nfrom fastrenewables.timeseries.learner import fast_prediction_ts as fast_prediction_tcn\nfrom fastrenewables.utils import filter_preds\nimport gridfs\nimport pandas as pd\nfrom deelea.mongo import (\n filter_results_by_config,\n get_model_from_artifacts,\n get_results_of_db,\n)\n\nfrom deelea.utils_models import ModelType\n\n\ndef get_indexes_and_targets(model_type, to_train, to_test):\n if model_type == ModelType.MLP:\n indexes_train, indexes_test = to_train.items.index, to_test.items.index\n targets_train, targets_test = (\n to_train.ys.values.ravel(),\n to_test.ys.values.ravel(),\n )\n elif model_type == ModelType.TCN:\n indexes_train, indexes_test = (\n to_train.indexes.reshape(-1),\n to_test.indexes.reshape(-1),\n )\n\n targets_train, targets_test = (\n to_np(to_train.ys).ravel(),\n to_np(to_test.ys).ravel(),\n )\n else:\n raise ValueError\n\n return (\n indexes_train,\n indexes_test,\n targets_train,\n targets_test,\n )\n\n\ndef get_prediction_setup(\n model_config, sacred_config_mlp_models, sacred_config_tcn_models\n):\n if model_config.model_type == ModelType.MLP:\n sacred_config = sacred_config_mlp_models\n fast_prediction = fast_prediction_mlp\n elif model_config.model_type == ModelType.TCN:\n sacred_config = sacred_config_tcn_models\n fast_prediction = fast_prediction_tcn\n else:\n raise ValueError\n\n return (\n sacred_config,\n fast_prediction,\n )\n\n\ndef get_predictions(to_train, to_test, fast_prediction, model, return_targets=True):\n preds_train, targets_train = fast_prediction(\n model.model, to_train, flatten=True, filter=False\n )\n preds_test, targets_test = fast_prediction(\n model.model, to_test, flatten=True, filter=False\n )\n\n preds_train, targets_train = filter_preds(\n preds_train, targets_train, filter_nas=False\n )\n\n preds_test, targets_test = filter_preds(preds_test, targets_test, filter_nas=False)\n if return_targets:\n return preds_train, preds_test, targets_train, targets_test\n else:\n return preds_train, preds_test\n\n\ndef get_model_by_config(data_config, model_config, sacred_config_model):\n df_res, db = get_results_of_db(model_config, data_config, sacred_config_model)\n df_res = df_res[df_res.Status == \"COMPLETED\"]\n grid_fs = gridfs.GridFS(db)\n\n df_res_filtered = filter_results_by_config(model_config, data_config, df_res)\n source_model = get_model_from_artifacts(grid_fs, df_res_filtered)\n return source_model\n\n\ndef create_single_df(\n preds_train, preds_test, indexes_train, indexes_test, name, include_test_flag=False\n):\n df_train = pd.DataFrame({name: preds_train}, index=indexes_train)\n df_test = pd.DataFrame({name: preds_test}, index=indexes_test)\n df_train.index.names = [\"TimeUTC\"]\n df_test.index.names = [\"TimeUTC\"]\n if include_test_flag:\n df_train[\"IsTest\"] = False\n df_test[\"IsTest\"] = True\n\n return pd.concat([df_train, df_test], axis=0)\n","repo_name":"scribbler00/deelea","sub_path":"deelea/forecasts.py","file_name":"forecasts.py","file_ext":"py","file_size_in_byte":3226,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"33"} +{"seq_id":"43173314490","text":"def get_dist_origin(x, y):\n\n return ((x ** 2) + (y ** 2)) ** (1/2)\n\ndef get_circle_dot_count(r):\n\n count = 0\n circle_on = 0\n\n x, y = r, 0\n\n while y <= r:\n\n while get_dist_origin(x, y) > r:\n x -= 1\n count += x + 1\n \n if get_dist_origin(x, y) == r:\n circle_on += 1\n\n y += 1\n \n total = (count * 2 - 1) + ((count - (r * 2) - 1) * 2)\n circle__on_total = circle_on * 2 + ((circle_on - 2) * 2)\n \n \n return [total, circle__on_total]\n\n\ndef solution(r1, r2):\n\n '''\n 나의 풀이\n 반지름 두개가 주어지면 큰 원과 작은 원 사이의 \n 정수의 위치값을 가지는 좌표의 개수를 카운팅 하는 문제\n (원 위에 있는 좌표도 포함)\n\n 나의 접근법\n 처음엔 반지름당 가지는 좌표의 개수를 구해서\n 해볼려고 했으나 점화식?? 을 모르겠어서 포기..\n\n 그 후엔 0,0 ~ r,r 까지 전부 탐색하고 해보려고 했으나\n 시간초과가 떴었음\n\n 그래서 생각한 방법이\n y값을 0 ~ r까지 1씩 증가 시키면서\n x값은 r ~ 0 까지 탐색 \n 만약 (x, y) 가 만족하면 (x-1, y), (x-2, y), ... (0, y) 는 전부 만족하는 좌표 이므로\n 해당 개수를 더해주고\n 탐색하면서 원 위에 있는 좌표는 따로 개수를 카운팅해줌\n\n 그 후 큰원의 좌표개수와 작은 원의 자표개수를 빼주고 작은 원에 원 위에 있는 좌표값을\n 더해주면 정답이 나옴\n\n 진짜 또 거의 3시간 가까이 품....\n 진짜 심각하다.. ㅠㅠ 수학 부분은 너~~~~~~무 부족한듯..\n 이번껀 문제가 문제가 아니라 내가 너무 문제인듯 ㅋㅋㅋㅋㅋ\n '''\n\n answer = 0\n\n r1_dot = get_circle_dot_count(r1)\n r2_dot = get_circle_dot_count(r2)\n\n print(r1_dot, r2_dot)\n\n answer = r2_dot[0] - r1_dot[0] + r1_dot[1]\n\n return answer\n\n\nprint(solution(999999, 1000000))\n\nfrom math import sqrt\n\ndef firstSolu(r1, r2):\n\n '''\n 다른 사람 풀이\n https://velog.io/@error_io/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EB%91%90-%EC%9B%90-%EC%82%AC%EC%9D%B4-%EC%A0%95%EC%88%98%EC%9D%98-%EC%8C%8D-Lv.2-Python\n\n 풀이 엄청 간단할 것 같더라...ㅋ\n 근데 이해 1도 안감... 뭐지.. ㅋㅋㅋㅋㅋㅋ\n 한쪽만 구해서 * 4해주는 것 까진 이해 했는데\n 자세히는 모르겠ㅇㅁ...\n '''\n\n quar = 0\n for i in range(0, r2):\n quar += int(sqrt(r2**2 - i**2)) - int(sqrt(max(0, r1**2 - i**2 - 1)))\n return quar * 4","repo_name":"youhavetopay/Algorithm","sub_path":"Programmers/연습문제/레벨 2/두 원 사이의 정수 쌍.py","file_name":"두 원 사이의 정수 쌍.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"9271658580","text":"# EXTERNAL IMPORT\nfrom django.shortcuts import render\nfrom django.views.generic import ListView\nfrom django.core.mail import EmailMessage\nfrom django.template.loader import render_to_string\n\n# INTERNAL IMPORT\nfrom .models import Portfolio, TeckStack\nfrom django.conf import settings\n\n\nclass Home(ListView):\n context_object_name = 'item' \n template_name = 'home.html'\n queryset = Portfolio.objects.all()[:4]\n\n def get_context_data(self, **kwargs):\n context = super(Home, self).get_context_data(**kwargs)\n context['tech'] = TeckStack.objects.all()\n return context\n \n\ndef aboutPage(request, template_name='about.html'):\n pass\n return render(request, template_name)\n\n\ndef projectsPage(request):\n projects = Portfolio.objects.all()\n context = {\n \"projects\":projects\n }\n return render(request, 'projects.html', context)\n\n\ndef sendEmail(request):\n\n if request.method == 'POST':\n\n template = render_to_string('email_template.html',{\n 'name':request.POST['name'],\n 'email':request.POST['email'],\n 'message':request.POST['message'],\n })\n\n email = EmailMessage(\n request.POST['subject'],\n template,\n settings.EMAIL_HOST_USER,\n ['pushkaraditya916@gmail.com']\n )\n email.Fail_silently=False\n email.send()\n return render(request, 'email_sent.html')","repo_name":"aditya-pushkar/django-portfolio","sub_path":"project/mysite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"72508942815","text":"from sklearn.preprocessing import OneHotEncoder\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom category_encoders import TargetEncoder\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n\r\ntraindata = pd.read_table('data/train.csv')\r\n#traindata = traindata.sample(frac=0.1,random_state=42)\r\ntrainy = traindata.iloc[:,13]\r\ntestdata = pd.read_table('data/test.csv')\r\ntesty = testdata.iloc[:,13]\r\nalldata = pd.concat([traindata,testdata])\r\nally = pd.concat([trainy,testy])\r\nprint(traindata.shape)\r\nprint(alldata.shape)\r\nprint(alldata.count())\r\nalldata.to_csv('data/alldata.csv')\r\n\r\nenc =TargetEncoder(cols=['Anon Student Id','Problem Name','Problem Hierarchy','Step Name','KC(Default)'])\r\nto = enc.fit_transform(alldata, ally)\r\nto.to_csv('data/target_all.csv')\r\ntotrain = to.iloc[:232744]\r\ntotest = to.iloc[232744:233884]\r\ntotrain.to_csv('data/target_train.csv')\r\ntotest.to_csv('data/target_test.csv')\r\n\r\n\r\n# traindata = alldata\r\n# encoder = LabelEncoder()\r\n# ID = encoder.fit_transform(traindata['Anon Student Id'].values)\r\n# ID = np.array([ID]).T\r\n# PName = encoder.fit_transform(traindata['Problem Name'].values)\r\n# PName = np.array([PName]).T\r\n# PHierarchy = encoder.fit_transform(traindata['Problem Hierarchy'].values)\r\n# PHierarchy = np.array([PHierarchy]).T\r\n# SName = encoder.fit_transform(traindata['Step Name'].values)\r\n# SName = np.array([SName]).T\r\n# KC = encoder.fit_transform(traindata['KC(Default)'].values)\r\n# KC = np.array([KC]).T\r\n#\r\n# enc = OneHotEncoder()\r\n# ID=enc.fit_transform(ID)\r\n# ID=ID.toarray()\r\n# PName=enc.fit_transform(PName)\r\n# PName=PName.toarray()\r\n# PHierarchy=enc.fit_transform(PHierarchy)\r\n# PHierarchy=PHierarchy.toarray()\r\n# SName=enc.fit_transform(SName)\r\n# SName=SName.toarray()\r\n# KC=enc.fit_transform(KC)\r\n# KC=KC.toarray()\r\n\r\n\r\n","repo_name":"bin-soo/CS150A-Project","sub_path":"tagetEncoding.py","file_name":"tagetEncoding.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"71216747296","text":"import logging\nimport numpy as np\nimport os\nimport tritonclient.grpc as grpcclient\n\n\nlogging.basicConfig(format=\"%(asctime)s %(message)s\")\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\nTRITON_SERVER_URL = os.getenv(\"TRITON_SERVER_URL\", \"0.0.0.0\")\nURL = f\"{TRITON_SERVER_URL}:8001\"\n\nif __name__ == \"__main__\":\n client = grpcclient.InferenceServerClient(url=URL, verbose=False)\n\n input_text = [\"Translate English to German: What is a computer?\"]\n max_new_tokens = [64]\n num_beams = [3]\n\n input_text = np.array(input_text, dtype='|S64').reshape((-1,1))\n max_new_tokens = np.array(max_new_tokens).reshape((-1,1))\n num_beams = np.array(num_beams).reshape((-1,1))\n\n inputs = [\n grpcclient.InferInput(\"input_text\", input_text.shape, \"BYTES\"),\n grpcclient.InferInput(\"max_new_tokens\", max_new_tokens.shape, \"INT64\"),\n grpcclient.InferInput(\"num_beams\", num_beams.shape, \"INT64\")\n ]\n\n inputs[0].set_data_from_numpy(input_text)\n inputs[1].set_data_from_numpy(max_new_tokens)\n inputs[2].set_data_from_numpy(num_beams)\n\n triton_outputs = [grpcclient.InferRequestedOutput(\"output_text\")]\n\n infer_result = client.infer(\n \"t5\",\n inputs,\n model_version=\"1\",\n )\n\n logger.info(str(infer_result.as_numpy(\"output_text\").astype(str)))","repo_name":"tuttlebr/T5-TensorRT-LLM","sub_path":"workspace/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"28252570264","text":"# coding=utf-8\nimport math\n\nfrom RSA import encrypt, pad_encrypt, decrypt, del_pad\nfrom document_util import read_document, write_document, read_document_style\nfrom util import count, Word\n\n\ndef encrypt_watermarking(file_name, mark_file_name, marks=\"1111000\"):\n # encrypt & binary\n encrypt_mark = encrypt(code=marks)\n len_encrypt_mark = len(encrypt_mark)\n binary_mark = pad_encrypt(encrypt_mark)\n # print(binary_mark)\n binary_mark_len = int(len(binary_mark) / 8)\n\n # read from file && count by freq\n contents = read_document(file_name)\n word_count = count(contents)\n words = Word.get_words(word_count.keys())\n\n assert len(words) >= binary_mark_len, u\"mark的长度超过了文本的字符数,尝试缩小mark或增长文本\"\n # watermarking\n for index, word in enumerate(words[:binary_mark_len]):\n mark = binary_mark[index * 8:index * 8 + 8]\n word.set_special_style(True, mark)\n\n # print\n write_document(words, mark_file_name, contents=contents)\n\n return len_encrypt_mark\n\n\ndef watermarking(file_name, mark_file_name, marks=\"1111000\"):\n # read from file && count by freq\n contents = read_document(file_name)\n word_count = count(contents)\n words = Word.get_words(word_count.keys())\n\n assert len(words) >= len(marks), u\"mark的长度超过了文本的字符数,尝试缩小mark或增长文本\"\n # watermarking\n for mark, word in zip(marks, words[:len(marks)]):\n if mark == '1':\n word.set_special_style(True, '00000001')\n else:\n word.set_special_style(False, '00000000')\n\n # print\n write_document(words, mark_file_name, contents=contents)\n\n return\n\n\ndef encrypt_extract(mark_file_name, len_watermark=7, marks=''):\n # read && count\n word_style = read_document_style(mark_file_name)\n\n contents = read_document(mark_file_name)\n word_count = count(contents)\n\n # marking\n watermark = ''\n\n for index, word in enumerate(word_count):\n if index >= math.ceil(len_watermark/8):\n break\n special_mark = word_style.get(word)\n watermark += special_mark\n\n # print(watermark)\n watermark = del_pad(watermark, len_watermark)\n code = decrypt(origin_code=marks, b=watermark)\n print(code)\n\n\ndef extract(mark_file_name, len_watermark=7):\n # read && count\n word_style = read_document_style(mark_file_name)\n\n contents = read_document(mark_file_name)\n word_count = count(contents)\n\n # marking\n watermark = ''\n\n for index, word in enumerate(word_count):\n if index >= len_watermark:\n break\n special = word_style.get(word)\n if special == '00000001':\n watermark += '1'\n else:\n watermark += '0'\n\n print(watermark)\n\n\nif __name__ == '__main__':\n file_name = \"data/demo.docx\"\n mark_file_name = \"data/demo_mark.docx\"\n\n # 加密情况\n marks = \"hello,wangqi\"\n len_encrypt_mark = encrypt_watermarking(file_name, mark_file_name, marks)\n encrypt_extract(mark_file_name, len_encrypt_mark, marks)\n\n # 不加密情况\n marks = '1110001'\n watermarking(file_name, mark_file_name, marks=marks)\n extract(mark_file_name, len_watermark=len(marks))","repo_name":"wangqi1996/text_digital_watermarking","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"16327321451","text":"from cProfile import label\nimport joblib\nfrom pathlib import Path\nfrom typing import Union, TypeVar\n\nimport pandas as pd\nfrom predictor.exceptions import NoTextException\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nimport os\nfrom xgboost import XGBClassifier\nfrom sklearn.calibration import CalibratedClassifierCV\n\nVector = TypeVar('Vector')\n\n\nclass ClassifierPredictor:\n def __init__(\n self,\n column_name : str = None,\n tfidf_path : Union[str, Path] =None,\n model_path : Union[str, Path]=None,\n label_encoder_path : Union[str, Path] =None,\n agro_eco : bool=False,\n gaul : bool =False,\n calibrate : bool =True,\n **kwargs\n ):\n \"\"\"A class that generates predictions based on a trained XGBoost model. Can predict based on Ugandan Regions, GAUL regions, or FAO agro-ecological zones. Optionally predicts gaul regions using an ensemble calibrated classifier.\n \n Example:\n >>> surnames = pd.DataFrame({'names':['Ahimbisibwe', 'Auma', 'Amin', \n 'Makubuya', 'Museveni', 'Oculi', 'Kadaga']})\n >>> c = ClassifierPredictor(column_name='names')\n >>> predict_xgb = c.predict(surnames, \n get_label_names=True, \n predict_prob = True,\n df_out =True)\n\n Args:\n column_name (str, optional): When passing a pandas dataframe, the name of the columns with surnames. Defaults to None.\n tfidf_path (Union[str, Path], optional): the path of the joblib dump of the tfidf transformer. Defaults to None.\n model_path (Union[str, Path], optional): the path of the joblib dump of the trained model. Defaults to None.\n label_encoder_path (Union[str, Path], optional): the path of the joblib dump of the label encoder. Defaults to None.\n agro_eco (bool, optional): Whether to predict agro-ecological zones. Defaults to False.\n gaul (bool, optional): whether to predict gaul regions. Defaults to False.\n calibrate (bool, optional): whether to predict gaul regions. Defaults to True.\n \"\"\" \n if agro_eco ==True and gaul==True:\n \n raise Exception(\"You can't have agro_eco and gaul both true\")\n \n\n if tfidf_path is None:\n \n if agro_eco:\n # tfidf_path = Path(\n # \"predictor\",\n # \"saved_models\",\n # \"tfidf_multilabel_False_nokampala_True_agro_zone_smote_False_opt.joblib\",\n # )\n tfidf_path = \"predictor/saved_models/tfidf_multilabel_False_nokampala_True_agro_zone_smote_False_opt.joblib\"\n elif gaul:\n # tfidf_path = Path(\n # \"predictor\",\n # \"saved_models\",\n # \"tfidf_multilabel_False_nokampala_True_gaul_smote_False_gaul_opt.joblib\",\n # )\n \n tfidf_path = \"predictor/saved_models/tfidf_multilabel_False_nokampala_True_gaul_smote_False_gaul_opt.joblib\"\n\n else:\n # tfidf_path = Path(\n # \"predictor\",\n # \"saved_models\",\n # \"tfidf_multilabel_False_nokampala_True.joblib\",\n # )\n \n tfidf_path = \"predictor/saved_models/tfidf_multilabel_False_nokampala_True.joblib\"\n else:\n tfidf_path = Path(tfidf_path)\n\n if label_encoder_path is None:\n\n if agro_eco:\n # label_encoder_path = Path(\n # \"predictor\",\n # \"saved_models\",\n # \"label_encoder_multilabel_False_nokampala_True_agro_zone_smote_False_opt.joblib\",\n # )\n label_encoder_path = \"predictor/saved_models/label_encoder_multilabel_False_nokampala_True_agro_zone_smote_False_opt.joblib\"\n elif gaul:\n # label_encoder_path = Path(\n # \"predictor\",\n # \"saved_models\",\n # \"label_encoder_multilabel_False_nokampala_True_gaul_smote_False_gaul_opt.joblib\",\n # )\n \n label_encoder_path = \"predictor/saved_models/label_encoder_multilabel_False_nokampala_True_gaul_smote_False_gaul_opt.joblib\"\n \n else:\n # label_encoder_path = Path(\n # \"predictor\",\n # \"saved_models\",\n # \"label_encoder_multilabel_False_nokampala_True.joblib\",\n # )\n \n label_encoder_path = \"predictor/saved_models/label_encoder_multilabel_False_nokampala_True.joblib\"\n else:\n label_encoder_path = Path(label_encoder_path)\n\n if model_path is None:\n\n if agro_eco:\n # model_path = Path(\n # \"predictor\",\n # \"saved_models\",\n # \"xgb_None_multilabel_False_add_kampala_True_agro_zone_smote_False_opt.joblib\",\n # )\n model_path = \"predictor/saved_models/xgb_None_multilabel_False_add_kampala_True_agro_zone_smote_False_opt.joblib\"\n elif gaul:\n if calibrate:\n # model_path = Path(\n # \"predictor\",\n # 'saved_models',\n # 'xgb_None_calibrated_gaul_opt.joblib'\n # )\n model_path = \"predictor/saved_models/xgb_None_calibrated_gaul_opt.joblib\"\n else:\n # model_path = Path(\n # \"predictor\",\n # \"saved_models\",\n # \"xgb_None_multilabel_False_add_kampala_True_gaul_smote_False_gaul_opt.joblib\"\n # )\n model_path = \"predictor/saved_models/xgb_None_multilabel_False_add_kampala_True_gaul_smote_False_gaul_opt.joblib\"\n \n else:\n # model_path = Path(\n # \"predictor\",\n # \"saved_models\",\n # \"xgb_None_multilabel_False_add_kampala_True.joblib\",\n # )\n model_path = \"predictor/saved_models/xgb_None_multilabel_False_add_kampala_True.joblib\"\n else:\n model_path = Path(model_path)\n\n self.tfidf_path = tfidf_path\n self.model_path = model_path\n self.label_encoder_path = label_encoder_path\n \n self.column_name = column_name\n\n def load_tfidf(self) -> TfidfVectorizer:\n \"\"\"Loads Tfidf transformer. See [here](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html) for information on all functionality.\n \n Returns:\n TfidfVectorizer: A sklearn Tfidf Vectorizer Object\n \"\"\"\n\n return joblib.load(self.tfidf_path)\n\n def load_model(self) -> Union[XGBClassifier, CalibratedClassifierCV]:\n \"\"\"Loads pickled trained classifier. Current one is an XGBoost classifier.\n See [here](https://xgboost.readthedocs.io/en/latest/) for more details.\n \n Returns:\n Union[XGBClassifier, CalibratedClassifierCV]: Depending on the option, either a trained XGBoost Classifier or an sklearn calibrated classifier.\n \"\"\"\n return joblib.load(self.model_path)\n\n def load_label_encoder(self) -> CountVectorizer:\n \"\"\"Loads label encoder. See [here](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html)\n for more information.\n \n Returns:\n CountVectorizer: An sklearn Count Vectorizer object\n\n \"\"\"\n return joblib.load(self.label_encoder_path)\n\n def process_text(self, text: Union[str, list]) -> list:\n \"\"\"Pre-processes input text to make it ready for prediction.\n\n Arguments:\n text (str or list-like object): The input string or list of strings that are to be processed\n\n Returns:\n list: Pre-processed list of strings\n \"\"\"\n\n if isinstance(text, str):\n\n text = [text]\n elif isinstance(text, pd.DataFrame):\n if self.column_name is None:\n raise Exception(\"Got a dataframe, but did not get `column_name`\")\n text = text[self.column_name].tolist()\n\n processed_text = [i.lower().rstrip().lstrip() for i in text]\n\n return processed_text\n\n def transform_text(self, text : str = None) -> Vector:\n \"\"\"A function that takes a list of surnames or strings and transforms them through the tf-idf transformer\n\n Args:\n text (str, optional): the text to be transformed. Defaults to None.\n\n Raises:\n NoTextException: Raises if no text was given\n\n Returns:\n Vector: A sparse matrix of numpy matrix\n \"\"\" \n\n if text is None:\n raise NoTextException(\"No text was given for transformation.\")\n\n tfidf = self.load_tfidf()\n\n return tfidf.transform(text)\n\n def predict(self, \n text : list =None, \n get_label_names : bool=False, \n predict_prob : bool=False, \n df_out : bool=False) -> Union[pd.DataFrame, list]: \n \"\"\"Predicts origin based on classifier\n\n Keyword Arguments:\n text (list): List of strings to be predicted (default: {None})\n get_label_names (bool): Whether to output the label names after prediction (default: {False})\n predict_prob (bool): whether to give probabilities of coming from each region (default: {False})\n df_out (bool): whether to output a pandas dataframe (default: {False})\n \n >>> from predictor.classifier_prediction import ClassifierPredictor\n >>> # Instantiate predictor\n >>> c = ClassifierPredictor()\n >>> # Predict\n >>> prediction = c.predict(['Auma'])\n >>> print(prediction)\n\n Returns:\n Union[pd.DataFrame, list]: An object that contains predictions from the model\n \"\"\"\n labels = self.load_label_encoder()\n raw_text_aux = text.copy(deep = True)\n text = self.process_text(text)\n raw_text = raw_text_aux.assign(processed_text = text).set_index('processed_text')\n X = self.transform_text(text)\n\n model = self.load_model()\n\n if get_label_names:\n if predict_prob:\n label_names = labels.classes_\n probs = model.predict_proba(X)\n result = {\n t: {\n label_name: prob\n for label_name, prob in zip(label_names, probs[i])\n }\n for t, i in zip(text, range(len(probs)))\n }\n\n else:\n result = {\n name: prediction\n for name, prediction in zip(\n text, labels.inverse_transform(model.predict(X))\n )\n }\n else:\n if predict_prob:\n result = model.predict_proba(X)\n else:\n result = model.predict(X)\n\n if df_out:\n try:\n return (\n pd.DataFrame(result).T\n .sort_index()\n .merge(raw_text, \n left_index = True, \n right_index = True)\n .reset_index()\n .set_index(self.column_name)\n .rename({'index' : 'processed_surname'}, axis=1)\n )\n \n except ValueError:\n return pd.DataFrame(result.values(), index = result.keys()).rename({0 : 'prediction'}, axis=1)\n else:\n return result\n\n","repo_name":"amichuda/surname_region_prediction","sub_path":"predictor/classifier_prediction.py","file_name":"classifier_prediction.py","file_ext":"py","file_size_in_byte":12085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"12427547751","text":"import pygame\n\nfrom pygame.math import Vector2\nfrom utility import DDA, CvCoor, COLORS, FontText, persamaan, Button, InputBox, Tema\n\nclass Kartesius:\n\tpos = Vector2(0, 0)\n\tfokus = 100\n\n\t@classmethod\n\tdef render(cls, surface, menu):\n\t\tcolor = COLORS.fg_color\n\n\t\tx, y = CvCoor.xy(cls.pos.x, cls.pos.y)\n\t\tDDA((0, y), (CvCoor.size[0], y), surface, color) # X\n\t\tDDA((x, 0), (x, CvCoor.size[1]), surface, color) # y\n\n\t\tx, y = CvCoor.x(cls.fokus), CvCoor.y(cls.pos.y)\n\t\tDDA((x, y), (x, y - 10), surface, color) # F\n\t\tFontText.render(surface, FontText.font_22, (x, y - 25), \"f\", True, color)\n\n\t\tx = CvCoor.x(cls.fokus * 2)\n\t\tDDA((x, y), (x, y - 10), surface, color) # 2F\n\t\tFontText.render(surface, FontText.font_22, (x, y - 25), \"r\", True, color)\n\n\t\tif menu.cembung:\n\t\t\tx = CvCoor.x(cls.fokus * -1)\n\t\t\tDDA((x, y), (x, y - 10), surface, color) # F Mirror\n\t\t\tFontText.render(surface, FontText.font_22, (x, y - 25), \"f\", True, color)\n\n\t\t\tx = CvCoor.x(cls.fokus * 2 * -1)\n\t\t\tDDA((x, y), (x, y - 10), surface, color) # 2F Mirror\n\t\t\tFontText.render(surface, FontText.font_22, (x, y - 25), \"r\", True, color)\n\n\t@classmethod\n\tdef handle_movement(cls, key_pressed, mouse_pressed, mouse_pos):\n\t\tif key_pressed[pygame.K_q]:\n\t\t\tcls.fokus += 1\n\t\tif key_pressed[pygame.K_e]:\n\t\t\tcls.fokus -= 1\n\n\t\tif mouse_pressed[2] and not Button.check_all_col(mouse_pos) and not InputBox.check_all_col(mouse_pos):\n\t\t\tcls.fokus = (mouse_pos[0] - CvCoor.size[0]//2) * -1\n\n\t@classmethod\n\tdef handle_mirror(cls):\n\t\tif cls.fokus < 0:\n\t\t\tcls.fokus *= -1\n\n\t@classmethod\n\tdef set_fokus(cls, value):\n\t\tcls.fokus = value\n\n\t@classmethod\n\tdef get_fokus(cls):\n\t\treturn cls.fokus\n\nclass Benda:\n\tjarak = 200\n\ttinggi = 100\n\tsinar_1 = 0\n\tsinar_2 = 0\n\tmirror_x = False\n\tmirror_y = False\n\tcolor_awal = COLORS.green\n\tcolor_pantul = COLORS.greenyellow\n\n\t@classmethod\n\tdef render_cembung(cls, surface):\n\n\t\tx, y = CvCoor.xy(cls.jarak, cls.tinggi)\n\t\tkt_x, kt_y = CvCoor.xy(Kartesius.pos.x, Kartesius.pos.y)\n\t\tfokus = CvCoor.x(Kartesius.fokus * -1)\n\n\t\tcls.draw(surface, x, y, kt_y)\n\n\t\t# Sinar A ke garis kartesius\n\t\tx_new, y_new = persamaan((kt_x, y), (0, y), cls.sinar_1)\n\t\tpygame.draw.line(surface, cls.color_awal, (kt_x, y), (x_new, y_new))\n\n\t\t# Sinar A ke fokus\n\t\tx_new, y_new = persamaan((kt_x, y), (fokus, kt_y), cls.sinar_2)\n\t\tpygame.draw.line(surface, cls.color_pantul, (kt_x, y), (x_new, y_new))\n\n\t\t# Sinar C\n\t\tx_new, y_new = persamaan((kt_x, kt_y), (x, y), 0)\n\t\tpygame.draw.line(surface, COLORS.blue, (kt_x, kt_y), (x_new, y_new))\n\n\t@classmethod\n\tdef render_cekung(cls, surface):\n\t\tx, y = CvCoor.xy(cls.jarak, cls.tinggi)\n\t\tkt_x, kt_y = CvCoor.xy(Kartesius.pos.x, Kartesius.pos.y)\n\t\tbayangan_x, bayangan_y = CvCoor.xy(Bayangan.jarak, Bayangan.tinggi * -1)\n\n\t\tcls.draw(surface, x, y, kt_y)\n\n\t\t# Sinar A ke garis kartesius\n\t\tpygame.draw.line(surface, cls.color_awal, (kt_x, y), (x, y))\n\n\t\t# Sinar A ke fokus\n\t\tpygame.draw.line(surface, cls.color_pantul, (kt_x, y), (bayangan_x, bayangan_y))\n\n\t@classmethod\n\tdef draw(cls, surface, x, y, kt_y):\n\t\t# Gambar benda\n\t\timg = pygame.transform.flip(Tema.curr_chr, cls.mirror_x, cls.mirror_y)\n\t\tsize = img.get_size()\n\t\tw, h = cls.tinggi * size[0]//size[1], cls.tinggi\n\t\tif w < 0:\n\t\t\tw *= -1\n\t\tif h < 0:\n\t\t\th *= -1\n\t\tif w > 1000:\n\t\t\tw = 1000\n\t\tif h > 1000:\n\t\t\th = 1000\n\t\timg = pygame.transform.scale(img, (w, h))\n\t\trect = img.get_rect(topleft=(x, y))\n\t\tif cls.mirror_y:\n\t\t\trect = img.get_rect(bottomleft=(x, y + 1))\n\t\tsurface.blit(img, rect)\n\n\t\tpygame.draw.line(surface, COLORS.fg_color, (x, kt_y), (x, y))\n\n\t@classmethod\n\tdef handle_mirror(cls):\n\t\t# Kalau gak mirror\n\t\tif cls.jarak < 0:\n\t\t\tcls.mirror_x = True\n\t\t\tcls.sinar_1 = CvCoor.size[0]\n\n\t\t\tif cls.jarak >= Kartesius.fokus:\n\t\t\t\tcls.sinar_2 = 0\n\t\t\telse:\n\t\t\t\tcls.sinar_2 = CvCoor.size[0]\n\t\telse:\n\t\t\t# Kalau mirror\n\t\t\tcls.mirror_x = False\n\t\t\tcls.sinar_1 = 0\n\n\t\t\tif cls.jarak <= Kartesius.fokus:\n\t\t\t\tcls.sinar_2 = 0\n\t\t\telse:\n\t\t\t\tcls.sinar_2 = CvCoor.size[0]\n\n\t\tif cls.tinggi < 0:\n\t\t\tcls.mirror_y = True\n\t\telse:\n\t\t\tcls.mirror_y = False\n\n\t@classmethod\n\tdef handle_movement(cls, key_pressed, mouse_pressed, mouse_pos):\n\t\tif key_pressed[pygame.K_a]:\n\t\t\tcls.jarak += 1\n\t\tif key_pressed[pygame.K_d]:\n\t\t\tcls.jarak -= 1\n\t\tif key_pressed[pygame.K_w]:\n\t\t\tcls.tinggi += 1\n\t\tif key_pressed[pygame.K_s]:\n\t\t\tcls.tinggi -= 1\n\n\t\tif mouse_pressed[0] and not Button.check_all_col(mouse_pos) and not InputBox.check_all_col(mouse_pos):\n\t\t\tcls.jarak = (mouse_pos[0] - CvCoor.size[0]//2) * -1\n\t\t\tcls.tinggi = (mouse_pos[1] - CvCoor.size[1]//2) * -1\n\n\t@classmethod\n\tdef set_jarak(cls, value):\n\t\tcls.jarak = value\n\n\t@classmethod\n\tdef get_jarak(cls):\n\t\treturn abs(cls.jarak)\n\n\t@classmethod\n\tdef set_tinggi(cls, value):\n\t\tcls.tinggi = value\n\n\t@classmethod\n\tdef get_tinggi(cls):\n\t\treturn cls.tinggi\n\nclass Bayangan:\n\tjarak = 0\n\ttinggi = 0\n\tmirror_x = True\n\tmirror_y = True\n\n\t@classmethod\n\tdef update(cls):\n\t\ttry:\n\t\t\tcls.jarak = int((Kartesius.fokus * Benda.jarak) / (Benda.jarak - Kartesius.fokus))\n\t\texcept ZeroDivisionError:\n\t\t\tcls.jarak = 0\n\t\ttry:\n\t\t\tcls.tinggi = int((cls.jarak / Benda.jarak) * Benda.tinggi)\n\t\texcept ZeroDivisionError:\n\t\t\tcls.tinggi = 0\n\n\t@classmethod\n\tdef render_cembung(cls, surface):\n\n\t\t# Convert Kordinat\n\t\tx, y = CvCoor.xy(cls.jarak * -1, cls.tinggi * -1)\n\t\tkt_x, kt_y = CvCoor.xy(Kartesius.pos.x, Kartesius.pos.y)\n\t\tfokus = CvCoor.x(Kartesius.fokus)\n\n\t\tcls.draw(surface, x, y, kt_y)\n\n\t\t# Sinar B ke garis kartesius\n\t\tx_new, y_new = persamaan((kt_x, y), (0, y), Benda.sinar_2)\n\t\tpygame.draw.line(surface, COLORS.deeppink, (kt_x, y), (x_new, y_new))\n\n\t\t# Sinar B ke fokus\n\t\tx_new, y_new = persamaan((kt_x, y), (fokus, kt_y), Benda.sinar_1)\n\t\tpygame.draw.line(surface, COLORS.red, (kt_x, y), (x_new, y_new))\n\n\t\t# Sinar C\n\t\tx_new, y_new = persamaan((kt_x, kt_y), (x, y), CvCoor.size[0])\n\t\tpygame.draw.line(surface, COLORS.deepskyblue, (kt_x, kt_y), (x_new, y_new))\n\n\t@classmethod\n\tdef render_cekung(cls, surface):\n\t\tx, y = CvCoor.xy(cls.jarak, cls.tinggi * -1)\n\t\tkt_x, kt_y = CvCoor.xy(Kartesius.pos.x, Kartesius.pos.y)\n\t\tbenda_x, benda_y = CvCoor.xy(Benda.jarak, Benda.tinggi)\n\n\t\tcls.draw(surface, x, y, kt_y)\n\n\t\t# Sinar B ke garis kartesius\n\t\tpygame.draw.line(surface, COLORS.deeppink, (kt_x, y), (x, y))\n\n\t\t# Sinar B ke fokus\n\t\tpygame.draw.line(surface, COLORS.red, (kt_x, y), (benda_x, benda_y))\n\n\t@classmethod\n\tdef draw(cls, surface, x, y, kt_y):\n\t\t# Bayangan\n\t\timg = pygame.transform.flip(Tema.curr_chr, cls.mirror_x, cls.mirror_y)\n\t\timg.set_alpha(155)\n\t\tsize = img.get_size()\n\t\tw, h = cls.tinggi * size[0]//size[1], cls.tinggi\n\t\tif w < 0:\n\t\t\tw *= -1\n\t\tif h < 0:\n\t\t\th *= -1\n\t\tif w > 1000:\n\t\t\tw = 1000\n\t\tif h > 1000:\n\t\t\th = 1000\n\t\timg = pygame.transform.scale(img, (w, h))\n\t\trect = img.get_rect(topleft=(x, y))\n\t\tif cls.mirror_y:\n\t\t\trect = img.get_rect(bottomleft=(x, y + 1))\n\t\tsurface.blit(img, rect)\n\n\t\tpygame.draw.line(surface, COLORS.fg_color, (x, kt_y), (x, y))\n\n\t@classmethod\n\tdef handle_mirror(cls, menu):\n\t\tif menu.cembung:\n\t\t\tif cls.jarak < 0:\n\t\t\t\tcls.mirror_x = False\n\t\t\telse:\n\t\t\t\tcls.mirror_x = True\n\t\telse:\n\t\t\tif cls.jarak < 0:\n\t\t\t\tcls.mirror_x = True\n\t\t\telse:\n\t\t\t\tcls.mirror_x = False\n\n\t\tif cls.tinggi < 0:\n\t\t\tcls.mirror_y = False\n\t\telse:\n\t\t\tcls.mirror_y = True\n\n","repo_name":"refom/pembiasan-lensa","sub_path":"Mix/comp.py","file_name":"comp.py","file_ext":"py","file_size_in_byte":7114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"33729031152","text":"import pandas as pd\nfrom sklearn.svm import SVC\n\n\ndef get_X_y(df_):\n X = df_[range(1, len(df_.columns))]\n y = df_[0]\n return X, y\n\ndf = pd.read_csv('week3/assignment1/svm-data.csv', header=None)\nX, y = get_X_y(df)\n\nclf = SVC(kernel='linear', C=100000, random_state=241)\nclf.fit(X, y)\n\nprint(clf.support_)\n","repo_name":"fib0n/vorontsov_ml","sub_path":"week3/assignment1/sln.py","file_name":"sln.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"21975051948","text":"import numpy as np\r\nfrom skimage.external.tifffile import imsave, imread\r\nimport torch\r\n\r\n\r\ndef make_gaussian_noise(height, width, std):\r\n noise_img = np.zeros((1,height,width), dtype=np.float32)\r\n for h in range(height):\r\n for w in range(width):\r\n # avg : 0, std : 1\r\n std_norm = np.random.normal() \r\n # avg : 0, std : std\r\n random_noise = std*std_norm\r\n noise_img[0][h][w] = random_noise \r\n return noise_img\r\n\r\ndef save_tiff(path, np_image):\r\n imsave(path, np_image)\r\n print(\"{} save\".format(path))\r\n\r\nnoise1 = make_gaussian_noise(512, 512, 0.1)\r\nnoise2 = make_gaussian_noise(512, 512, 0.1)\r\nnoise1 = torch.from_numpy(noise1)\r\nnoise2 = torch.from_numpy(noise2)\r\nnoise = torch.cat([noise1,noise2],dim=0)\r\nprint(noise.shape)\r\nsave_tiff(\"./01.tiff\", noise)\r\n","repo_name":"mihyunkang/data_processing","sub_path":"CycleGAN_data/generate_gaussian_noise.py","file_name":"generate_gaussian_noise.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"13692283620","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport numpy as np\nimport random\nimport argparse\nfrom scipy.spatial import distance as dist\n\nimport colorsys\nimport cv2\n\nfrom mrcnn.config import Config\nfrom mrcnn import model as personModel\n\nHEIGHT=840\nWIDTH=680\n\nMIN_DISTANCE=50\n\nMIN_CONF = 0.8\nNMS_THRESH = 0.8\n\ncentroides = list()\nconfidences = []\n\n# construct the argument parse and parse the arguments\n# construir el argumento parse y analizar los argumentos\nap = argparse.ArgumentParser()\nap.add_argument(\"-o\", \"--output\", type=str, default=\"\",\thelp=\"path to (optional) output video file\")\nargs = vars(ap.parse_args([\"--output\",\"outputVideo.avi\"]))\n\n# MODELOS\n#model_filename = \"mask_rcnn_object_0005.h5\"\n#model_filename = \"mask_rcnn_object_0005_200img.h5\"\nmodel_filename = \"mask_rcnn_object_0010.h5\"\n#model_filename = \"mask_rcnn_object_0030.h5\"\n#model_filename = \"mask_rcnn_object_0040.h5\"\n\nclass_names = ['BG', 'persona']\nmin_confidence = 0.86\n\n#MODELO WIN\n#camera = cv2.VideoCapture(\"video_bajaDensidad.mp4\")\n#camera = cv2.VideoCapture(\"video_3-4_metros_densidadMedia.mp4\")\n#camera = cv2.VideoCapture(\"video_3-4_metros_densidadMediaAlta.mp4\")\n#camera = cv2.VideoCapture(\"video_3-4_metros_Trim.mp4\")\n#camera = cv2.VideoCapture(\"video_densidadMedia.mp4\")\ncamera = cv2.VideoCapture(\"video_filipinas1_densidadBaja.mp4\")\n#camera = cv2.VideoCapture(\"video_filipinas2_densidadMediaBaja.mp4\")\n\n#F EL MODELO\n#camera = cv2.VideoCapture(\"video_tokyo1.mp4\")\n#camera = cv2.VideoCapture(\"video_timeSquare1_AltaDensidad.mp4\")\n#camera = cv2.VideoCapture(\"video_timeSquare2_bajaDensidad.mp4\")\n#camera = cv2.VideoCapture(\"video_timeSquare3_mediaDensidad.mp4\")\n\nclass PersonaConfig(Config):\n # Give the configuration a recognizable name\n # Dar un nombre a la configuracion \n NAME = \"object\"\n\n # Train on 1 GPU and 1 image per GPU. Batch size is 1 (GPUs * images/GPU).\n # Entrenar en 1 GPU y 1 imagen por GPU, el tamaño del Batch es 1 (GPUs * images/GPU)\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n\n # Number of classes (including background)\n # Numero de clases (inluyendo el background)\n NUM_CLASSES = 1 + 1 # background + 1 (persona)\n\n # All of our training images are 512x512\n # Tama��o de todas las imagenes son: 512x512\n IMAGE_MIN_DIM = 512\n IMAGE_MAX_DIM = 512\n\n # You can experiment with this number to see if it improves training\n # Se puede modificar este valor para ver si el entrenamiento es mejorado\n STEPS_PER_EPOCH = 500\n\n # This is how often validation is run. If you are using too much hard drive space on saved models (in the MODEL_DIR), try making this value larger.\n # Esto se refiere al proceso de validacion. Si se esta usando mucha mas memoria en disco salvando modelos (exactamente MODEL_DIR), este valor se deberia incrementar.\n VALIDATION_STEPS = 5\n\n # Other esstential config\n # Otras configuraciones esenciales\n RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128)\n TRAIN_ROIS_PER_IMAGE = 32\n MAX_GT_INSTANCES = 50 \n POST_NMS_ROIS_INFERENCE = 500 \n POST_NMS_ROIS_TRAINING = 1000 \n \nconfig = PersonaConfig()\n#config.display()\n\nclass InferenceConfig(PersonaConfig):\n # config para optimizar el conteo de personas\n BACKBONE_STRIDES=[4, 8, 16, 32, 64]\n BATCH_SIZE=1\n COMPUTE_BACKBONE_SHAPE=None\n DETECTION_MAX_INSTANCES=100\n DETECTION_MIN_CONFIDENCE=min_confidence\n DETECTION_NMS_THRESHOLD=0.3\n FPN_CLASSIF_FC_LAYERS_SIZE=1024\n GPU_COUNT=1\n GRADIENT_CLIP_NORM=5.0\n IMAGES_PER_GPU=1\n IMAGE_CHANNEL_COUNT=3\n IMAGE_MAX_DIM=512\n IMAGE_META_SIZE=14\n IMAGE_MIN_DIM=512\n IMAGE_MIN_SCALE=0\n LEARNING_MOMENTUM=0.9\n LEARNING_RATE=0.001\n MASK_POOL_SIZE=14\n MASK_SHAPE=[28, 28]\n MAX_GT_INSTANCES=100\n MINI_MASK_SHAPE=(56, 56)\n NAME=\"object\"\n NUM_CLASSES=2\n POOL_SIZE=7\n POST_NMS_ROIS_INFERENCE=1000\n POST_NMS_ROIS_TRAINING=2000\n PRE_NMS_LIMIT=6000\n ROI_POSITIVE_RATIO=0.33\n RPN_ANCHOR_RATIOS=[0.5, 1, 2]\n RPN_ANCHOR_SCALES=(32, 64, 128, 256, 512)\n RPN_ANCHOR_STRIDE=1\n RPN_NMS_THRESHOLD=0.7\n RPN_TRAIN_ANCHORS_PER_IMAGE=256\n STEPS_PER_EPOCH=500\n TOP_DOWN_PYRAMID_SIZE=256\n TRAIN_ROIS_PER_IMAGE=200\n VALIDATION_STEPS=5\n WEIGHT_DECAY=0.0001\n \ninference_config = InferenceConfig()\ninference_config.display()\n\n# Recreate the model in inference mode\n# Recreacion del modelo en modo inferencia\nmodel = personModel.MaskRCNN(mode=\"inference\", config=inference_config, model_dir='logs')\n\n# Get path to saved weights. Either set a specific path or find last trained weights\n# Ruta hacia los pesos guardados. De igual manera la ruta hacia el ultimo modelo entrenado\nmodel_path = os.path.join('logs', model_filename)\n#model_path = model.find_last()\n\n# Load trained weights (fill in path to trained weights here)\n# Cargar los pesos entrenados (llenar la ruta de pesos establecidos aqui)\nassert model_path != \"\", \"Provide path to trained weights\"\nprint(\"Loading weights from \", model_path)\nmodel.load_weights(model_path, by_name=True)\n\ndef calcular_dist(boxes, indexes):\n\n if len(indexes) > 2:\n idf = indexes.flatten()\n centers = list()\n status = list()\n violate = set()\n\n safe = list()\n low_risk = list()\n high_risk = list()\n\n for i in idf:\n #The mask RCNN bounding box format demands the top left and bottom right coordinate of the box which is given by: [x, y, x+w, y+h].\n #El formato de la bbox de mask RCNN arroja el borde superior izquierda, y el borde inferior derecho en base a las coordenada dadas por: [x, y, x+w, y+h]\n # x, y, x+w, y+h\n (x,y) = (boxes[i][0],boxes[i][1]) # top-left position\n (w,h) = (boxes[i][2]-boxes[i][0],boxes[i][3]-boxes[i][1])\n \n centers.append([int(y+(h/2)),int(x+(w/2))])\n #print(\"centros \", centers)\n \n \n dst = dist.cdist(centers, centers, metric=\"euclidean\")\n #print(\"matriz distancia \\n\", dst)\n \n # loop over the upper triangular of the distance matrix\n # Recorrer la matriz de distancia contando unicamente su traingularidad superior\n for i in range(0, dst.shape[0]):\n for j in range(i + 1, dst.shape[1]):\n # check to see if the distance between any two centroid pairs is less than the configured number of pixels\n # revisar si la distancia que existe entre dos distintos centroides es menor que la cantidad de pixeles configurados inicialmente.\n if dst[i, j] < MIN_DISTANCE:\n # update our violation set with the indexes of the centroid pairs\n # actualizamos el conjunto de \"violate\" con los indices de los centroides que cumplen esta condicion\n violate.add(i)\n violate.add(j)\n high_risk.append([centers[i], centers[j]])\n #y, x, y+h x+w\n y1, x1, y2, x2 = boxes[i]\n #print(\"coordenadas \", boxes[i])\n cv2.rectangle(frame_obj, (x1, y1), (x2, y2),(0,10,255), 2)\n\n person_count = len(centers)\n safe_count = len(centers)-len(violate)\n high_risk_count = len(violate)\n \n return high_risk_count, safe_count, idf, high_risk\n\ndef draw_distance(frame, idf, boxes, WIDTH, HEIGHT, high_risk, safe, high_risk_cord, total):\n\n for i in idf:\n sub_img = frame[630:HEIGHT, 0:150]\n black_rect = np.ones(sub_img.shape, dtype=np.uint8) * 0\n res = cv2.addWeighted(sub_img, 0.70, black_rect, 0.30, 1.0)\n frame[630:HEIGHT, 0:150] = res\n # B- G- R-\n #cv2.putText(frame_obj,'TEST',(0, 670), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0), 1)\n cv2.putText(frame_obj, \"TOTAL : {}\".format(total),(10, 650),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\n cv2.putText(frame_obj, \"EN RIESGO : {}\".format(high_risk),(10, 670),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 10, 255), 2)\n \n for l in high_risk_cord:\n cv2.line(frame_obj, tuple(l[0]), tuple(l[1]), (10, 44, 236), 2) \n\n return frame\n\nwriter = None\n\nwhile camera:\n ret, frame = camera.read()\n frame = cv2.resize(frame, (HEIGHT, WIDTH), interpolation = cv2.INTER_AREA)\n \n results = model.detect([frame], verbose=0)\n r = results[0]\n \n N = r['rois'].shape[0]\n #print(\"N:\",N)\n boxes=r['rois']\n masks=r['masks']\n class_ids=r['class_ids']\n scores=r['scores']\n # Bounding box indexes. \n # Indices de los cuadros delimitadores.\n indices = cv2.dnn.NMSBoxes(boxes, scores, MIN_CONF, NMS_THRESH) \n #print(\"indices: \", indices) \n \n hsv = [(i / N, 1, 0.7) for i in range(N)]\n colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))\n \n random.shuffle(colors)\n #print(\"N_obj:\",N)\n masked_image = frame.astype(np.uint32).copy()\n \n for i in range(N):\n \n #if not np.any(boxes[i]):\n # Skip this instance. Has no bbox. Likely lost in image cropping.\n # continue\n\n # lista de colores para cada mascara de las instancias por cada frame\n color = list(np.random.random(size=3) * 256)\n mask = masks[:, :, i]\n alpha=0.5\n \n # Recorrer las mascaras y darles una tonalidad que se refleje en los resultados.\n for c in range(3):\n masked_image[:, :, c] = np.where(mask == 1, masked_image[:, :, c] * (1 - alpha) + alpha * color[c], masked_image[:, :, c])\n \n frame_obj=masked_image.astype(np.uint8)\n \n # Localizar los atributos de las detecciones\n class_id = class_ids[i]\n score = scores[i] if scores is not None else None\n masked_image = frame_obj.astype(np.uint32).copy()\n \n # Incluir cada score al conjunto de confianza \n confidences.append(float(score))\n \n # se calcula las distancias de todas las instancias en el frame dado\n high_risk, safe, idf, high_risk_cord = calcular_dist(boxes, indices)\n # se dibuja dicha distancia para que sea acorde \n draw_distance(frame_obj, idf, boxes, WIDTH, HEIGHT, high_risk, safe, high_risk_cord, N)\n \n if N>0:\n cv2.imshow('Aglomeracion de personas', frame_obj)\n else:\n cv2.imshow('Aglomeracion de personas', frame)\n \n # parar la ejecucion del programa con letra 'q'\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break;\n \n # if an output video file path has been supplied and the video writer has not been initialized, do so now\n # si se proporcionó una ruta de archivo de video de salida y el escritor de video no se ha inicializado, se procede a configurarlo \n if args[\"output\"] != \"\" and writer is None:\n # initialize our video writer\n # inicializar el escritor de video \n fourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n writer = cv2.VideoWriter(args[\"output\"], fourcc, 25,(frame.shape[1], frame.shape[0]), True)\n\n\t# if the video writer is not None, write the frame to the output video file\n # si el escritor de video no es None, escriba el cuadro en el archivo de video de salida\n if writer is not None:\n writer.write(frame_obj)\n\n# \ncamera.release()\n# destruir todas las ventanas y procesos despues de la inferencia.\ncv2.destroyAllWindows()","repo_name":"CesarTaco1007/TIC_SegmentacionSemantica_AglomeracionPersonas_CPTA","sub_path":"MaskRCNN_Video/personaVideoDistancia.py","file_name":"personaVideoDistancia.py","file_ext":"py","file_size_in_byte":11094,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"4396055276","text":"\"\"\"\n\nthe Time Complxity is O(N) and bacuse of we do not use extra space so the space complexity \nis O(n)\n\nthe nested while loop does not on our time complexity bacuse it just walk through our array of element and did \nmake any hard work.So this will not affected\n\n\"\"\"\n\n\ndef compress(chars):\n i = 0\n j = 0\n index = 0\n while(i < len(chars)):\n while(j < len(chars) and chars[i] == chars[j]):\n j += 1\n chars[index] = chars[i] # not important though\n index += 1\n if(j - i > 1):\n l = str(j - i)\n for c in l:\n chars[index] = c # not important\n index += 1\n i = j\n return index\n\n\n# [\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]\nprint(compress([\"a\", \"a\", \"b\", \"b\", \"c\", \"c\", \"c\"]))\nprint(compress([\"a\"])) # return 1 [\"a\"]\nprint(compress([\"a\", \"b\", \"b\", \"b\", \"b\", \"b\",\n \"b\", \"b\", \"b\", \"b\", \"b\", \"b\", \"b\"])) # return 4\n","repo_name":"RajibMiah/leetcode-solution","sub_path":"medium/443. String Compression.py","file_name":"443. String Compression.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"8099208724","text":"class Solution:\n def getWinner(self, arr: List[int], k: int) -> int:\n \"\"\"\n ints are unique\n is it guaranteed there will be a winner? - YES\n - YES: if the array is already sorted in reverse order\n - YES: if array is in sorted order, and\n\n\n arr = [1,11,22,33,44,55,66,77,88,99], k = 1000000000\n [1,11,22,33,44,55,66,77,88,99]\n [22,33,44,55,66,77,88,99, 1, 11]\n\n element. | wins\n 11 1\n 22 1\n 33 1\n 44 1\n 55 1\n\n {\n 1: []\n }\n\n what happens is that the list goes into greatest to least order, and once that's the case\n we know we'll have a winner - that's the largest element\n\n will the winner always be the largest element:\n if k > number of spaces between the max and the 0 index\n - return the max element\n\n other wise:\n\n play the game, use a dict to know the winner\n \"\"\"\n # find the max element, and it's index\n max_element = arr[0]\n max_index = 0\n for index, num in enumerate(arr):\n if num > max_element:\n max_element = num\n max_index = index\n # early exit\n if k > max_index - 0:\n return max_element\n # init a dict to map wins to elements\n nums_wins = dict()\n # while there is no winner:\n while k not in nums_wins.values():\n # get the elements at the 0 and 1 index\n elem1, elem2 = arr[0], arr[1]\n # give the larger one a win\n larger = 0\n if elem1 > elem2:\n larger = elem1\n else:\n larger = elem2\n if larger in nums_wins:\n nums_wins[larger] += 1\n else:\n nums_wins[larger] = 1\n # move the larger to index 0\n if larger == elem2:\n # swap first and second elements\n arr[0], arr[1] = arr[1], arr[0]\n # move the smaller to the end\n arr.append(arr.pop(1))\n # return the winner\n for num in nums_wins:\n if nums_wins[num] == k:\n return num\n","repo_name":"UPstartDeveloper/Problem_Solving_Practice","sub_path":"miscellaneous/array_game.py","file_name":"array_game.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"38400049197","text":"\"\"\"\r\nthis file contains a set of helper functions that will will be called \r\ninsisde functions of app.py (main app file)\r\n\r\n\"\"\"\r\n\r\nimport requests\r\nimport json\r\nfrom config import *\r\n\r\ndef parse_message(message):\r\n \"\"\"\r\n a function that parses message objects and return correspondent info : text message and chat id \r\n \"\"\"\r\n msg_text = message[\"message\"][\"text\"]\r\n #sender_name = resp[\"message\"][\"from\"][\"first_name\"]\r\n chat_id = message[\"message\"][\"chat\"][\"id\"]\r\n\r\n return chat_id, msg_text\r\n\r\ndef message_response(msg_txt):\r\n \"\"\"\r\n a helper function that returns correspondent message for a user command\r\n \"\"\"\r\n commands = {\"/start\":\"Hello! I am CHATBOT-DS-42, I am here to help \\n/track : if you want to track your code \\n/end to end conversation.\",\r\n \"/track\" : \"please type your code, or /menu to return to main menu\", \r\n \"/menu\" : \"/track : to track your code \\n /end : to end conversation.\", \r\n \"/end\" : \"good bye!\"}\r\n if msg_txt in commands.keys():\r\n return commands[msg_txt]\r\n else:\r\n return \"did you mean track my code?\\n /track : to track the code.\\n /end : to end conversation.\"\r\n\r\ndef send_message(chat_id, msg):\r\n \"\"\"\r\n a function that sends messages to user through telegram api using a post request\r\n \"\"\"\r\n url = \"{}/bot{}/sendMessage\".format(API_URL,TOKEN)\r\n payload = {\r\n \"text\":msg,\r\n \"chat_id\":chat_id\r\n }\r\n \r\n resp = requests.post(url, json=payload)\r\n return resp\r\n\r\ndef write_json(data, filename=\"response.json\"):\r\n with open(filename, 'w') as f:\r\n json.dump(data, f, indent=4, ensure_ascii=True)\r\n\r\n","repo_name":"tmajjati/chatbot-project-DS","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"74828660894","text":"#!/usr/bin/env python\n\nimport rospy\nimport time\nimport actionlib\nimport math\nimport tf\nimport tf2_ros\nimport geometry_msgs.msg\n\nfrom move_base_msgs.msg import MoveBaseGoal, MoveBaseAction, MoveBaseActionFeedback\nfrom actionlib_msgs.msg import GoalStatus\nfrom geometry_msgs.msg import Pose, Point, Quaternion, PoseWithCovarianceStamped\nfrom tf.transformations import quaternion_from_euler\n \n\n\nclass InitialGoalMove():\n\n def __init__(self):\n\n\n self.goal_point = []\n #making from_initial_to_goal_node node\n rospy.init_node('from_initial_to_goal_node')\n #taking initial and goal points from parameter server \n self.initial_point = rospy.get_param('send_goal_point/init_point_pose_param')\n self.goal_point = rospy.get_param('send_goal_point/goal_point_pose_param')\n #euler to queternion transform \n self.initial_quat = Quaternion(*(quaternion_from_euler(0,0,self.initial_point[2]*math.pi/180,axes='sxyz')))\n self.goal_quat = Quaternion(*(quaternion_from_euler(0,0,self.goal_point[2]*math.pi/180,axes='sxyz')))\n\n #create initial pose publisher \n self.pub = rospy.Publisher('/initialpose',PoseWithCovarianceStamped,queue_size=10)\n init_pose_msg = PoseWithCovarianceStamped()\n init_pose_msg.header.frame_id = 'map'\n \n #create initial pose message\n init_pose_msg.pose.pose.position.x = self.initial_point[0]\n init_pose_msg.pose.pose.position.y = self.initial_point[1]\n init_pose_msg.pose.pose.orientation.w = self.initial_quat.w\n \n\n #create action client\n self.client = actionlib.SimpleActionClient('move_base', MoveBaseAction)\n rospy.loginfo(\"Waiting for move_base action server...\")\n wait = self.client.wait_for_server(rospy.Duration(10.0))\n\n if not wait:\n rospy.logerr(\"Action server not available!\")\n rospy.signal_shutdown(\"Action server not available!\")\n return\n rospy.loginfo(\"Connected to move base server\")\n rospy.loginfo(\"Starting goals achievements ...\")\n\n #send publisher message\n self.pub.publish(init_pose_msg)\n rospy.loginfo(\"INITIAL POSE SEND\")\n\n self.movebase_client()\n \n\n def movebase_client(self):\n \n goal = MoveBaseGoal()\n goal.target_pose.header.frame_id = 'map'\n goal.target_pose.header.stamp = rospy.Time.now()\n goal.target_pose.pose.position.x = self.goal_point[0]\n goal.target_pose.pose.position.y = self.goal_point[1]\n goal.target_pose.pose.orientation.w = self.goal_quat.w\n\n self.client.send_goal(goal)\n result = self.client.wait_for_result()\n\n if not result:\n rospy.logerr(\"There is no result!\")\n rospy.signal_shutdown(\"There is no result!\")\n rospy.logerr(\"There is an error!\")\n else:\n rospy.loginfo(\"Turtlebot reached goal pose.\")\n return self.client.get_result()\n\n\n\nif __name__ == '__main__':\n try:\n InitialGoalMove()\n\n #rospy.init_node('movebase_client_py')\n #result = movebase_client()\n #if result:\n # rospy.loginfo(\"Goal execution done!\")\n \n except rospy.ROSInterruptException:\n rospy.loginfo(\"Navigation test finished.\")\n pass\n \n","repo_name":"fcelitok/Send_goal_rep","sub_path":"scripts/send_goal_point.py","file_name":"send_goal_point.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"7316773712","text":"\"\"\"\nTaken from CodeSignals \"Grouping dishes\" exercise:\n\nYou are given a list dishes, where each element consists of a list of strings \nbeginning with the name of the dish, followed by all the ingredients used in\npreparing it. You want to group the dishes by ingredients, so that for each \ningredient you'll be able to find all the dishes that contain it (if there \nare at least 2 such dishes).\n\nReturn an array where each element is a list beginning with the ingredient \nname, followed by the names of all the dishes that contain this ingredient. \nThe dishes inside each list should be sorted lexicographically, and the \nresult array should be sorted lexicographically by the names of the \ningredients.\n\"\"\"\n\n\ndef groupingDishes(dishes):\n list_of_ingredients = []\n added_dish_to_ingredients_list = False\n\n for i in range(len(dishes)): #list of dishes\n for j in range(1,len(dishes[i])): #current dish\n curr_dish = dishes[i][0]\n curr_ingredient = dishes[i][j]\n\n for k in range(len(list_of_ingredients)):\n if list_of_ingredients[k][0] == curr_ingredient: #it's already there\n list_of_ingredients[k].append(curr_dish)\n added_dish_to_ingredients_list = True\n if not added_dish_to_ingredients_list: #there is no matching ingredient for now\n new_ingredient = [curr_ingredient, curr_dish] #create what shouldbe added\n list_of_ingredients.append(new_ingredient) #and add it\n\n added_dish_to_ingredients_list = False #preparing next iteration\n \n sorted_res = lex_matrix_sort(list_of_ingredients)\n filtered_res = filter(lambda x: len(x) > 2, sorted_res)\n return list(filtered_res)\n\n\ndef lex_matrix_sort(mat):\n for i in range(len(mat)): #sorting dishes for each ingredient\n curr_ingredient = mat[i][0]\n curr_dishes = mat[i][1:]\n curr_dishes.sort(key=lambda x: x) #sorting dishes in ingredients\n mat[i] = curr_dishes\n mat[i].insert(0, curr_ingredient)\n mat.sort(key=lambda x: x[0]) #sorting ingredients \n return mat\n\n\n\n #################################### Driver ##################################\ndishes = [[\"Salad\", \"Tomato\", \"Cucumber\", \"Salad\", \"Sauce\"],\n [\"Pizza\", \"Tomato\", \"Sausage\", \"Sauce\", \"Dough\"],\n [\"Quesadilla\", \"Chicken\", \"Cheese\", \"Sauce\"],\n [\"Sandwich\", \"Salad\", \"Bread\", \"Tomato\", \"Cheese\"]]\nprint(groupingDishes(dishes))\n","repo_name":"ryk-wolf/general_coding_practice","sub_path":"python/re_arranging_matrices.py","file_name":"re_arranging_matrices.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"36591747904","text":"from typing import List, Optional, Tuple, Union\n\nimport numpy as np\nfrom numpy.typing import NDArray\n\nFloatSequence = Union[List[float], Tuple[float], NDArray[float]]\n\n\ndef camelcase2snakecase(camel_case_str):\n \"\"\"\n Convert string from CamelCase to snake_case\n e.g. CamelCase becomes camel_case.\n \"\"\"\n idx = list(reversed([i for i, c in enumerate(camel_case_str) if c.isupper()]))\n param_len = len(camel_case_str)\n for i in idx:\n # check if we should insert an underscore\n if i > 0 and i < param_len:\n camel_case_str = camel_case_str[:i] + \"_\" + camel_case_str[i:]\n\n return camel_case_str.lower()\n\n\ndef depth_from_pressure(\n pressure: Union[float, FloatSequence],\n latitude: Optional[Union[float, FloatSequence]] = 30.0,\n atm_pres_surf: Optional[Union[float, FloatSequence]] = 0.0,\n) -> NDArray[float]:\n \"\"\"\n Convert pressure to depth using UNESCO 1983 algorithm.\n\n UNESCO. 1983. Algorithms for computation of fundamental properties of seawater (Pressure to\n Depth conversion, pages 25-27). Prepared by Fofonoff, N.P. and Millard, R.C. UNESCO technical\n papers in marine science, 44. http://unesdoc.unesco.org/images/0005/000598/059832eb.pdf\n\n Parameters\n ----------\n pressure : Union[float, FloatSequence]\n Pressure in dbar\n latitude : Union[float, FloatSequence], default=30.0\n Latitude in decimal degrees.\n atm_pres_surf : Union[float, FloatSequence], default=0.0\n Atmospheric pressure at the surface in dbar.\n Use the default 0.0 value if pressure is corrected to be 0 at the surface.\n Otherwise, enter a correction for pressure due to air, sea ice and any other\n medium that may be present\n\n Returns\n -------\n depth : NDArray[float]\n Depth in meters\n \"\"\"\n\n def _as_nparray_check(v, check_vs_pressure=False):\n \"\"\"\n Convert to np.array if not already a np.array.\n Ensure latitude and atm_pres_surf are of the same size and shape as\n pressure if they are not scalar.\n \"\"\"\n v_array = np.array(v) if not isinstance(v, np.ndarray) else v\n if check_vs_pressure:\n if v_array.size != 1:\n if v_array.size != pressure.size or v_array.shape != pressure.shape:\n raise ValueError(\"Sequence shape or size does not match pressure\")\n return v_array\n\n pressure = _as_nparray_check(pressure)\n latitude = _as_nparray_check(latitude, check_vs_pressure=True)\n atm_pres_surf = _as_nparray_check(atm_pres_surf, check_vs_pressure=True)\n\n # Constants\n g = 9.780318\n c1 = 9.72659\n c2 = -2.2512e-5\n c3 = 2.279e-10\n c4 = -1.82e-15\n k1 = 5.2788e-3\n k2 = 2.36e-5\n k3 = 1.092e-6\n\n # Calculate depth\n pressure = pressure - atm_pres_surf\n depth_w_g = c1 * pressure + c2 * pressure**2 + c3 * pressure**3 + c4 * pressure**4\n x = np.sin(np.deg2rad(latitude))\n gravity = g * (1.0 + k1 * x**2 + k2 * x**4) + k3 * pressure\n depth = depth_w_g / gravity\n return depth\n","repo_name":"OSOceanAcoustics/echopype","sub_path":"echopype/utils/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","stars":78,"dataset":"github-code","pt":"33"} +{"seq_id":"43479664966","text":"from MyPythonClass import MathGame\nfrom time import sleep\nprint('='*50)\nprint(\"Arithmetics game\".center(50))\nprint(\"=\"*50)\n\nstarter = MathGame()\nstarter.Iniciar()\nwhile True:\n question = input(\"Do you want to see your Score?[Y/N]\").upper()\n if question == \"Y\":\n starter.show_score()\n break\n elif question == \"N\":\n break\n else:\n print('Invalid Value! please insert \"Y\" or \"N\":')\ninput(\"Press Any Key To Finish....\")\n\n\n\nprint('='*50)\nprint(\"Finished!!!\".center(50))\nprint(\"=\"*50)\nsleep(2)\n","repo_name":"Jeronimo-MZ/Math-And-PEMDAS","sub_path":"MathGame.py","file_name":"MathGame.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"42358069642","text":"\"\"\"The module provides implementation for converting RSS contents to several formats\"\"\"\n\nimport logging\nimport os\nfrom typing import List\n\nfrom xhtml2pdf import pisa\nfrom yattag import Doc, indent\n\nlogger = logging.getLogger()\n\n\nclass Converter:\n \"\"\"Represents rss-to-file converter\"\"\"\n\n def __init__(self, rss_contents: List[tuple]) -> None:\n \"\"\"Converter constructor\n\n Args:\n rss_contents: List containing the news items\n \"\"\"\n self._rss_contents = rss_contents\n self._html_content = None\n\n def _to_html(self) -> None:\n \"\"\"Converts news items to HTML\n\n Returns:\n None\n \"\"\"\n doc, tag, text = Doc().tagtext()\n doc.asis('')\n with tag('html'):\n doc.stag('meta', charset='utf-8')\n with tag('body'):\n doc.attr(style=\"text-align:left; font-size:20px\")\n for item in self._rss_contents:\n with tag('h1'):\n text(f\"Title: {item[2]}\")\n with tag('h3'):\n text(f\"Date published: {item[3]}\")\n with tag('h4'):\n text(f\"Feed source: {item[1]}\")\n with tag('div'):\n doc.attr(style=\"word-wrap: break-word; width: 1000px; line-height:25px\")\n text(f\"{item[4]}\\n\")\n with tag('a'):\n doc.attr(href=f\"{item[5]}\")\n doc.stag('br')\n text('Read more here')\n doc.stag('br')\n doc.stag('br')\n with tag('div'):\n if item[6] != 'No Image':\n doc.stag('img', src=f\"{item[6]}\")\n doc.attr(style=\"zoom:100%\")\n else:\n text('Image is not available')\n self._html_content = indent(doc.getvalue())\n\n def generate_file(self, filetype: str, filepath: str) -> None:\n \"\"\"Generates HTML/PDF file\n\n Returns:\n None\n \"\"\"\n self._to_html()\n file_ = os.path.join(filepath, f'news.{filetype}')\n os.makedirs(os.path.dirname(file_), exist_ok=True)\n if filetype == 'pdf':\n with open(file_, 'w+b') as file:\n print('Creating PDF file...')\n logging.disable(logging.DEBUG)\n pisa.CreatePDF(self._html_content, dest=file)\n print(f'PDF file created at {os.path.abspath(file_)}')\n elif filetype == 'html':\n with open(file_, 'w') as file:\n print('Creating HTML file...')\n file.write(self._html_content)\n print(f'HTML file created at {os.path.abspath(file_)}')\n","repo_name":"irgashevsardor/RSS-reader","sub_path":"output_manager/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"40822754748","text":"from typing import Optional, List\nimport random\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 __init__(self, head: Optional[ListNode]):\n self.head = head\n\n def getRandom(self) -> int:\n ans = 0\n node = self.head\n scannedcnt = 0\n while node:\n scannedcnt += 1\n if random.random() < 1 / scannedcnt:\n ans = node.val\n node = node.next\n \n return ans\n\n \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(head)\n# param_1 = obj.getRandom()","repo_name":"MasayoshiTsutsui/leetcode","sub_path":"linkedlistrandomnode.py","file_name":"linkedlistrandomnode.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"6255364271","text":"import sys\nsys.stdin = open(\"input.txt\", \"r\")\n\nfor tc in range(1, 11):\n N = int(input())\n datas = input()\n stack = []\n result = ''\n for data in datas:\n\n # 숫자일 때 넣기\n if data.isdigit():\n result += data\n\n # 여는 괄호일때 연산자에 넣기\n elif data == '(':\n stack.append(data)\n\n # 닫는 괄호일때, 여는 괄호가 나올때까지 쭉 넣기\n elif data == ')':\n while stack[-1] != '(':\n result += stack.pop()\n stack.pop()\n\n # 곱셈연산자일때, 다음 곱셈 연산자가 나올때까지 넣어줌\n elif data == '*':\n while stack[-1] == '*':\n result += stack.pop()\n stack.append(data)\n\n # 덧셈연산자일때, 여는 괄호가 나올때까지 넣어줌\n elif data == '+':\n while stack[-1] != '(':\n result += stack.pop()\n stack.append(data)\n print(result)\n\n nums = []\n for i in range(len(result)):\n if result[i].isdigit():\n nums.append(int(result[i]))\n else:\n a = nums.pop()\n b = nums.pop()\n if result[i] == '+':\n nums.append(b+a)\n elif result[i] == '*':\n nums.append(b*a)\n print('#{} {}'.format(tc, nums.pop()))\n","repo_name":"semipumpkin/MY_SWEA","sub_path":"1224_계산기3/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"15947334830","text":"from Protocol import sender, serialization\n\nsocket = sender.Initializer(\n 'localhost', 5000\n).getConnection()\n\nsock_ = sender.assign_name(socket, \"Device_1\")\n\n#create a simple function for serailization:\n\ndef function(*args):\n import os\n return str(os.listdir())\n\n#serialize:\nfunction_data = serialization.SerializationBase(\n function = function\n).b64String()\n\nmeta = serialization.add_arguments(function_data, 1, 2, 3, 4)\n\ndata = serialization.create_network_portable_stream(meta)\n\nsender.DispatcherProtocol(\n socket_ = sock_, function_metadata = data\n).call()\n","repo_name":"Narasimha1997/RPEio","sub_path":"ExecutionTest.py","file_name":"ExecutionTest.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"37866294113","text":"from flask import Blueprint, jsonify\nfrom application.models.company import Company, CompanySchema\n\n\nfirst = Blueprint('first', __name__, url_prefix='/first')\n\ncompany_schema = CompanySchema()\ncompanys_schema = CompanySchema(many=True)\n\n\n@first.route('/')\ndef getCompanyList():\n list = Company.query.all()\n result = companys_schema.dump(list)\n return jsonify(result)\n\n\n@first.route('/')\ndef getCompanyById(id):\n company = Company.query.get(id)\n result = company_schema.dump(company)\n return jsonify(result)\n","repo_name":"rankyangel2014/flasklearn","sub_path":"application/views/first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"26352615193","text":"# filter x number of features from gtex file using importance scoring from genes (features_6_tissues)\n# python pca_filter_features.py 1000 ../../data/gtex/features_6_tissues.tsv.RF.20201013.0006 headers_genes.tsv gtex_6.tsv tsv gtex_6_1000.tsv genes_all_1000.tsv tsv 1\n# python pca_filter_features.py 1000 ../../data/gtex/features_6_tissues.tsv.DT.20201013.0010 headers_genes.tsv gtex_6.tsv tsv gtex_6_1000.tsv genes_all_1000.tsv tsv 1\n# feed gtex_6_1000.tsv genes_all_1000.tsv to jupyter plotly_pca_3d_interactive\n\nimport pandas as pd\nimport sys, argparse, subprocess, datetime\nimport ScoreFeatures\n#from .ScoreFeatures import ScoreFeatures #otherwise it won't work with Popen from score.py\n\n##########################################################################\n# read genes scoring file and return top n genes\n##########################################################################\ndef readGenesScoringFile(genesFile, nGenes):\n #print('readGenesScoringFile ' + genesFile + ' ' + nGenes, file=sys.stderr)\n topGenes = []\n #print(subprocess.Popen(['/home/rlopeztec/mysite/bml/benchmark/rene.sh']))\n with open(genesFile, 'r') as inputFile:\n c = 0\n for line in inputFile:\n if nGenes == 'all' or c < int(nGenes):\n topGenes.append(line.split('\\t')[0])\n #print('topGenes', line.split('\\t')[0], line.split('\\t'))\n else:\n break\n c += 1\n #print('reading', genesFile, c, 'select', nGenes, 'genes', 'and got', len(topGenes), topGenes)\n #print(topGenes)\n return topGenes\n\n##########################################################################\n# read headers file and note position of gene if one of the top n genes\n##########################################################################\ndef readHeadersFile(headersFile, topGenes, genesalloutFile, fileType, dataType, targetClass, dimNames, xSeqs, ycols):\n delimiter='\\t'\n if fileType == 'csv':\n delimiter=','\n retHeaders = []\n retHeadersGenes = []\n genesOutput = open(genesalloutFile, 'w')\n\n # get headers from file or build headers from DNA sequencing data (ACGTs)\n if dataType not in ('DNA', 'Variants'):\n with open(headersFile, 'r') as inputFile:\n line = inputFile.readline()\n dimNames = line.split(delimiter)\n xSeqs, ycols = None, None\n c = 0\n first = True\n #print('RENE cols read headers file onehot:', len(cols), file=sys.stderr)\n for gene in dimNames:\n #print('RENE gene in cols:', gene, len(cols), len(topGenes), topGenes, file=sys.stderr)\n if gene in topGenes:\n #print('gene in top:', gene, len(topGenes))\n if gene not in retHeadersGenes:\n retHeaders.append(c)\n retHeadersGenes.append(gene)\n #print('gene not in:', gene, len(retHeadersGenes))\n if first:\n first = False\n else:\n genesOutput.write('\\t')\n genesOutput.write(gene)\n else:\n print('DUPLICATE', c, gene)\n c += 1\n #print('headersFile:', headersFile, 'headers:', len(retHeaders), retHeaders)\n genesOutput.close()\n return retHeaders, dimNames, xSeqs, ycols\n\n################################################################################\n# read values file and keep genes if one of the top n genes in the output file #\n################################################################################\ndef readInputFile(genesin, fileType, outputFile, headersGenes, targetClass, dataType, dimNames=None, xSeqs=None, ycols=None):\n\n #print('pca_filter_features readInputFile', genesin, fileType, outputFile, headersGenes, targetClass, datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\"), file=sys.stderr)\n c = 0\n targetClassPos = -1\n delimiter='\\t'\n if fileType == 'csv':\n delimiter=','\n outputFile = open(outputFile, 'w')\n\n # read original file and get only the columns scored as important\n if dataType == 'DNA' or dataType == 'Variants':\n # dimNames, xSeqs, ycols\n for i in range(0,len(xSeqs)):\n # write target/y class and feature headers\n if i == 0:\n #print('RENE y labels1:', type(ycols), file=sys.stderr)\n #print('RENE y labels2:', type(ycols.iloc[:0]), file=sys.stderr)\n #print('RENE y labels3:', i, type(ycols.iloc[i:0]), file=sys.stderr)\n #print('RENE y labels4:', str(ycols.iloc[i]), file=sys.stderr)\n #print('RENE y labels5:', type(ycols.iat[0]), file=sys.stderr)\n #print('RENE y labels6:', str(ycols.iat[i]), file=sys.stderr)\n #print('RENE y labels7:', str(ycols.iloc[i:i+1]), file=sys.stderr)\n #print('RENE y labels8:', str(ycols.iloc[:10]), file=sys.stderr)\n outputFile.write(targetClass)\n for header in headersGenes:\n outputFile.write('\\t' + dimNames[header])\n outputFile.write('\\n')\n outputFile.write(str(ycols.iat[i]) + '\\t')\n cols = 0\n for gene in headersGenes:\n #if i == 0:\n #print('RENE xSeqs0:', headersGenes, file=sys.stderr)\n #print('RENE xSeqs1:', len(xSeqs), i, gene, type(xSeqs), file=sys.stderr)\n #print('RENE xSeqs2:', type(xSeqs.iat[i,gene]), file=sys.stderr)\n #print('RENE xSeqs3:', str(int(xSeqs.iat[i,gene])), file=sys.stderr)\n outputFile.write(str(int(xSeqs.iat[i,gene])))\n if cols < len(headersGenes) - 1:\n outputFile.write('\\t')\n cols += 1\n outputFile.write('\\n')\n else:\n with open(genesin, 'r') as inputFile:\n for line in inputFile:\n line = line.replace('\\n','')\n listGenes = line.split(delimiter)\n\n # find the target class position\n if c == 0:\n for i in range(0,len(listGenes)):\n if listGenes[i] == targetClass:\n targetClassPos = i\n break\n c += 1\n\n # add target class (y) to file as the 1st position\n outputFile.write(listGenes[targetClassPos] + '\\t')\n\n cols = 0\n for gene in headersGenes:\n outputFile.write(listGenes[gene])\n if cols < len(headersGenes) - 1:\n outputFile.write('\\t')\n #if c < 3: print('gene value:', gene, listGenes[gene])\n cols += 1\n outputFile.write('\\n')\n outputFile.close()\n #print('pca_filter_features, input lines', c, datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\"), file=sys.stderr)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('n', help='number of genes to keep')\n parser.add_argument('genes', help='genes scoring file')\n parser.add_argument('headers', help='genes headers file')\n parser.add_argument('genesin', help='genes input values file')\n parser.add_argument('filetype', help='input file type')\n parser.add_argument('genesout', help='genes output values file')\n parser.add_argument('genesallout', help='ngenes output file')\n parser.add_argument('t', help='file type tsv or csv')\n parser.add_argument('p', help='target class position')\n args = parser.parse_args()\n #parser.add_argument('', help='')\n print('filter features')\n print(args)\n topGenes = readGenesScoringFile(args.genes, args.n)\n headersGenes = readHeadersFile(args.headers, topGenes, args.genesallout, args.t)\n\n # last 3 parameters are dim names, x sequences, y labels for DNA data type\n readInputFile(args.genesin, args.filetype, args.genesout, headersGenes, int(args.p), None, None, None)\n\n","repo_name":"rlopeztec/bench-ml","sub_path":"bml/benchmark/pca_filter_features.py","file_name":"pca_filter_features.py","file_ext":"py","file_size_in_byte":7955,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"32282916563","text":"from dal import filemanager\nfrom os import path\nfrom tkinter import messagebox\nfrom datetime import datetime\n\ndefault_path = filemanager.getPath()\n\ndef relLigacaoXUnid():\n ramais = []\n for line in filemanager.listRows():\n ramais.append(list(line.split(','))[4][1])\n ramais.remove('a')\n\n emp5 = 0\n emp6 = 0\n emp8 = 0\n outr = 0\n\n for n in ramais:\n if n == '2':\n emp5 = emp5+1\n elif n == '5':\n emp6 = emp6+1\n elif n == '1':\n emp8 = emp8+1\n else:\n outr = outr+1\n\n hora = datetime.now().strftime(\"%d-%m-%y %H:%M:%S\")\n fpath = filemanager.getPath(\"LigacaoXUnid.txt\") \n if path.isfile(fpath):\n with open(fpath, 'a') as file:\n rel = f'\\nData: {hora}\\n\\nEmpr.5: {emp5}\\nEmpr.6: {emp6}\\nEmpr.8: {emp8}\\nOutros: {outr}\\n'\n file.write(rel)\n else:\n with open(fpath, 'w') as file:\n rel = f'Relatório de ligações por unidade\\nData: {hora}\\n\\nEmpr.5: {emp5}\\nEmpr.6: {emp6}\\nEmpr.8: {emp8}\\nOutros: {outr}\\n'\n file.write(rel)\n\n messagebox.showinfo(title='Registro interno', message=f'Relaório criado:\\n\"{fpath}\"')","repo_name":"ViniciusLibano/prjRegistroInterno","sub_path":"model/relatorio.py","file_name":"relatorio.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"35810079534","text":"# Coin Flip Simulation\n\nimport random\nlength = []\ndef flip(x,y):\n chain = \"\"\n while (True):\n x = random.randint(x,y)\n if x == 0:\n chain += \"O\"\n else:\n chain += \"R\"\n n = len(chain)\n if n >= 3:\n if chain[n-1] == chain[n-2] and chain[n-1] == chain[n-3]:\n break\n return chain\n\nfor i in range(10):\n result = (flip(0,1))\n print(result)\n a = len(result)\n length.append(a)\n print(\"For getting the result\", len(result), \"flips were needed\")\n\nprint(length)\navarege = sum(length)/len(length)\nprint(\"Avarege number of flips needed\", avarege)\n","repo_name":"VladyslavHornitskyi/projects","sub_path":"project4.py","file_name":"project4.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"19314596035","text":"\nfrom datetime import date\nfrom datetime import time\nfrom datetime import datetime\nfrom datetime import timedelta\n\ndef main1():\n print(timedelta(days=365, hours=5, minutes=1))\n\n n = datetime.now()\n print(\"Today is:\", n)\n\n print(\"one year from now:\", str(n + timedelta(days=365)))\n print(\"In two weeks and 3 days it will be:\", str(n + timedelta(weeks=2, days=3)))\n\n t = datetime.now() - timedelta(weeks=1)\n s = t.strftime(\"%A %B %d, %Y\")\n print(\"One week ago it was:\", s)\n\ndef main2():\n today = date.today()\n afd = date(today.year, 4, 1)\n if afd < today:\n print(\"April fool's day is passed:\", ((today - afd).days))\n afd = afd.replace(year = today.year + 1)\n time_to_afd = afd - today\n print(\"April fool's day is in:\", time_to_afd.days, \"days\")\n\nif __name__ == \"__main__\":\n main2()","repo_name":"mills312/linkin_learn_py_2020","sub_path":"timedeltas_start.py","file_name":"timedeltas_start.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"27768050331","text":"import cv2\nimport mediapipe as mp\nimport math\n\n# 初始化姿势检测模型\nmp_pose = mp.solutions.pose\npose = mp_pose.Pose()\n\n# 读取视频\ncap = cv2.VideoCapture('badminton_training.mp4')\n\n# 初始化计数器和列表存储运动员坐标\ncounter = 0\ncoords = []\n\n\n# 定义运动姿势判断函数\ndef check_pose(coords):\n # 设定关键关节点坐标阈值\n thresholds = {\n 'shoulder': 30,\n 'elbow': 20,\n 'wrist': 15,\n 'hip': 30,\n 'knee': 20,\n 'ankle': 15\n }\n\n # 关键点索引\n keypoints = {\n 'left_shoulder': 11,\n 'right_shoulder': 12,\n 'left_elbow': 13,\n 'right_elbow': 14,\n 'left_wrist': 15,\n 'right_wrist': 16,\n 'left_hip': 23,\n 'right_hip': 24,\n 'left_knee': 25,\n 'right_knee': 26,\n 'left_ankle': 27,\n 'right_ankle': 28\n }\n\n # 判断关键点间的距离\n for key, threshold in thresholds.items():\n key_parts = key.split('_')\n left_keypoint = keypoints[f\"left_{key_parts[0]}\"]\n right_keypoint = keypoints[f\"right_{key_parts[0]}\"]\n if abs(coords[left_keypoint][0] - coords[right_keypoint][0]) > threshold:\n print(f'{key_parts[0].capitalize()}距离过大,姿势不标准')\n else:\n print(f'{key_parts[0].capitalize()}距离正常')\n\n\n# 计算运动员移动距离\ndef calculate_distance(coords):\n if len(coords) >= 2:\n last_frame = coords[-2]\n current_frame = coords[-1]\n hip_center_last = [(last_frame[23][0] + last_frame[24][0]) / 2, (last_frame[23][1] + last_frame[24][1]) / 2]\n hip_center_current = [(current_frame[23][0] + current_frame[24][0]) / 2,\n (current_frame[23][1] + current_frame[24][1]) / 2]\n distance = math.sqrt((hip_center_current[0] - hip_center_last[0]) ** 2 + (\n hip_center_current[1] - hip_center_last[1]) ** 2)\n return distance\n else:\n return 0\n\n\n# 循环检测视频中的每一帧\nwhile cap.isOpened():\n # 读取帧\n ret, frame = cap.read()\n\n # 如果读取帧成功,进行检测\n if ret:\n\n # 将当前帧发送到Pose检测模型\n results = pose.process(frame)\n\n # 如果检测到人体,获取人体关节点的坐标\n if results.pose_landmarks:\n # 获取当前帧中人体关节点的相关坐标\n landmark_coords = []\n for _, landmark in enumerate(results.pose_landmarks.landmark):\n landmark_coords.append([landmark.x, landmark.y, landmark.z, landmark.visibility])\n\n # 将当前人体坐标添加到总坐标列表中\n coords.append(landmark_coords)\n\n # 根据坐标列表判断姿势\n check_pose(coords)\n\n # 计算移动距离\n distance = calculate_distance(coords)\n print(f'移动距离: {distance}')\n\n # 显示当前帧并标注关键点\n mp_pose.draw_landmarks(\n frame,\n results.pose_landmarks,\n mp_pose.POSE_CONNECTIONS\n )\n\n # 显示图像\n cv2.imshow('MediaPipe Pose', frame)\n\n # 如果q键被按下,退出循环\n if cv2.waitKey(10) & 0xFF == ord('q'):\n break\n\n # 增加帧计数器\n counter += 1\n\n# 释放资源\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"youngzs/badminton_training","sub_path":"badminton_pose.py","file_name":"badminton_pose.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"33"} +{"seq_id":"35452745493","text":"import pygame\nfrom pygame.sprite import Sprite\n\nclass Ship(Sprite):\n\tdef __init__(self,settings,screen):\n\t\tsuper().__init__()\n\t\tself.screen = screen\n\t\tself.settings = settings\n\t\t\n\t\tself.image = pygame.image.load('images/ship.bmp')\n\t\tself.rect = self.image.get_rect()\n\t\tself.screen_rect = self.screen.get_rect()\n\t\t\n\t\tself.rect.centerx = self.screen_rect.centerx\n\t\tself.rect.bottom = self.screen_rect.bottom\n\t\tself.x = float(self.rect.centerx)\n\t\tself.y = float(self.rect.centery)\n\t\t\n\t\tself.moving_right = False\n\t\tself.moving_left = False\n\t\tself.moving_up = False\n\t\tself.moving_down = False\n\t\t\t\n\tdef update(self):\n\t\tself.ship_moving()\n\t\tself.rect.centerx = self.x\n\t\tself.rect.centery = self.y\n\t\t\n\tdef ship_moving(self):\n\t\tif self.moving_right and (self.rect.right <= \n\t\t\t\tself.screen_rect.right):\n\t\t\tself.x += self.settings.ship_speed_factor\n\t\tif self.moving_left and self.rect.left >= 0:\n\t\t\tself.x -= self.settings.ship_speed_factor\n\t\tif self.moving_up and self.rect.top >= 0:\n\t\t\tself.y -= self.settings.ship_speed_factor*2/3\n\t\tif self.moving_down and (self.rect.bottom <= \n\t\t\t\tself.screen_rect.bottom):\n\t\t\tself.y += self.settings.ship_speed_factor*2/3\n\t\t\n\tdef relocate_ship(self):\n\t\tself.x = self.screen_rect.centerx\n\t\tself.rect.bottom = self.screen_rect.bottom\n\t\t#下一步十分重要,否则update()的时候rect.centery会变成之前ship_moving()\n\t\t#\t里改变了的self.y,即重生点y坐标会回到死亡点的y坐标,而不是到最底下\n\t\tself.y = self.rect.y\n\t\t\n\tdef blitme(self):\n\t\tself.screen.blit(self.image,self.rect)\n\t\t\n","repo_name":"sunfanyi/Alien-Invasion_mini-game_Python-Pygame","sub_path":"ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"26897765315","text":"import tensorflow as tf\nimport numpy as np\n\n# import os,sys \n# parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) \n# sys.path.insert(0,parentdir) \n# from mylib.data_import import dataCreate \ndef CNN():\n from mylib.data_import import dataCreate \n def weight_variable(shape):\n initial = tf.truncated_normal(shape,seed=1,stddev=0.1) \n return tf.Variable(initial,name='weight')\n def bias_variable(shape):\n initial = tf.constant(0.1,shape=shape)\n return tf.Variable(initial,name='bias')\n def conv2d(x,W):\n return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME',name='conv')\n def max_pool(x,size):\n return tf.nn.max_pool(x,ksize=size,strides = [1,2,2,1],padding='SAME',name='max_pool')\n\n label_size = 7\n\n with tf.name_scope('input'):\n x_skeleton = tf.placeholder(tf.float32,[None,29,20,3],name='x_skeleton')\n x_motion = tf.placeholder(tf.float32,[None,29,20,3],name='x_motion')\n # x_skeleton = tf.placeholder(tf.float32,[None,29,14,3],name='x_skeleton')\n # x_motion = tf.placeholder(tf.float32,[None,29,14,3],name='x_motion')\n y_ = tf.placeholder(tf.float32,[None,label_size],name='y_prediction')\n keep_prob = tf.placeholder(tf.float32,name='keep_prob')\n\n #===============================Conv===================================\n with tf.name_scope('skeleton_conv'):\n W_conv_skeleton1 = weight_variable([5,3,3,64])\n b_conv_skeleton1 = bias_variable([64])\n h_conv_skeleton1 = tf.nn.leaky_relu(conv2d(x_skeleton,W_conv_skeleton1) + b_conv_skeleton1)\n h_pool_skeleton1 = max_pool(h_conv_skeleton1,[1,3,3,1])\n\n W_conv_skeleton2 = weight_variable([5,3,64,128])\n b_conv_skeleton2 = bias_variable([128])\n h_conv_skeleton2 = tf.nn.leaky_relu(conv2d(h_pool_skeleton1,W_conv_skeleton2) + b_conv_skeleton2)\n h_pool_skeleton2 = max_pool(h_conv_skeleton2,[1,3,3,1])\n\n with tf.name_scope('motion_conv'):\n W_conv_motion1 = weight_variable([5,3,3,64])\n b_conv_motion1 = bias_variable([64])\n h_conv_motion1 = tf.nn.leaky_relu(conv2d(x_motion,W_conv_motion1) + b_conv_motion1)\n h_pool_motion1 = max_pool(h_conv_motion1,[1,3,3,1])\n\n W_conv_motion2 = weight_variable([5,3,64,128])\n b_conv_motion2 = bias_variable([128])\n h_conv_motion2 = tf.nn.leaky_relu(conv2d(h_pool_motion1,W_conv_motion2) + b_conv_motion2)\n h_pool_motion2 = max_pool(h_conv_motion2,[1,3,3,1])\n\n #=================================Concat================================ \n with tf.name_scope('concat'):\n x_concat = tf.concat([h_pool_skeleton2, h_pool_motion2],axis=1)\n\n #============================fully connected============================\n\n with tf.name_scope('fully_connected_layer'):\n W_fc1 = weight_variable([2*8*5*128,32])\n # W_fc1 = weight_variable([2*8*4*128,32])\n b_fc1 = bias_variable([32])\n x_concat_flat = tf.reshape(x_concat,[-1,2*8*5*128])\n # x_concat_flat = tf.reshape(x_concat,[-1,2*8*4*128])\n h_fc1 = tf.nn.leaky_relu(tf.matmul(x_concat_flat,W_fc1) + b_fc1 )\n h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)\n\n # W_fc2 = weight_variable([64, 32])\n # b_fc2 = bias_variable([32])\n # h_fc2 = tf.nn.leaky_relu(tf.matmul(h_fc1_drop,W_fc2) + b_fc2)\n # h_fc2_drop = tf.nn.dropout(h_fc2,keep_prob)\n\n W_fc3 = weight_variable([32, 16])\n b_fc3 = bias_variable([16])\n h_fc3 = tf.nn.leaky_relu(tf.matmul(h_fc1_drop,W_fc3) + b_fc3)\n h_fc3_drop = tf.nn.dropout(h_fc3,keep_prob)\n\n W_fc4 = weight_variable([16, 8])\n b_fc4 = bias_variable([8])\n h_fc4 = tf.nn.leaky_relu(tf.matmul(h_fc3_drop,W_fc4) + b_fc4)\n h_fc4_drop = tf.nn.dropout(h_fc4,keep_prob)\n\n W_fc5 = weight_variable([8,label_size])\n b_fc5 = bias_variable([label_size])\n y_conv = tf.nn.leaky_relu(tf.matmul(h_fc4_drop,W_fc5) + b_fc5)\n\n with tf.name_scope('cross_entroy'):\n cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y_conv))\n tf.summary.scalar('loss',cross_entropy)\n\n with tf.name_scope('train'):\n current_iter = tf.Variable(0)\n learning_rate = tf.train.exponential_decay(0.01,current_iter,decay_steps=1000,decay_rate=0.003)\n train_step = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy ,global_step=current_iter)\n\n with tf.name_scope('accuracy'):\n correct_prediciton = tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediciton,tf.float32))\n tf.summary.scalar('accuracy',accuracy)\n\n\n\n merged_summary_op = tf.summary.merge_all()\n\n init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\n\n data = dataCreate(model='CNN')\n # data.run()\n data.data()\n\n saver = tf.train.Saver()\n\n _batch_size = 200\n result = 0\n with tf.Session() as sess:\n sess.run(init)\n train_writer = tf.summary.FileWriter(\"CNN_Train/logs/train\",sess.graph)\n test_writer = tf.summary.FileWriter(\"CNN_Train/logs/test\",sess.graph)\n # training\n for i in range(450):\n \n batch_skeleton,batch_motion, batch_y = data.next_batch(i,_batch_size)\n test_skeleton,test_motion,test_label = data.next_batch(i,flag=1)\n\n sess.run(train_step, feed_dict={x_skeleton:batch_skeleton,x_motion:batch_motion, y_:batch_y, keep_prob:0.5})\n \n train_result = sess.run(merged_summary_op, feed_dict={x_skeleton:batch_skeleton,x_motion:batch_motion, y_:batch_y, keep_prob:1})\n test_result = sess.run(merged_summary_op, feed_dict={x_skeleton:test_skeleton,x_motion:test_motion, y_:test_label, keep_prob:1})\n train_writer.add_summary(train_result,i+1)\n test_writer.add_summary(test_result,i+1)\n\n print(\"Optimization Finished!\")\n saver.save(sess,\"CNN_Train/Model4/model.ckpt\")\n # prediction\n result = sess.run(accuracy, feed_dict={x_skeleton:test_skeleton,x_motion:test_motion, y_:test_label, keep_prob:1})\n return result\nif __name__ == \"__main__\":\n import os,sys \n parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) \n sys.path.insert(0,parentdir) \n print(CNN())","repo_name":"ZacharyXue/Action-detection-using-Kinect","sub_path":"CNN_Train/keleton_based_classfication.py","file_name":"keleton_based_classfication.py","file_ext":"py","file_size_in_byte":7108,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"33"} +{"seq_id":"13157245310","text":"import os\n\nimport requests\nimport logging\nimport json\n\nfrom requests_toolbelt.multipart.encoder import MultipartEncoder\n\nmodule_logger = logging.getLogger('icad_tr_uploader.openmhz_uploader')\n\n\ndef upload_to_openmhz(openmhz, m4a_path, call_data):\n api_key = openmhz.get('api_key', None)\n short_name = openmhz.get('short_name', None)\n\n if not api_key or not short_name:\n module_logger.error(\"API Key or Short Name not found.\")\n return False\n\n call_data[\"short_name\"] = short_name\n call_data[\"api_key\"] = api_key\n\n source_list = []\n if len(call_data.get('srcList', 0)) != 0:\n for source in call_data['srcList']:\n source_list.append({\"pos\": source['pos'], \"src\": source['src']})\n\n multipart_data = MultipartEncoder(\n fields={\n 'call': (os.path.basename(m4a_path), open(m4a_path, 'rb'), 'application/octet-stream'),\n 'freq': str(call_data['freq']),\n 'error_count': str(0),\n 'spike_count': str(0),\n 'start_time': str(call_data['start_time']),\n 'stop_time': str(call_data['start_time'] + call_data[\"call_length\"]),\n 'call_length': str(call_data[\"call_length\"]),\n 'talkgroup_num': str(call_data[\"talkgroup\"]),\n 'emergency': str(0),\n 'api_key': api_key,\n 'source_list': json.dumps(source_list)\n }\n )\n\n session = requests.Session()\n response = session.post(\n url=f\"https://api.openmhz.com/{short_name}/upload\",\n data=multipart_data,\n headers={'User-Agent': 'TrunkRecorder1.0', 'Content-Type': multipart_data.content_type}\n )\n\n if response.status_code == 200:\n module_logger.info('Upload successful.')\n else:\n module_logger.error('Upload failed.')\n return response\n","repo_name":"TheGreatCodeholio/icad_tr_uploader","sub_path":"lib/openmhz_handler.py","file_name":"openmhz_handler.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"16652537159","text":"import pytest\nimport sciwing.constants as constants\nfrom sciwing.datasets.seq_labeling.conll_dataset import CoNLLDatasetManager\nfrom sciwing.utils.class_nursery import ClassNursery\nimport pathlib\n\nPATHS = constants.PATHS\nDATA_DIR = PATHS[\"DATA_DIR\"]\nDATA_DIR = pathlib.Path(DATA_DIR)\n\n\n@pytest.fixture\ndef setup_science_ie_dataset():\n train_filename = DATA_DIR.joinpath(\"train_science_ie_conll.txt\")\n dev_filename = DATA_DIR.joinpath(\"dev_science_ie_conll.txt\")\n data_manager = CoNLLDatasetManager(\n train_filename=train_filename,\n dev_filename=dev_filename,\n test_filename=dev_filename,\n column_names=[\"TASK\", \"PROCESS\", \"MATERIAL\"],\n )\n return data_manager\n\n\nclass TestScienceIE:\n def test_label_namespaces(self, setup_science_ie_dataset):\n data_manager = setup_science_ie_dataset\n label_namespaces = data_manager.label_namespaces\n assert \"TASK\" in label_namespaces\n assert \"PROCESS\" in label_namespaces\n assert \"MATERIAL\" in label_namespaces\n\n def test_num_classes(self, setup_science_ie_dataset):\n data_manager = setup_science_ie_dataset\n label_namespaces = data_manager.label_namespaces\n for namespace in label_namespaces:\n assert data_manager.num_labels[namespace] == 9\n\n def test_lines_labels_not_empty(self, setup_science_ie_dataset):\n data_manager = setup_science_ie_dataset\n lines, labels = data_manager.train_dataset.get_lines_labels()\n\n for line, label in zip(lines, labels):\n line_text = line.text\n task_label_tokens = label.tokens[\"TASK\"]\n process_label_tokens = label.tokens[\"PROCESS\"]\n material_label_tokens = label.tokens[\"MATERIAL\"]\n\n task_label_tokens = [tok.text for tok in task_label_tokens]\n process_label_tokens = [tok.text for tok in process_label_tokens]\n material_label_tokens = [tok.text for tok in material_label_tokens]\n\n assert bool(line_text.strip())\n assert all([bool(tok) for tok in task_label_tokens])\n assert all([bool(tok) for tok in process_label_tokens])\n assert all([bool(tok) for tok in material_label_tokens])\n\n def test_lines_labels_are_equal_length(self, setup_science_ie_dataset):\n data_manager = setup_science_ie_dataset\n lines, labels = data_manager.train_dataset.get_lines_labels()\n\n for line, label in zip(lines, labels):\n line_tokens = line.tokens[\"tokens\"]\n line_tokens = [tok.text for tok in line_tokens]\n for namespace in [\"TASK\", \"PROCESS\", \"MATERIAL\"]:\n label_tokens = label.tokens[namespace]\n label_tokens = [tok.text for tok in label_tokens]\n assert len(line_tokens) == len(label_tokens)\n\n def test_science_ie_in_nursery(self):\n assert ClassNursery.class_nursery.get(\"CoNLLDatasetManager\") is not None\n","repo_name":"abhinavkashyap/sciwing","sub_path":"tests/datasets/seq_labeling/test_science_ie_dataset.py","file_name":"test_science_ie_dataset.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"33"} +{"seq_id":"35221039570","text":"import json\nimport re\nfrom pylab import *\nfig = figure(figsize=(8,6), dpi=300)\ny1 = fig.add_subplot(111)\ny1.set_xlabel('Iterations')\ny2 = y1.twinx()\ny1.set_ylim(0,1.0)\nwith open(r'./日志名.txt') as f:\n whole = f.read()\n pattern = re.compile(r'json_stats: (\\{.*\\})')\n lis = pattern.findall(whole)\n try:\n parsed = [json.loads(j) for j in lis]\n print(parsed[0])\n except:\n print(\"json format is not corrrect\")\n exit(1)\n\n _iter = [ j['iter'] for j in parsed]\n _loss = [ j['loss'] for j in parsed]\n _loss_bbox = [ j['loss_bbox'] for j in parsed]\n _loss_cls = [ j['loss_cls'] for j in parsed]\n _accuracy_cls = [ j['accuracy_cls'] for j in parsed]\n _lr = [ j['lr'] for j in parsed]\n try:\n _mask_loss = [ j['mask_loss'] for j in parsed]\n except:\n _mask_loss = None\n\n y1.plot(_iter, _loss_bbox, color=\"green\", linewidth=1.0,linestyle=\"-\",label='loss_bbox')\n y1.plot(_iter, _loss, color=\"blue\", linewidth=1.0, linestyle=\"-\",label='loss')\n y1.plot(_iter, _loss_cls, color=\"black\", linewidth=1.0, linestyle=\"-\",label='loss_cls')\n y1.plot(_iter, _accuracy_cls, color=\"red\", linewidth=1.0, linestyle=\"-\",label='accuracy_cls')\n if _mask_loss is not None:\n y1.plot(_iter, _mask_loss, color=\"grey\", linewidth=1.0, linestyle=\"-\",label='mask_loss')\n\n y2.set_ylim(0,max(_lr)/0.8)\n y2.plot(_iter, _lr, color=\"purple\", linewidth=1.0, linestyle=\"-\",label='lr')\n y2.set_ylabel('lr')\n\n #可以选择开启网格\n #grid()\n #图例\n y1.legend()\n savefig('./fig.png')\n show()","repo_name":"lih980412/FSCE","sub_path":"tools/vis_log.py","file_name":"vis_log.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"16835814928","text":"from flask import Flask, render_template, redirect, url_for\nfrom flask_bootstrap import Bootstrap5\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import DataRequired, URL\nfrom flask_ckeditor import CKEditor, CKEditorField\nfrom datetime import date\n\n'''\nMake sure the required packages are installed: \nOpen the Terminal in PyCharm (bottom left). \n\nOn Windows type:\npython -m pip install -r requirements.txt\n\nOn MacOS type:\npip3 install -r requirements.txt\n\nThis will install the packages from the requirements.txt for this project.\n'''\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'\nBootstrap5(app)\nckeditor = CKEditor(app)\n\n\n# CONNECT TO DB\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'\ndb = SQLAlchemy()\ndb.init_app(app)\n\n\n# CONFIGURE TABLE\nclass BlogPost(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(250), unique=True, nullable=False)\n subtitle = db.Column(db.String(250), nullable=False)\n date = db.Column(db.String(250), nullable=False)\n body = db.Column(db.Text, nullable=False)\n author = db.Column(db.String(250), nullable=False)\n img_url = db.Column(db.String(250), nullable=False)\n\n\nwith app.app_context():\n db.create_all()\n\nclass NewPostForm(FlaskForm):\n title = StringField('Post Title', validators=[DataRequired()])\n subtitle = StringField('Subtitle', validators=[DataRequired()])\n author = StringField('Author', validators=[DataRequired()])\n img_url = StringField('Image background URL', validators=[DataRequired()])\n body = CKEditorField('Body')\n submit = SubmitField('Submit')\n\n@app.route('/')\ndef get_all_posts():\n # TODO: Query the database for all the posts. Convert the data to a python list.\n results = db.session.execute(db.select(BlogPost).limit(3)).scalars().all()\n posts = []\n for result in results:\n post = {\n \"title\": result.title,\n \"subtitle\": result.subtitle,\n \"id\": result.id,\n \"author\": result.author,\n \"date\": result.date\n }\n posts.append(post)\n return render_template(\"index.html\", all_posts=posts)\n\n\n# TODO: Add a route so that you can click on individual posts.\n@app.route('/show_post/', methods=[\"GET\", \"POST\"])\ndef show_post(post_id):\n # TODO: Retrieve a BlogPost from the database based on the post_id\n result = db.session.execute(db.select(BlogPost).where(BlogPost.id == post_id)).scalar()\n requested_post = {\n \"subtitle\": result.subtitle,\n \"author\": result.author,\n \"date\": result.date,\n \"body\": result.body,\n \"id\": result.id\n }\n return render_template(\"post.html\", post=requested_post)\n\n\n# TODO: add_new_post() to create a new blog post\n@app.route('/new-post/', methods=[\"GET\", \"POST\"])\ndef new_post():\n blog_form = NewPostForm()\n\n if blog_form.validate_on_submit():\n blog_post = {\n \"title\": blog_form.title.data,\n \"subtitle\": blog_form.subtitle.data,\n \"author\": blog_form.author.data,\n \"img_url\": blog_form.img_url.data,\n \"body\": blog_form.body.data\n }\n new_blog_post = BlogPost(\n title=blog_post[\"title\"],\n subtitle=blog_post[\"subtitle\"],\n body=blog_post[\"body\"],\n author=blog_post[\"author\"],\n img_url=blog_post[\"img_url\"],\n date=date.today().strftime(\"%B %d, %Y\")\n\n )\n db.session.add(new_blog_post)\n db.session.commit()\n return redirect(url_for('get_all_posts'))\n\n return render_template(\"make-post.html\", form=blog_form, pagetitle=\"New Post\")\n\n\n# TODO: edit_post() to change an existing blog post\n@app.route('/edit-post/', methods=[\"GET\", \"POST\"])\ndef edit_post(post_id):\n result = db.session.execute(db.select(BlogPost).where(BlogPost.id == post_id)).scalar()\n edit_blog_form = NewPostForm(\n title=result.title,\n subtitle = result.subtitle,\n author = result.author,\n img_url = result.img_url,\n body = result.body\n )\n if edit_blog_form.validate_on_submit():\n result.title = edit_blog_form.title.data\n result.subtitle = edit_blog_form.subtitle.data\n result.author = edit_blog_form.author.data\n result.img_url = edit_blog_form.title.data\n result.body = edit_blog_form.body.data\n db.session.commit()\n return redirect(url_for('show_post', post_id=post_id))\n\n return render_template(\"make-post.html\", form=edit_blog_form, pagetitle=\"Edit Post\")\n\n\n# TODO: delete_post() to remove a blog post from the database\n@app.route('/delete-post/', methods=[\"GET\", \"POST\"])\ndef delete_post(post_id):\n result = db.session.execute(db.select(BlogPost).where(BlogPost.id == post_id)).scalar()\n db.session.delete(result)\n db.session.commit()\n return redirect(url_for('get_all_posts'))\n\n# Below is the code from previous lessons. No changes needed.\n@app.route(\"/about\")\ndef about():\n return render_template(\"about.html\")\n\n\n@app.route(\"/contact\")\ndef contact():\n return render_template(\"contact.html\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, port=5003)\n","repo_name":"greenhalghdan/day-67-starting-files-upgraded-blog","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"277624837","text":"from preprocess.processor import Processor\nfrom preprocess.util import read_s3\nfrom preprocess.move_average import MoveAverage\nfrom preprocess.ohlc import Ohlc\nfrom preprocess.bollinger_band import BollingerBand\nfrom preprocess.stochastics import Stochastics\nfrom preprocess.correlation import Correlation\nfrom model.ml.lgbm import LgbModel\nfrom model.ml.linner import LinnerModel\nfrom preprocess.stacking import Stacking\nfrom preprocess.util import check_ymd, save_parquet\nimport glob\n\nimport pandas as pd\nimport gc\n\nimport argparse\n\nimport os\n\n\ndef data_make(process_name, ymd):\n if process_name == \"move_average\":\n processor = Processor(MoveAverage, ymd)\n elif process_name == \"ohlc\":\n processor = Processor(Ohlc, ymd)\n elif process_name == \"bollinger_band\":\n processor = Processor(BollingerBand, ymd)\n elif process_name == \"stochastics\":\n processor = Processor(Stochastics, ymd)\n elif process_name == \"correlation\":\n processor = Processor(Correlation, ymd)\n return processor.run()\n\ndef train(name, ymd):\n X_train, X_val, X_test, y_train, y_val, y_test = data_make(name, ymd)\n \n model = LgbModel(name, X_train, y_train, X_val, y_val)\n model.train()\n y_pred = model.predict(X_test)\n\n score, precision_recall, metrics = model.validation(y_test, y_pred) \n explain = pd.DataFrame(model.get_importance(), index=X_train.columns).T\n \n for data in [score, precision_recall, metrics, explain]:\n data[\"method\"] = name\n data[\"Date\"] = ymd\n \n save_score(score)\n save_metrics(metrics)\n save_explain(explain)\n save_precision_recall(precision_recall)\n\ndef save_score(score):\n save_parquet(\n df = score,\n bucket = \"stock-scope-bucket\",\n key = \"prediction\",\n filename = \"score\",\n cols = [\"Date\", \"method\"]\n )\n\ndef save_metrics(metrics):\n save_parquet(\n df = metrics,\n bucket = \"stock-scope-bucket\",\n key = \"prediction\",\n filename = \"metrics\",\n cols = [\"Date\", \"method\"]\n )\n\ndef save_precision_recall(precision_recall):\n save_parquet(\n df = precision_recall,\n bucket = \"stock-scope-bucket\",\n key = \"prediction\",\n filename = \"precision_recall\",\n cols = [\"Date\", \"method\"]\n )\n\ndef save_explain(explain):\n save_parquet(\n df = explain,\n bucket = \"stock-scope-bucket\",\n key = \"prediction\",\n filename = \"explain\",\n cols = [\"Date\", \"method\"]\n )\n\n\ndef ensemble(model_list, start, end, ymd):\n for model in model_list:\n files = glob.glob(\"./result/*\")\n simulate(model, start, end)\n\n date_idx = set([ymd.strftime(\"%Y-%m-%d\") for ymd in pd.date_range(ymd,end)])\n date_idx = check_ymd(date_idx)\n\n result_list = []\n for ymd in date_idx:\n processor = Stacking(model_list, start, end, ymd)\n df = processor.process()\n print(df)\n X_train, X_val, X_test, y_train, y_val, y_test = processor.data_split(df)\n model = LinnerModel(model_list)\n model.train(X_train, y_train, X_val, y_val)\n y_pred = model.predict(X_test)\n result, auc = model.validation(y_test, y_pred)\n print(auc)\n result_list.append(result)\n gc.collect()\n\n results = pd.concat(result_list)\n results.sort_values(\"pred\").to_csv(\"./result/stacking_result.csv\", index=False)\n\n \ndef simulate(name, start, end):\n result_list = []\n score_df = pd.read_csv(f\"./result/{name}_result.csv\")\n\n ymd_list = set(score_df[\"ymd\"])\n date_idx = set([ymd.strftime(\"%Y-%m-%d\") for ymd in pd.date_range(start,end)])\n date_idx = date_idx - ymd_list\n date_idx = check_ymd(date_idx)\n\n if len(date_idx) == 0:\n print(f\"{name} is all updated\")\n return\n \n for ymd in date_idx:\n print(f\"{name}_{ymd}_start\")\n result = train(name, ymd)\n result_list.append(result)\n\n results = pd.concat(result_list)\n results = pd.concat([score_df, results])\n results.sort_values(\"pred\").to_csv(f\"./result/{name}_result.csv\", index=False)\n \n \n print(results)\n \n\nif __name__ == \"__main__\":\n print(\"learning start\")\n alg = os.environ[\"ALG\"]\n ymd = os.environ[\"YMD\"]\n result = train(alg, ymd)\n\n print(\"learning end\")\n \n \n","repo_name":"mattyamonaca/StockScope","sub_path":"scripts/ml/entry_point.py","file_name":"entry_point.py","file_ext":"py","file_size_in_byte":4287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"22773427627","text":"import requests, bs4\nfrom bs4 import BeautifulSoup\nimport xlsxwriter\n# xlsxwriter document: https://xlsxwriter.readthedocs.io/\n\nLIST_PAGE_URL_CN = 'https://www.fmprc.gov.cn/web/ziliao_674904/zyjh_674906/'\nLIST_PAGE_URL_EN = 'https://www.fmprc.gov.cn/mfa_eng/wjdt_665385/zyjh_665391/'\nSAVE_FILE = 'data.xlsx' #保存的文件\n\n# Crawl the list page and return article url\ndef get_article_list(url, selector):\n res = requests.get(url,\n headers = {'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36'})\n # print(r.content)\n soup = BeautifulSoup(res.text, 'html.parser')\n link_eles = soup.select(selector)\n links = [ele.get('href') for ele in link_eles]\n \n print('====> links len=', len(links))\n return links\n\ndef get_article_doc(url, lang='en', title_sel='', time_sel='', content_sel=''):\n res = requests.get(url,\n headers = {'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36'})\n # print('Encoding=====>', res.encoding)\n res.encoding = \"gbk2312\" # charset 解决中文编码问题\n # print(res.text)\n\n if title_sel=='' or time_sel=='' or content_sel=='':\n print('[Error]: No selector sepcify!')\n return []\n\n soup = BeautifulSoup(res.text, 'html.parser')\n title = soup.select(title_sel)[0].get_text()\n time = soup.select(time_sel)[0].get_text()\n full_content = soup.select(content_sel)[0].get_text()\n\n print('[title]====>', title)\n\n return [title, time, full_content]\n\ndef init_worksheet(workbook, name, style):\n # Add sheet\n worksheet = workbook.add_worksheet(name)\n # Write sheet head\n row0 = [\"title\", \"time\", \"content\"]\n for i in range(0,len(row0)):\n worksheet.write(0,i,row0[i], style)\n \n return worksheet\n\n\nif __name__ == '__main__': \n workbook = xlsxwriter.Workbook(SAVE_FILE)\n # Add style\n bold = workbook.add_format({'bold': True})\n regular = workbook.add_format({'bold': False})\n\n # crawl CN data \n worksheet_cn = init_worksheet(workbook, 'cn', bold)\n\n article_links_cn = get_article_list(LIST_PAGE_URL_CN, '.newsBd a')\n # article_links = ['./202112/t20211201_10460659.shtml'] # for test\n \n # other page of list\n for page in range(1, 24): # 24\n article_links_cn += get_article_list(LIST_PAGE_URL_CN + \"index_%d.shtml\" % page, '.newsBd a')\n \n for index, link in enumerate(article_links_cn):\n full_link = LIST_PAGE_URL_CN + link\n # print('full_link:', full_link)\n title_sel = \".news-title h1\"\n time_sel = \".news-title p.time\"\n content_sel = \".news-main\"\n article_data = get_article_doc(full_link, 'cn', title_sel, time_sel, content_sel)\n for i in range(0,len(article_data)):\n worksheet_cn.write(index+1,i,article_data[i], regular)\n\n # crawl EN data \n worksheet_en = init_worksheet(workbook, 'en', bold)\n article_links_en = get_article_list(LIST_PAGE_URL_EN, '.newsLst_mod a')\n # print('======>', len(article_links_en))\n # article_links_en = [article_links_en[0]] # for test\n for index, link in enumerate(article_links_en):\n full_link = LIST_PAGE_URL_EN + link\n title_sel = \".content_mod h2.title\"\n time_sel = \".content_mod #News_Body_Time\"\n content_sel = \".content_mod .content\"\n article_data = get_article_doc(full_link, 'en', title_sel, time_sel, content_sel)\n for i in range(0,len(article_data)):\n worksheet_en.write(index+1,i,article_data[i], regular)\n \n workbook.close()\n\n","repo_name":"twinkletwinklelittlestar70/fmprc_gov_speech_crawler","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"19453843887","text":"from yovirmac.modules.constants import *\nfrom yovirmac.modules.errors import *\nfrom yovirmac.modules.object_control import link\nfrom yovirmac.modules.tape_control import append, pull\nfrom yovirmac.modules.types_control import write\nfrom yovirmac.modules.segment_control import find, change\n\n\ndef Jump(arg):\n arg_type, arg_value = arg\n if arg_type == \"link\":\n change.attribute(seg_links[\"system\"], \"target_cell\", arg_value)\n else:\n raise UndefinedBehaviour(f\"Поведение команды Jmp с аргументом типа\"\n f\"{arg_type} не определено\")\n\n\ndef Jump_if(condition, arg):\n cond_arg_type, cond_type, cond_value = link.unpack(condition)\n arg_type, arg_value = arg\n if arg_type == \"link\":\n if cond_type == \"logic\":\n if not cond_value:\n change.attribute(seg_links[\"system\"], \"target_cell\", arg_value)\n append.memory_stack(\"link\", 0)\n else:\n raise UndefinedBehaviour(\n f\"Поведение команды Jif с аргументами типов {arg_type} и \"\n f\"{cond_type} не определено\")\n else:\n raise UndefinedArgument(f\"Поведение команды Jif с аргументом типа\"\n f\"{arg_type} не определено\")\n\n\ndef End():\n change.attribute(seg_links[\"system\"], \"target_cell\", 0)\n","repo_name":"PenzaStreetGames/Yo","sub_path":"yovirmac/modules/upper_commands/jumps.py","file_name":"jumps.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"ru","doc_type":"code","stars":4,"dataset":"github-code","pt":"33"} +{"seq_id":"3732553148","text":"import tkinter as tk\nfrom tkinter import *\n \ncounter = -1\nrunning = False\ndef counter_label(label): \n def count(): \n if running: \n global counter \n if counter==-1: \n display=\"Starting...\"\n else: \n display=str(counter) \n \n label['text']=display \n label.after(1000, count) \n counter += 1\n \n \n count() \n \ndef Start(label): \n global running \n running=True\n counter_label(label) \n start['state']='disabled'\n stop['state']='normal'\n reset['state']='normal'\n \n\ndef Stop(): \n global running \n start['state']='normal'\n stop['state']='disabled'\n reset['state']='normal'\n running = False\n \n\ndef Reset(label): \n global counter \n counter=-1\n \n if running==False: \n reset['state']='disabled'\n label['text']='Welcome!'\n \n else: \n label['text']='Starting...'\n \nroot = Tk() \nroot.title(\"Stopwatch\") \n \n# Fixing the window size. \nroot.minsize(width=250, height=70) \nlabel = tk.Label(root, text=\"Welcome!\", fg=\"black\", font=\"Verdana 30 bold\") \nlabel.pack() \nstart = tk.Button(root, text='Start', \nwidth=15, command=lambda:Start(label)) \nstop = tk.Button(root, text='Stop', \nwidth=15, state='disabled', command=Stop) \nreset = tk.Button(root, text='Reset', \n width=15, state='disabled', command=lambda:Reset(label)) \nstart.pack() \nstop.pack() \nreset.pack() \nroot.mainloop() \n","repo_name":"Infinity8sailor/pythonlab-program","sub_path":"basics/time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"70878034975","text":"from typing import Tuple\n\n\nclass OutOfDomain(Exception):\n def __init__(self, value: int | float, domain: Tuple[int | float | str, int | float | str] = (0, \"inf\"),\n brackets: str = \"()\") -> None:\n message = f\"Argument {value} contains a value outside of the function domain {brackets[0]}{domain[0]}, \" \\\n f\"{domain[1]}{brackets[1]}\"\n super().__init__(message)\n\n\nclass TooFewInputs(Exception):\n def __init__(self, input_size: int, min_size: int, block_name: str) -> None:\n message = f\"The input composed of {input_size} variables is too small for {block_name} that requires {min_size} \" \\\n \"variables\"\n super().__init__(message)\n","repo_name":"jkarolczak/function-synthesis","sub_path":"src/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"677280831","text":"import os\nimport sys\nimport glob\nimport torch\nimport pandas as pd\nimport numpy as np\nimport random\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision.transforms import Lambda, Compose\nfrom torch.utils.data.sampler import SubsetRandomSampler\n\nsys.path.append('/home/jovyan/train')\n#from Meta import Meta\n\nclass LSTMLandmarkDataset(Dataset):\n \"\"\"PyTorch Custom Dataset and Dataloader reference:\n https://pytorch.org/tutorials/beginner/basics/data_tutorial.html#creating-a-custom-dataset-for-your-files\n https://pytorch.org/tutorials/recipes/recipes/custom_dataset_transforms_loader.html\n\n transform: functions on data\n target_transform: transform on label\n \"\"\"\n\n\n\n def __init__(self, data_dir, model_dir, seq_len, transform = None, target_transform = None):\n\n self.file_list = []\n self.landmark_frames = pd.DataFrame()\n self.class_map = {}\n self.num_class = 0\n self.seq_len = seq_len\n\n # concatenate directory, assign class index\n self.file_list = sorted( glob.glob(data_dir + \"/*.csv\") )\n for class_idx, filename in enumerate(self.file_list):\n class_name = filename.replace('.csv', '').split('/')[-1]\n self.class_map[class_idx] = class_name\n\n landmark_frame = pd.read_csv(filename, header=None)\n\n # add class label to dataframe\n landmark_frame.insert(0, \"class_idx\", class_idx)\n\n # concatenate dataframes into memory\n self.landmark_frames = pd.concat([self.landmark_frames, landmark_frame])\n\n\n self.num_class = len(self.class_map)\n self.num_sequence = len(self.landmark_frames) // self.seq_len\n\n self.transform = transform\n self.target_transform = target_transform\n\n\n def __len__(self):\n return int(len(self.landmark_frames) / self.seq_len)\n\n def __getitem__(self, idx):\n seq_start_idx = idx * self.seq_len\n seq_end_idx = (idx + 1) * self.seq_len\n sequence = self.landmark_frames[seq_start_idx:seq_end_idx]\n return int(sequence.iloc[0][\"class_idx\"]), sequence.values[:, 1:]\n\n # len of landmark points\n def input_size(self):\n r = random.randint(0, int(len(self) / self.seq_len) )\n _, landmarks = self[r]\n return len(landmarks[0])\n\n\n#\n# ~/python -i LandmarkDataset.py\n#\nif __name__ == \"__main__\":\n\n transformations = Compose([\n Lambda(lambda x: torch.tensor(x.values))\n ])\n\n dataset = LSTMLandmarkDataset(\"/home/jovyan/train/lstm_data\",\n \"/home/jovyan/model\",\n 30,\n transform=transformations)\n\n # Splitting\n # https://stackoverflow.com/questions/50544730/how-do-i-split-a-custom-dataset-into-training-and-test-datasets/50544887#50544887\n # https://pytorch.org/docs/stable/data.html#torch.utils.data.Sampler\n #\n # Stratified Sample\n # ensure we take split_p of each class (class sizes can vary) vs split_p of entire dataset (unbalanced distribution)\n # filter for each class, collect train/val split, and sample from those respective collections\n #\n # Split your dataset into train and test indices\n num_samples = len(dataset)\n indices = list(range(num_samples))\n split = int(np.floor(0.2 * num_samples)) # 20% test set\n np.random.shuffle(indices)\n train_indices, test_indices = indices[split:], indices[:split]\n\n # Define samplers for each split\n train_sampler = SubsetRandomSampler(train_indices)\n test_sampler = SubsetRandomSampler(test_indices)\n\n # Define dataloaders for each split\n batch_size = 1\n train_dataloader = DataLoader(dataset, batch_size=batch_size, sampler=train_sampler)\n valid_dataloader = DataLoader(dataset, batch_size=batch_size, sampler=test_sampler)\n\n def print_dataloader(dataloader):\n for batch_idx, sample in enumerate(dataloader):\n print(batch_idx, sample[0])\n\n print(\"TRAIN\")\n print_dataloader(train_dataloader)\n\n print(\"VALID\")\n print_dataloader(valid_dataloader)\n","repo_name":"vergeman/pit-trader","sub_path":"model/LSTMLandmarkDataset.py","file_name":"LSTMLandmarkDataset.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"14259088045","text":"if args.algo in ['a2c', 'acktr']:\n values, action_log_probs, dist_entropy = actor_critic.evaluate_actions(Variable(rollouts.states[:-1].view(-1, *obs_shape)), Variable(rollouts.actions.view(-1, action_shape)))\n \n values = values.view(args.num_steps, args.num_processes, 1)\n action_log_probs = action_log_probs.view(args.num_steps, args.num_processes, 1)\n\n advantages = Variable(rollouts.returns[:-1]) - values\n value_loss = advantages.pow(2).mean()\n\n action_loss = -(Variable(advantages.data) * action_log_probs).mean()\n (value_loss * args.value_loss_coef + action_loss - dist_entropy * args.entropy_coef).backward()\n\n if args.algo == 'a2c':\n nn.utils.clip_grad_norm(actor_critic.parameters(), args.max_grad_norm)\n\n optimizer.step()\nelif args.algo == 'ppo':\n advantages = rollouts.returns[:-1] - rollouts.value_preds[:-1]\n advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-5)\n\n '''copy all model parameter to old_model'''\n old_model.load_state_dict(actor_critic.state_dict())\n\n for _ in range(args.ppo_epoch):\n sampler = BatchSampler(SubsetRandomSampler(range(args.num_processes * args.num_steps)), args.batch_size * args.num_processes, drop_last=False)\n for indices in sampler:\n indices = torch.LongTensor(indices)\n if args.cuda:\n indices = indices.cuda()\n states_batch = rollouts.states[:-1].view(-1, *obs_shape)[indices]\n actions_batch = rollouts.actions.view(-1, action_shape)[indices]\n return_batch = rollouts.returns[:-1].view(-1, 1)[indices]\n\n # Reshape to do in a single forward pass for all steps\n values, action_log_probs, dist_entropy = actor_critic.evaluate_actions(Variable(states_batch), Variable(actions_batch))\n\n _, old_action_log_probs, _ = old_model.evaluate_actions(Variable(states_batch, volatile=True), Variable(actions_batch, volatile=True))\n\n ratio = torch.exp(action_log_probs - Variable(old_action_log_probs.data))\n adv_targ = Variable(advantages.view(-1, 1)[indices])\n surr1 = ratio * adv_targ\n surr2 = torch.clamp(ratio, 1.0 - args.clip_param, 1.0 + args.clip_param) * adv_targ\n action_loss = -torch.min(surr1, surr2).mean() # PPO's pessimistic surrogate (L^CLIP)\n\n value_loss = (Variable(return_batch) - values).pow(2).mean()\n\n optimizer.zero_grad()\n (value_loss + action_loss - dist_entropy * args.entropy_coef).backward()\n optimizer.step()\n","repo_name":"YuhangSong/GTN","sub_path":"ppo_optimize.py","file_name":"ppo_optimize.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"21296824758","text":"from turtle import *\nimport random\nimport draw\n\n# 二つの亀を相互回避酔歩させる\n# forによって簡潔化することは可能だが、_evasiveとの差別化のためにあえて現型を保持\n\n# 設定\nstep = 10 # 亀の歩幅。0より大きい実数を入力\ndistance = 60 # 二頭の亀の初期位置間の距離。0より大きい実数を入力。相互回避が成立するためには、stepの正整数倍である必要がある。\n\n# 準備\nt1 = Turtle()\nt2 = Turtle()\nt1_is_alive = True\nt2_is_alive = True\nt1.speed(0)\nt2.speed(0)\n\nt1.penup()\nt2.penup()\nt1.setpos(-distance/2, 0)\nt2.setpos(distance/2, 0)\nt1.pendown()\nt2.pendown()\n\n# log作成\nlog = {}\n\nfor t in [t1, t2]:\n x, y = t.pos()\n x, y = round(x), round(y)\n log[x] = {y}\n\n# 始点描画\ndraw.origin(t1, 6)\ndraw.origin(t2, 6)\n\n# 酔歩\nwhile t1_is_alive or t2_is_alive:\n if t1_is_alive:\n # 現在地取得\n x1, y1 = t1.pos()\n x1, y1 = round(x1), round(y1)\n\n # 移動可能な方向を取得\n directions = [0, 90, 180, 270]\n\n if y1+step in log[x1]:\n directions.remove(90)\n \n if y1-step in log[x1]:\n directions.remove(270)\n\n if x1+step in log.keys():\n if y1 in log[x1+step]:\n directions.remove(0)\n\n if x1-step in log.keys():\n if y1 in log[x1-step]:\n directions.remove(180)\n\n # いずれの方向にも移動不可能である場合は移動を終了\n if len(directions) == 0:\n t1_is_alive = False\n continue\n\n # 移動方向を決定\n randdirection = random.choice(directions)\n t1.setheading(randdirection)\n\n # 現在地と移動方向を出力\n print((x1, y1), randdirection)\n\n # 移動\n t1.forward(step)\n\n # 現在地をlogに追加\n if randdirection == 0:\n if x1+step in log.keys():\n log[x1+step].add(y1)\n else:\n log[x1+step] = {y1}\n elif randdirection == 90:\n log[x1].add(y1+step)\n elif randdirection == 180:\n if x1-step in log.keys():\n log[x1-step].add(y1)\n else:\n log[x1-step] = {y1}\n elif randdirection == 270:\n log[x1].add(y1-step)\n\n if t2_is_alive:\n # 現在地取得\n x2, y2 = t2.pos()\n x2, y2 = round(x2), round(y2)\n\n # 移動可能な方向を取得\n directions = [0, 90, 180, 270]\n\n if y2+step in log[x2]:\n directions.remove(90)\n \n if y2-step in log[x2]:\n directions.remove(270)\n\n if x2+step in log.keys():\n if y2 in log[x2+step]:\n directions.remove(0)\n\n if x2-step in log.keys():\n if y2 in log[x2-step]:\n directions.remove(180)\n\n # いずれの方向にも移動不可能である場合は移動を終了\n if len(directions) == 0:\n t2_is_alive = False\n continue\n\n # 移動方向を決定\n randdirection = random.choice(directions)\n t2.setheading(randdirection)\n\n # 現在地と移動方向を出力\n print((x2, y2), randdirection)\n\n # 移動\n t2.forward(step)\n\n # 移動先をlogに追加\n if randdirection == 0:\n if x2+step in log.keys():\n log[x2+step].add(y2)\n else:\n log[x2+step] = {y2}\n elif randdirection == 90:\n log[x2].add(y2+step)\n elif randdirection == 180:\n if x2-step in log.keys():\n log[x2-step].add(y2)\n else:\n log[x2-step] = {y2}\n elif randdirection == 270:\n log[x2].add(y2-step)\n\n# 終了\nprint(log)\ndone()\n","repo_name":"yatabashi/randomwalk","sub_path":"randomwalk_mutually-avoiding.py","file_name":"randomwalk_mutually-avoiding.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"2446638994","text":"import pprint\nimport numpy as np\nimport parse\nimport math\n\npp = pprint.PrettyPrinter()\n\ndef mag(v):\n return np.sqrt(v.dot(v))\n \ndef vadd(v, n):\n m = mag(v)\n if m == 0:\n return v * 1\n return (m + n) * (v / m)\n\ndef mv_both(vec_h, vec_t, mv_h):\n vec_h = vec_h + mv_h\n mov_t = np.round(vadd(vec_h - vec_t, -1))\n vec_t = vec_t + mov_t\n return vec_h, vec_t\n\ndef mv_tail(vec_h, vec_t, mv_h):\n mov_t = np.round(vadd(vec_h - vec_t, -1))\n vec_t = vec_t + mov_t\n return vec_t, mov_t\n\n#---------------------------------------------------------------\n\ndef prepare(file_path):\n with open(file_path, 'r') as infile:\n input = infile.read()\n\n moves = []\n for parsed in parse.findall(\"{cmd} {val:d}\\n\", input):\n cmd = parsed['cmd']\n val = parsed['val'] * 1.0\n moves.append({\n 'R': np.array((val, 0.0)),\n 'L': np.array((-val, 0.0)),\n 'U': np.array((0.0, val)),\n 'D': np.array((0.0, -val)),\n }[cmd])\n\n return moves\n\ndef part_1(moves):\n visited = {(0.0, 0.0),}\n\n vec_h = np.array((0, 0))\n vec_t = np.array((0, 0))\n for move in moves:\n mna = max(abs(move))\n for _ in range(1, int(mna + 1)):\n mov_h = move/mna\n vec_h, vec_t = mv_both(vec_h, vec_t, mov_h)\n\n visited.add(tuple(vec_t))\n\n return len(visited)\n\ndef part_2(moves):\n\n visited = {(0.0, 0.0),}\n\n vec_h = np.array((0.0, 0.0))\n vecs_t = [np.array((0.0, 0.0)) for n in range(9)]\n for move in moves:\n mna = max(abs(move))\n for i in range(1, int(mna + 1)):\n mov_t = move/mna\n vec_h = vec_h + mov_t\n vec_th = vec_h\n for i, vec_t in enumerate(vecs_t):\n vec_th, mov_t = mv_tail(vec_th, vec_t, mov_t)\n vecs_t[i] = vec_th\n\n visited.add(tuple(vecs_t[8]))\n\n return len(visited)\n\n\nif __name__ == '__main__':\n moves = prepare('input/day09.txt')\n print(\"--------- Day 8 -----------\")\n print(\"Part 1: %s\" % part_1(moves))\n print(\"Part 2: %s\" % part_2(moves))\n\n#---------------------------------------------------------------\nimport pytest\n\ndef test_part_1():\n moves = prepare('input/day09-example-1.txt')\n assert part_1(moves) == 13\n\ndef test_part_2():\n moves = prepare('input/day09-example-1.txt')\n assert part_2(moves) == 1\n moves = prepare('input/day09-example-2.txt')\n assert part_2(moves) == 36\n","repo_name":"vwallen/adventofcode-2022-python","sub_path":"day09.py","file_name":"day09.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"37235895299","text":"# from datetime import datetime\nimport calendar\nimport datetime\n\nimport pytz\n\nfrom odoo import models, fields, api\nfrom odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT\n\n\nclass ResourceCalender(models.Model):\n _inherit = \"resource.calendar\"\n\n max_sign_in = fields.Float(\"Max late sign in\", default=0)\n\n\nclass HrAttendanceSheet(models.Model):\n _inherit = \"hr.attendance\"\n\n def _default_employee(self):\n return self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)\n\n employee_id = fields.Many2one('hr.employee', string=\"Employee\", default=_default_employee, required=True,\n ondelete='cascade', index=True)\n department_id = fields.Many2one('hr.department', string=\"Department\", related=\"employee_id.department_id\",\n readonly=True)\n check_in = fields.Datetime(string=\"Check In\", default=fields.Datetime.now, required=True)\n check_out = fields.Datetime(string=\"Check Out\")\n worked_hours = fields.Float(string='Worked Hours', compute='_compute_worked_hours', store=True, readonly=True)\n # planned_worked_hours = fields.Float(string='Worked Hours', compute='_compute_worked_hours', store=True, readonly=True)\n state = fields.Selection(\n [('working day', 'Working day'),\n ('absent', 'Absent'),\n ('week end', 'Week End'),\n ('unpaid leave', 'Unpaid Leave'),\n ('paid leave', 'paid leave'),\n ('Public Holiday', 'Public Holiday')],\n )\n day = fields.Char()\n planned_sign_in = fields.Float()\n sign_in_limit = fields.Float()\n planned_sign_ou = fields.Float()\n late_in = fields.Float()\n # s_ov_time = fields.Float(\"Special Overtime\")\n deduct_time = fields.Float(\"Deduction (Hours)\")\n over_time = fields.Float()\n early_sign_out = fields.Float()\n note = fields.Text()\n\n @api.onchange('check_in', 'employee_id', 'check_out')\n def _set_attendance_normal_info(self):\n\n for attendance in self:\n user_pool = self.env['res.users']\n user = user_pool.browse(self.env.uid)\n tz = pytz.timezone(user.partner_id.tz) or pytz.utc\n day_int = datetime.datetime.strptime(attendance.check_in, DEFAULT_SERVER_DATETIME_FORMAT).weekday()\n contract = self.env['hr.contract'].search(\n [('employee_id', '=', attendance.employee_id.id), ('state', '=', 'open')], limit=1)\n attendance_rule = self.env[\"hr.attendance.config\"].search([], limit=1)\n if day_int < 6:\n day_no = day_int + 1\n day_str = calendar.day_name[day_int]\n elif day_int == 6:\n day_no = 0\n day_str = calendar.day_name[day_int]\n attendance.day = day_str\n counter = 0\n today_int = datetime.datetime.strptime(attendance.check_in, DEFAULT_SERVER_DATETIME_FORMAT).weekday()\n if today_int < 6:\n day_no = today_int + 1\n day_str = calendar.day_name[today_int]\n elif today_int == 6:\n day_no = 0\n check_in_time = pytz.utc.localize(\n datetime.datetime.strptime(attendance.check_in, DEFAULT_SERVER_DATETIME_FORMAT)).astimezone(tz)\n time_in = check_in_time.hour + check_in_time.minute / 60.0\n if attendance.check_out and attendance.check_in:\n check_out_time = pytz.utc.localize(\n datetime.datetime.strptime(attendance.check_out, DEFAULT_SERVER_DATETIME_FORMAT)).astimezone(tz)\n time_out = check_out_time.hour + check_out_time.minute / 60.0\n delta = datetime.datetime.strptime(attendance.check_out,\n DEFAULT_SERVER_DATETIME_FORMAT) - datetime.datetime.strptime(\n attendance.check_in, DEFAULT_SERVER_DATETIME_FORMAT)\n else:\n delta = 0\n time_out = 0\n if contract:\n if contract.resource_calendar_id:\n x = 0\n for line in contract.resource_calendar_id.attendance_ids:\n counter = counter + 1\n if int(line.dayofweek) == int(day_no):\n x = 1\n attendance.planned_sign_in = line.hour_from\n attendance.planned_sign_ou = line.hour_to\n wh = line.hour_to - line.hour_from\n # attendance.s_ov_time = 0\n attendance.sign_in_limit = line.hour_from + contract.resource_calendar_id.max_sign_in\n if time_out:\n if attendance.worked_hours > wh:\n attendance.early_sign_out = 0\n attendance.over_time += attendance.worked_hours - wh\n attendance.deduct_time = 0\n elif attendance.worked_hours < wh:\n attendance.early_sign_out = wh - attendance.worked_hours\n attendance.deduct_time = wh - attendance.worked_hours\n attendance.over_time = 0\n else:\n attendance.early_sign_out = 0\n attendance.over_time = 0\n attendance.deduct_time = 0\n else:\n attendance.early_sign_out = 0\n attendance.over_time = 0\n attendance.deduct_time = 0\n if time_in <= line.hour_from + contract.resource_calendar_id.max_sign_in:\n attendance.late_in = 0\n if attendance.worked_hours > wh:\n attendance.over_time += line.hour_from - time_in\n else:\n attendance.late_in = time_in - line.hour_from - contract.resource_calendar_id.max_sign_in\n\n # attendance.deduct_time = attendance.early_sign_out + attendance.late_in\n if not x:\n # if delta:\n # attendance.s_ov_time = delta.total_seconds() / 3600.0\n attendance.late_in = 0\n attendance.early_sign_out = 0\n attendance.over_time = 0\n attendance.deduct_time = 0\n attendance.planned_sign_in = 0\n attendance.planned_sign_ou = 0\n attendance.sign_in_limit = 0\n else:\n # attendance.s_ov_time = 0\n attendance.late_in = 0\n attendance.early_sign_out = 0\n attendance.over_time = 0\n attendance.deduct_time = 0\n attendance.planned_sign_in = 0\n attendance.planned_sign_ou = 0\n attendance.sign_in_limit = 0\n else:\n # attendance.s_ov_time = 0\n attendance.late_in = 0\n attendance.early_sign_out = 0\n attendance.over_time = 0\n attendance.deduct_time = 0\n attendance.planned_sign_in = 0\n attendance.planned_sign_ou = 0\n attendance.sign_in_limit = 0\n\n # if attendance_rule:\n # if int(line.dayofweek) == int(day_no):\n # # print(attendance_rule.f_time_from)\n # # print(time_in, \"time in\")\n # # print(attendance_rule.f_time_to)\n # # print(time_in > attendance_rule.f_time_from)\n # # print(time_in <= attendance_rule.f_time_to)\n # # print(time_in > attendance_rule.s_time_from)\n # # print(time_in <= attendance_rule.s_time_to)\n # # print(time_in > attendance_rule.s_time_to)\n # if time_in < attendance_rule.f_time_from:\n # # print(\"early come \")\n # attendance.deduct_time = 0\n # # print(attendance.deduct_time)\n # elif time_in > attendance_rule.f_time_from and time_in <= attendance_rule.f_time_to:\n # # print(\"latency phase 1 = \", time_in - attendance_rule.f_time_from)\n # attendance.late_in = time_in - attendance_rule.f_time_from\n # attendance.deduct_time = 2\n # # print(attendance.deduct_time)\n # elif time_in > attendance_rule.s_time_from and time_in <= attendance_rule.s_time_to:\n # # print(\"latency phase 2= \", time_in - attendance_rule.f_time_from)\n # attendance.late_in = time_in - attendance_rule.f_time_from\n # attendance.deduct_time = 4\n # # print(attendance.deduct_time)\n # elif time_in > attendance_rule.s_time_to:\n # # print(\"latency phase 3 \", time_in - attendance_rule.f_time_from)\n # attendance.late_in = time_in - attendance_rule.f_time_from\n # attendance.deduct_time = 8\n # # print(attendance.deduct_time)\n # else:\n # # print(\"early come \")\n # attendance.deduct_time = 0\n # # print(attendance.deduct_time)\n\n @api.depends('check_in', 'check_out')\n def _compute_worked_hours(self):\n user_pool = self.env['res.users']\n user = user_pool.browse(self.env.uid)\n tz = pytz.timezone(user.partner_id.tz) or pytz.utc\n # attendance_rule = self.env[\"hr.attendance.config\"].search([],limit=1)\n # attendance_rule =attendance_rules[0]\n # get time zone times\n\n for attendance in self:\n if attendance.check_out:\n # if attendance_rule:\n # attendance.sign_in_limit = attendance_rule.f_time_from\n\n delta = datetime.datetime.strptime(attendance.check_out,\n DEFAULT_SERVER_DATETIME_FORMAT) - datetime.datetime.strptime(\n attendance.check_in, DEFAULT_SERVER_DATETIME_FORMAT)\n # print(delta)\n\n check_out_time = pytz.utc.localize(\n datetime.datetime.strptime(attendance.check_out, DEFAULT_SERVER_DATETIME_FORMAT)).astimezone(tz)\n time_out = check_out_time.hour + check_out_time.minute / 60.0\n # print(delta.total_seconds() / 3600.0,\"total hours\")\n # print(attendance.check_out)\n # beacouse it of not using tz\n day_int = datetime.datetime.strptime(attendance.check_in, DEFAULT_SERVER_DATETIME_FORMAT).weekday()\n contract = self.env['hr.contract'].search(\n [('employee_id', '=', attendance.employee_id.id), ('state', '=', 'open')], limit=1)\n if day_int < 6:\n day_no = day_int + 1\n day_str = calendar.day_name[day_int]\n elif day_int == 6:\n day_no = 0\n day_str = calendar.day_name[day_int]\n counter = 0\n x = 0\n today_int = datetime.datetime.strptime(attendance.check_in, DEFAULT_SERVER_DATETIME_FORMAT).weekday()\n if today_int < 6:\n day_no = today_int + 1\n day_str = calendar.day_name[today_int]\n elif today_int == 6:\n day_no = 0\n if contract.resource_calendar_id:\n for line in contract.resource_calendar_id.attendance_ids:\n counter = counter + 1\n if int(line.dayofweek) == int(day_no):\n attendance.worked_hours = delta.total_seconds() / 3600.0\n x = 1\n if not x:\n attendance.worked_hours = 0\n else:\n attendance.worked_hours = delta.total_seconds() / 3600.0\n # print(attendance.worked_hours)\n contract = self.env['hr.contract'].search([('employee_id', '=', attendance.employee_id.id)], limit=1)\n # print(contract.resource_calendar_id.name)\n counter = 0\n # for line in contract.resource_calendar_id.attendance_ids:\n # if time_out > line.hour_to:\n # attendance.over_time = time_out - line.hour_to\n # attendance.early_sign_out = 0.0\n # # print(\"over time = \", time_out - line.hour_to)\n # else:\n # attendance.over_time = 0.0\n # attendance.early_sign_out = line.hour_to - time_out\n # # print(\"early sign out = \", line.hour_to - time_out)\n # break\n","repo_name":"emadraafatgad/hr_extra","sub_path":"code_sa/model/hr_attendance.py","file_name":"hr_attendance.py","file_ext":"py","file_size_in_byte":13476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"42289409910","text":"from argparse import ArgumentParser\n\nfrom .client import Client\nfrom .server import Server\n\n\nclass CommandLineInterface:\n '''\n Command Line Interface for Terminal Chat Application.\n '''\n\n def __init__(self):\n # Top level parser for client and server program.\n parser = ArgumentParser(\n prog='Terminal Chat Application',\n description=self.__doc__\n )\n \n # Subparser for client and server program.\n subparser = parser.add_subparsers(\n help='Choose a program between client and server.',\n dest='program'\n )\n\n # Server program parser.\n server_parser = subparser.add_parser(\n 'server', \n prog='Server Program',\n help='Run the program as server.'\n )\n server_parser.add_argument(\n '-p',\n '--port',\n default=1719,\n type=int,\n help='''\n Server port. Default is 1719. \n '''\n )\n server_parser.add_argument(\n '--password',\n default='top_secret',\n help='''\n Password for authorization header. \n Default is `top_secret`.\n '''\n )\n server_parser.add_argument(\n '-cdc',\n '--cryptography-digest-count',\n default=3,\n type=int,\n help='''\n Digest count for cryptography of server \n and client program. Max of 5 and min of 1.\n ''',\n dest='digest_count'\n )\n\n # Client program parser.\n client_parser = subparser.add_parser(\n 'client',\n prog='Client Program',\n help='Run the program as client.'\n )\n client_parser.add_argument(\n 'cryptography_key',\n default='ws://localhost:1719/',\n help='''\n Cryptography key for cryptography of server \n and client program.\n '''\n )\n client_parser.add_argument(\n '--url',\n default='ws://localhost:1719/',\n help='''\n URL where the client will connect. Default is \n \"ws://localhost:1719/\".\n ''',\n dest='websocket_url'\n )\n client_parser.add_argument(\n '--username',\n default='',\n help='''\n Username for username header of client. If you don't \n use this optional arg, the Client Program will create \n its own username. Starting with user then number. \n Example: \"user_1234\".\n '''\n )\n client_parser.add_argument(\n '--password',\n default='top_secret',\n help='''\n Password for authorization header. \n Default is `top_secret`.\n '''\n )\n client_parser.add_argument(\n '-cdc',\n '--cryptography-digest-count',\n default=3,\n type=int,\n help='''\n Digest count for cryptography of server \n and client program. Max of 5 and min of 1.\n ''',\n dest='digest_count'\n )\n \n self.args = parser.parse_args()\n \n # Validates if digest count for cryptography\n # is in between 1-5. If not raise\n # `parser.error()`.\n if not self.args.digest_count in range(1, 6):\n # Chooce which parser to use. If client\n # or server program.\n error_info = f'Invalid digest count for cryptography. It should be in between of 1-5 but got \"{self.args.digest_count}\".'\n if self.args.program == 'server':\n raise server_parser.error(error_info)\n raise client_parser.error(error_info)\n \n \n def run(self):\n '''\n Runs the program.\n '''\n try:\n # Run the program as server\n if self.args.program == 'server':\n server = Server(\n port=self.args.port, \n password=self.args.password,\n cryptography_digest_count=self.args.digest_count\n )\n server.run()\n\n # Run the program as client\n elif self.args.program == 'client':\n client = Client(\n cryptography_key=self.args.cryptography_key,\n cryptography_digest_count=self.args.digest_count,\n url=self.args.websocket_url,\n username=self.args.username,\n password=self.args.password\n )\n \n client.run()\n except KeyboardInterrupt:\n if self.args.program == 'server':\n print('\\nServer has been stopped.')\n elif self.args.program == 'client':\n if client._successfully_connected:\n print(f'\\nDisconnected to the `{client.url}` server.')","repo_name":"markcarcillar/terminal_chatapp","sub_path":"terminal_chatapp/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":5011,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"36404986661","text":"\n#number guesssing game:\nimport random\n\ndef number_guessing_game():\n secret_number=random.randint(1,1000)\n attempts=0\n\n while True:\n guess=int(input(\"Guess the number from 1 to 1000:\"))\n attempts+=1\n \n if guess==secret_number:\n print(\"congrats you won it\")\n\n elif guess 0:\n n, remainder = divmod(n - 1, 26)\n string = chr(65 + remainder) + string\n return string\n\ndef excelRange(bag):\n xvalues = []\n yvalues = []\n for cell in bag:\n coordinate = cellLoc(cell)\n xvalues.append(''.join([i for i in coordinate if not i.isdigit()]))\n yvalues.append(int(''.join([i for i in coordinate if i.isdigit()])))\n high = 0\n low = 0\n for i in xvalues:\n if col2num(i) >= high:\n high = col2num(i)\n if low == 0:\n low = col2num(i)\n elif col2num(i) < low:\n low = col2num(i)\n highx = colnum_string(high)\n lowx = colnum_string(low)\n highy = str(max(yvalues))\n lowy = str(min(yvalues))\n\n return '{' + lowx + lowy + '-' + highx + highy + '}'\n\n\n# %%\n\n\ndf = pd.DataFrame()\ntrace = TransformTrace()\n\n\n# %%\n\n\"\"\"\nfrom urllib.request import Request, urlopen\n\ndef all_same(items):\n if len(items) == 0:\n return False\n return all(x == items[0] for x in items)\n\nreq = Request(\"https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/articles/whichoccupationshavethehighestpotentialexposuretothecoronaviruscovid19/2020-05-11\", headers={'User-Agent': 'Mozilla/5.0'})\nhtml = urlopen(req).read()\nplaintext = html.decode('utf8')\nlinks = re.findall(\"href=[\\\"\\'](.*?)[\\\"\\']\", plaintext)\nlinks = [x for x in links if x.endswith(\"xls\")]\nif all_same(links) == True:\n dataURL = links[0]\n with open('info.json', 'r+') as info:\n data = json.load(info)\n data[\"dataURL\"] = dataURL\n info.seek(0)\n json.dump(data, info, indent=4)\n info.truncate()\nelse:\n print(\"Multiple or No files found, investigate or retrieve manually\")\n for i in links:\n print(i)\n\n\"\"\"\n# %%\n\n\nscrape = Scraper(seed = 'info.json')\nscrape.distributions[0].title = \"Which occupations have the highest potential exposure to the coronavirus (COVID-19)?\"\nscrape\n\ntabs = { tab.name: tab for tab in scrape.distributions[0].as_databaker() }\nlist(tabs)\n\n# ##### Sheet: Occupations and exposure\n\n\n# %%\n\n\ntab = tabs['Occupations and exposure']\ndatacube_name = \"Which occupations have the highest potential exposure to the coronavirus (COVID-19)?\"\ncolumns=['Measure type', 'UK SOC 2010 Code', 'Occupation title', 'Total in employment', 'Median hourly pay', 'Percentage of the workforce that are female', 'Percentage of the workforce that are aged 55 plus', 'Percentage of the workforce that are BAME', 'Unit']\ntrace.start(datacube_name, tab, columns, scrape.distributions[0].downloadURL)\n\ncell = tab.filter(contains_string('Occupations and exposure to disease data'))\ncell.assert_one()\n\nsoc_codes = cell.shift(0,3).expand(DOWN).is_not_blank()\ntrace.UK_SOC_2010_Code('UK SOC 2010 Code given at cell range: {}', var = excelRange(soc_codes))\n\noccupation_title = cell.shift(1,3).expand(DOWN).is_not_blank()\ntrace.Occupation_title('Occupation title given at cell range: {}', var = excelRange(occupation_title))\n\nmeasure_type = cell.shift(2,2).expand(RIGHT).is_not_blank() - cell.shift(4,2).expand(RIGHT)\ntrace.Measure_type('Measure type given at cell range: {}', var = excelRange(measure_type))\n\n#attributes\ntotal_employment = cell.shift(4,3).expand(DOWN).is_not_blank()\ntrace.Total_in_employment('Total in employment given at cell range: {}', var = excelRange(total_employment))\n\nmedian_hourly_pay = cell.shift(5,3).expand(DOWN).is_not_blank()\ntrace.Median_hourly_pay('Median hourly pay (£) given at cell range: {}', var = excelRange(median_hourly_pay))\n\nworkforce_female = cell.shift(6,3).expand(DOWN).is_not_blank()\ntrace.Percentage_of_the_workforce_that_are_female('Percentage of the workforce that are female given at cell range: {}', var = excelRange(workforce_female))\n\nworkforce_55_plus = cell.shift(7,3).expand(DOWN).is_not_blank()\ntrace.Percentage_of_the_workforce_that_are_aged_55_plus('Percentage of the workforce that are aged 55+ given at cell range: {}', var = excelRange(workforce_55_plus))\n\nworkforce_bame = cell.shift(8,3).expand(DOWN).is_not_blank()\ntrace.Percentage_of_the_workforce_that_are_BAME('Percentage of the workforce that are BAME given at cell range: {}', var = excelRange(workforce_bame))\n\nunit = 'Standardised Scale'\ntrace.Unit('Hardcoded as : standardised to a scale')\ntrace.Unit(\"Information regarding The standardised exposure to disease / infections measure found here: https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/articles/whichoccupationshavethehighestpotentialexposuretothecoronaviruscovid19/2020-05-11 \")\n\nobservations = measure_type.fill(DOWN).is_not_blank()\n\ndimensions = [\n HDim(soc_codes, 'Occupation', DIRECTLY, LEFT),\n HDim(occupation_title, 'Occupation title', DIRECTLY, LEFT),\n HDim(measure_type, 'Measure type', DIRECTLY, ABOVE),\n HDim(measure_type, 'Working Condition Category', DIRECTLY, ABOVE),\n HDim(total_employment, 'Total in employment', DIRECTLY, RIGHT),\n HDim(median_hourly_pay, 'Median hourly pay', DIRECTLY, RIGHT),\n HDim(workforce_female, 'Percentage Workforce Female', DIRECTLY, RIGHT),\n HDim(workforce_55_plus, 'Percentage Workforce Aged 55plus', DIRECTLY, RIGHT),\n HDim(workforce_bame, 'Percentage Workforce BAME', DIRECTLY, RIGHT),\n HDimConst('Unit', unit),\n]\ntidy_sheet = ConversionSegment(tab, dimensions, observations)\ntrace.with_preview(tidy_sheet)\n#savepreviewhtml(tidy_sheet)\ntrace.store(\"combined_dataframe\", tidy_sheet.topandas())\n\ndf = trace.combine_and_trace(datacube_name, \"combined_dataframe\")\ntrace.add_column(\"Value\")\ntrace.multi([ \"Value\"], \"Rename databaker columns OBS to Value\")\ndf.rename(columns={'OBS' : 'Value'}, inplace=True)\ndf[\"Occupation\"] = pd.to_numeric(df[\"Occupation\"])\ndf[\"Occupation\"] = df[\"Occupation\"].astype(int)\ndf = df.replace({'Measure type' : {'Proximity to others' : 'Proximity', 'Exposure to disease' : 'Exposure'}})\n# -\n\nfrom IPython.core.display import HTML\nfor col in df:\n if col not in ['Value']:\n df[col] = df[col].astype('category')\n display(HTML(f\"

{col}

\"))\n display(df[col].cat.categories)\n\n\n# %%\n#tidy = df[['UK SOC 2010 Code', 'Occupation','Total in employment', 'Median hourly pay', 'Percentage Workforce Female', 'Percentage Workforce Aged 55plus', 'Percentage Workforce BAME', 'Working Condition Category', 'Measure type', 'Unit', 'Value']]\ntidy = df[['Occupation', 'Working Condition Category', 'Measure type', 'Unit', 'Value']]\n\ntrace.Occupation_title(\"Remove any prefixed whitespace from all values in column and pathify\")\nfor column in tidy:\n if column in ('Working Condition Category'):\n tidy[column] = tidy[column].str.lstrip()\n tidy[column] = tidy[column].str.rstrip()\n tidy[column] = tidy[column].map(lambda x: pathify(x))\n\n\n# %%\n\n\n\n# ________________________________________________________________________\n# REMOVING OBS WITH MEASURETYPE \"PROXIMITY TO OTHERS\" FOR NOW DUE TO NOT CURRENTLY BEING ABLE TO HANDEL MULTPLE MEASURE TYPES. WILL NEED TO BE ADDED BACK IN.\n# _________________________________________________________________________\n\ndf.drop(df[df['Measure type'] == 'Proximity'].index, inplace=True)\n\n\n# _______________________________________________________________________________________________________________\n\n#Removing columns as they are defined in info.json\ndel tidy['Measure type']\ndel tidy['Unit']\n\nnotes = \"\"\"Some occupations are excluded due to no exposure and/or proximity measures being available\nPlease note the exposure to disease and proximity to others data was calculated by O*NET prior to the coronavirus (COVID-19) outbreak, therefore will not reflect any changes to working practices implemented since the outbreak.\nThe BAME group includes: Mixed/Multiple ethnic groups; Indian; Pakistani; Bangladeshi; Chinese; any other Asian background; Black/African/Caribbean/Black British\nThis measure of pay comes from the Annual Survey of Hours and Earnings (ASHE). It is hourly earnings excluding overtime. It's calculated as (gross pay excluding overtime/basic paid hours). The pay period in question was not affected by absence. It includes people aged 16+ both full-time and part-time.\nFor the percentage of women in each occupation, figures have been grouped together for percentages greater than 95% for disclosure reasons\n\nplease follow link for more information on how The standardised exposure to disease or infections measure is defined:\nhttps://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/articles/whichoccupationshavethehighestpotentialexposuretothecoronaviruscovid19/2020-05-11\n\"\"\"\n\n\n# %%\n\n\n#SET UP OUTPUT FOLDER AND OUTPUT DATA TO CSV\ncsvName = 'observations.csv'\nout = Path('out')\nout.mkdir(exist_ok=True)\ntidy.drop_duplicates().to_csv(out / csvName, index = False)\nscrape.dataset.family = 'covid-19'\nscrape.dataset.description = scrape.dataset.description + '\\n ' + notes\nscrape.dataset.comment = 'ONS has created an estimate of exposure to generic disease, and physical proximity to others, for UK occupations based on US analysis of these factors.'\n\n# CREATE MAPPING CLASS INSTANCE, SET UP VARIABLES AND WRITE FILES\ncsvw_transform = CSVWMapping()\ncsvw_transform.set_csv(out / csvName)\ncsvw_transform.set_mapping(json.load(open('info.json')))\ncsvw_transform.set_dataset_uri(urljoin(scrape._base_uri, f'data/{scrape._dataset_id}'))\ncsvw_transform.write(out / f'{csvName}-metadata.json')\n#\n\n\n# %%\n\n\n# CREATE AND OUTPUT TRIG FILE\nwith open(out / f'{csvName}-metadata.trig', 'wb') as metadata:\n metadata.write(scrape.generate_trig())\n\ntrace.output()\n#tidy\n\n\n# %%\n\n\n#info = json.load(open('info.json'))\n#codelistcreation = info['transform']['codelists']\n#print(codelistcreation)\n#print(\"-------------------------------------------------------\")\n\n#codeclass = CSVCodelists()\n#for cl in codelistcreation:\n# if cl in tidy.columns:\n# tidy[cl] = tidy[cl].str.replace(\"-\",\" \")\n# tidy[cl] = tidy[cl].str.capitalize()\n# codeclass.create_codelists(pd.DataFrame(tidy[cl]), 'codelists', 'covid-19', Path(os.getcwd()).name.lower())\n\n\n# %%\n\n\n\n\n\n# Notes taken from Tables / https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/articles/whichoccupationshavethehighestpotentialexposuretothecoronaviruscovid19/2020-05-11\n\n\n\n# #### Sheet : Total workforce data\n#\n# COMMENTED OUT FOR NOW, ONLY 3 OBSERVATIONS AND THEY ARE DERRIABLE FROM SHEET ABOVE\n\n# tab = tabs['Total_workforce_population']\n# datacube_name = \"Which occupations have the highest potential exposure to the coronavirus (COVID-19)?\"\n# columns=['Occupation title', 'Workforce category', 'Unit', 'Measure type']\n# trace.start(datacube_name, tab, columns, scrape.distributions[0].downloadURL)\n#\n# cell = tab.filter(contains_string('Total workforce population'))\n# cell.assert_one()\n#\n# workforce_cat = cell.shift(1,-1).expand(RIGHT).is_not_blank()\n# trace.Workforce_category('Workforce category given at cell range: {}', var = excelRange(workforce_cat))\n#\n# unit = 'Percent'\n# trace.Unit('Hardcoded as : Percent')\n# measure_type = 'Percentage'\n# trace.Unit('Hardcoded as : Percentage')\n#\n# observations = workforce_cat.fill(DOWN).is_not_blank()\n# dimensions = [\n# HDim(workforce_cat, 'Workforce Category', DIRECTLY, ABOVE),\n# HDimConst('Measure type', measure_type),\n# HDimConst('Unit', unit),\n# ]\n# tidy_sheet = ConversionSegment(tab, dimensions, observations)\n# trace.with_preview(tidy_sheet)\n# #savepreviewhtml(tidy_sheet)\n# trace.store(\"combined_dataframe_2\", tidy_sheet.topandas())\n#\n# df = trace.combine_and_trace(datacube_name, \"combined_dataframe_2\")\n# trace.add_column(\"Value\")\n# trace.multi([ \"Value\"], \"Rename databaker columns OBS to Value\")\n# df.rename(columns={'OBS' : 'Value'}, inplace=True)\n# df = df.replace({'Workforce Category' : {'Percentage of the workforce that are female(%)' : 'Females',\n# 'Percentage of the workforce that are BAME (%)' : 'BAME',\n# 'Percentage of the workforce that are aged 55+ (%)': 'Aged 55plus'}})\n#\n#\n# tidy = df[['Workforce Category', 'Measure type', 'Unit', 'Value']]\n\n\n\n# %%\n\n# %%\n","repo_name":"GSS-Cogs/family-covid-19","sub_path":"datasets/ONS-Which-occupations-have-the-highest-potential-exposure-to-the-coronavirus-COVID-19/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"24166815344","text":"#\n# @lc app=leetcode id=35 lang=python3\n#\n# [35] Search Insert Position\n#\n\n# @lc code=start\nclass Solution:\n def searchInsert(self, nums: List[int], target: int) -> int:\n\n if len(nums) <= 2 and target not in nums:\n if len(nums) == 1:\n if nums[0] > target: return 0\n else: return 1\n\n elif len(nums) == 2:\n if nums[0] > target:\n return 0\n elif nums[0] < target <= nums[1]:\n return 1\n else: return 2\n\n else: return 0\n\n\n\n middle = len(nums)//2\n if nums[middle] == target:\n return middle\n elif nums[middle] < target:\n relative_idx = self.searchInsert(nums[middle:], target)\n middle + relative_idx\n else:\n relative_idx = self.searchInsert(nums[:middle], target)\n return relative_idx\n\n# @lc code=end\n\n","repo_name":"sushantjha78/DSA-problem-solving","sub_path":"Leetcode/35.search-insert-position.py","file_name":"35.search-insert-position.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"30147651236","text":"from model import Card, Deck\nfrom logger import *\nimport itertools\nimport time\nimport copy\n\ndef is_set(a, b, c):\n if a.third(b) == c:\n log(\"Cards are a set!\")\n return True\n else:\n log(\"Cards are not a set: needed %s, gave %s\", a.third(b), c)\n return False\n\nclass Game:\n\n BOARD_SHAPE = (3, 4)\n\n MAX_CARDS = 18\n MAX_NORMAL = BOARD_SHAPE[0] * BOARD_SHAPE[1]\n\n DELAY=.1\n\n SET_TIMEOUT = 5\n\n SESSION_CALLS = ('remove', 'select', 'deselect', 'place', 'set_yelled', 'score_update',\n 'set_stolen', 'too_late', 'end_game', 'resume', 'more_requested')\n\n def __init__(self, session):\n self.deck = Deck()\n self.deck.shuffle()\n self.layout = dict()\n self.selected = dict()\n\n self.requests = {}\n self.session = session\n self.scores = { client.id : 0 for client in self.session.clients }\n self.current_yeller = None\n self.reset_requests()\n\n def has_set(self):\n for c1, c2, c3 in itertools.combinations(self.layout.values(), 3):\n if c1.third(c2) == c3:\n return True\n return False\n\n def reset_requests(self):\n for id in self.session.client_ids():\n self.requests[id] = False\n\n @classmethod\n def iterxy(cls):\n for y in range(cls.BOARD_SHAPE[1]):\n for x in range(cls.BOARD_SHAPE[0]):\n yield x,y\n for ex_x in range(3):\n yield cls.BOARD_SHAPE[0], ex_x\n for ex_x in range(3):\n yield cls.BOARD_SHAPE[0] + 1, ex_x\n\n\n def request_more(self, client):\n self.requests[client.id] = True\n num_requested = len([r for r in self.requests.values() if r])\n self.session.more_requested(client.id, num_requested, len(self.requests))\n if all(self.requests.values()):\n self.place_three()\n self.reset_requests()\n\n def yell_set(self, client):\n if self.current_yeller is None:\n self.session.set_yelled(client.id)\n self.current_yeller = (client, time.time() + self.SET_TIMEOUT)\n self.requests[client.id] = False\n else:\n yeller, timeout = self.current_yeller\n if self.current_yeller != client:\n if time.time() > timeout:\n self.deselect_all()\n self.scores[yeller.id] -= 1\n self.session.score_update(self.scores)\n self.session.set_stolen(client.id)\n self.current_yeller = (client, time.time() + self.TIMEOUT)\n self.requests[client.id] = False\n else:\n self.session.too_late(client.id, int(timeout - time.time()))\n\n def deselect_all(self):\n selected = copy.deepcopy(self.selected)\n for (x,y), card in selected.items():\n self.deselect_card(card, x, y)\n self.selected.clear()\n\n\n def cards_remain(self):\n return self.deck.cards_remaining() > 0\n\n def next_spot(self):\n for x, y in self.iterxy():\n if self.card_at(x, y) is None:\n return x, y\n return None, None\n\n def card_at(self, x, y):\n return self.layout.get((x,y), None)\n\n def valid_card(self, card, x, y):\n card_at = self.card_at(x, y)\n if not card_at == card:\n log_warn(\"Card at %d %d is %s, not %s\", x, y, card_at, card)\n return False\n return True\n\n def remove_card(self, card, x, y):\n if not self.valid_card(card, x, y):\n log_warn(\"Cannot remove card\")\n return\n\n self.session.remove(card.properties, x, y)\n if (x, y) in self.selected:\n del self.selected[(x, y)]\n del self.layout[(x,y)]\n\n def select_card(self, card, x, y):\n if not self.valid_card(card, x, y):\n log_warn(\"Cannot select card\")\n return\n self.session.select(card.properties, x, y)\n self.selected[(x,y)] = card\n\n def check_set(self, client):\n if len(self.selected) == 3 and is_set(*self.selected.values()):\n self.scores[client.id] += 1\n self.session.score_update(self.scores)\n selected = copy.deepcopy(self.selected)\n for (x,y), card in selected.items():\n self.remove_card(card, x, y)\n self.selected.clear()\n self.fill_board()\n self.reorganize()\n log(\"{} cards remaining\".format(self.deck.cards_remaining()))\n log(\"Set present? {}\".format(self.has_set()))\n if self.deck.cards_remaining() == 0 and not self.has_set():\n self.session.end_game(self.scores)\n return True\n else:\n log(\"%d cards selected : not a set\", len(self.selected))\n self.scores[client.id] -= 1\n self.session.score_update(self.scores)\n self.selected.clear()\n self.current_yeller = None\n self.session.resume()\n\n def place_three(self):\n for _ in range(3):\n self.place_next()\n\n def deselect_card(self, card, x, y):\n if not self.valid_card(card, x, y):\n log_warn(\"Cannot deselect card\")\n return\n if not (x,y) in self.selected:\n log_warn(\"Deselecting non-selected card\")\n else:\n del self.selected[(x,y)]\n self.session.deselect(card.properties, x, y)\n\n def place_card(self, card):\n if len(self.layout) == self.MAX_CARDS:\n log_warn(\"Attempted to place more than MAX_CARDS\")\n return\n x, y = self.next_spot()\n if x is None:\n log_error(\"MAX_CARDS not placed but no next_spot available\")\n return\n self.layout[(x,y)] = card\n self.session.place(card.properties, x, y)\n #time.sleep(self.DELAY)\n\n def place_next(self):\n if len(self.layout) == self.MAX_CARDS:\n log_warn(\"Cannot place more than %d cards\", self.MAX_CARDS)\n return\n card = self.deck.draw()\n self.place_card(card)\n\n def fill_board(self):\n while self.cards_remain() and len(self.layout) < self.MAX_NORMAL:\n self.place_next()\n\n def iloc(self, i):\n for idx, (x,y) in enumerate(self.iterxy()):\n if idx == i:\n return x, y, self.card_at(x,y)\n\n def reorganize(self):\n for i in range(self.MAX_CARDS)[::-1]:\n if i < self.MAX_NORMAL:\n return\n x, y, c = self.iloc(i)\n if c is None:\n continue\n else:\n log(\"Reorganizing card %d\", i)\n self.remove_card(c, x, y)\n self.place_card(c)\n updated = True\n\n def disconnect(self, client):\n self.session.end_game(self.scores, \"Player {} exited early -- \".format(client.id))\n return True\n","repo_name":"isaac-ped/53T","sub_path":"host.py","file_name":"host.py","file_ext":"py","file_size_in_byte":6887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"71369212896","text":"# python 有一类本身就包含数据的被称为容器(container)的数据类型,例如list,dictionary\n# 如果直接标注变量类型为 list 等,会造成信息不足\n\ndef my_sum1(lst: list) -> int:\n total = 0\n for i in lst:\n total += i\n return total \n\nmy_sum1([0,1,2])\nmy_sum1([0,1,\"2\"])\n\n# python-3.9 之后可以\ndef my_sum2(lst: list[int]) -> int:\n total = 0\n for i in lst:\n total += i\n return total \n\nmy_sum2([0,1,2])\nmy_sum2([0,1,\"2\"])\n\n# python-3.9 之前\nfrom typing import List\n\ndef my_sum3(lst: List[int]) -> int:\n total = 0\n for i in lst:\n total += i\n return total \n\nmy_sum3([0,1,2])\nmy_sum3([0,1,\"2\"])\n","repo_name":"oneLuckyman/learn_python","sub_path":"Type_Hint/type_hint_3.py","file_name":"type_hint_3.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"7939648584","text":"\n\ndef user_input():\n game_range=[1,2,3,4,5,6,7,8,9]\n choice=0\n while(choice==0):\n choice=input(\"Enter your choice from 1-10: \")\n choice=int(choice)\n if choice not in game_range:\n print(\"Not in range\")\n choice= 0\n return choice\n\n\n\ndef marker_assign():\n p1=''\n while p1 !='X' and p1 != 'O':\n p1=input(\"Player 1, are you X/O: \")\n if p1=='X':\n p2='O'\n else:\n p2='X'\n print(f\"Player 1: {p1} and Player 2: {p2}\")\n return (p1,p2)\n\n\nrow1=[' ',' ',' ']\nrow2=[' ',' ',' ']\nrow3=[' ',' ',' ']\n\n\n\ndef display_board(): \n print(row1[0]+'|'+row1[1]+'|'+row1[2])\n print(\"__ __\")\n print(row2[0]+'|'+row2[1]+'|'+row2[2])\n print(\"__ __\")\n print(row3[0]+'|'+row3[1]+'|'+row3[2])\n print(\"__ __\")\n\n\ndisplay_board()\np1,p2=marker_assign()\nct=1\nstat='con'\nwhile stat=='con':\n if row1[0]==row1[1]==row1[2]=='X' or row2[0]==row2[1]==row2[2]=='X' or row3[0]==row3[1]==row3[2]=='X' or row1[0]==row2[1]==row3[2]=='X' or row1[2]==row2[1]==row3[0]=='X'or row1[0]==row1[1]==row1[2]=='O' or row2[0]==row2[1]==row2[2]=='O' or row3[0]==row3[1]==row3[2]=='O' or row1[0]==row2[1]==row3[2]=='O' or row1[2]==row2[1]==row3[0]=='O'or row1[0]==row2[0]==row3[0]=='X' or row1[1]==row2[1]==row3[1]=='X' or row1[2]==row2[2]==row3[2]=='X' or row1[0]==row2[0]==row3[0]=='O' or row1[0]==row2[0]==row3[0]=='O' or row1[0]==row2[0]==row3[0]=='O' or ct==10 :\n stat='brek'\n elif ct%2 !=0:\n print('Player 1, Your chance now!')\n choice=user_input()\n choice=choice\n if choice in range(1,4):\n row1[choice-1]=p1\n elif choice in range(4,7):\n row2[choice-4]=p1\n else:\n row3[choice-7]=p1\n ct=ct+1\n display_board()\n else:\n print('Player 2, Your chance now!')\n choice=user_input()\n choice=choice\n if choice in range(1,4):\n row1[choice-1]=p2\n elif choice in range(4,7):\n row2[choice-4]=p2\n else:\n row3[choice-7]=p2\n ct=ct+1\n display_board()\n \nprint(ct)\nif ct !=10:\n if ct%2==0:\n print(\"Congrats, Player 1 has won,\\n Player 2 better luck next time\")\n else:\n print(\"Congrats, Player 2 has won,\\n Player 1 better luck next time\")\nelif ct==10:\n print(\"This game is a draw!!\")\n\n\n\n\n\n \n\n \n \n \n \n\n","repo_name":"Elizabeth-Mathew1/Python_all","sub_path":"TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"6186330891","text":"import re, abc, sys\nfrom .constraints import Constraints\n\ndef _removeEmptyConstraints (problem, constraints):\n return [ n for n in constraints if problem.getConstraintDimensions(n)[2] > 0 ]\n\nclass Rules(object):\n def __init__ (self, grippers, handles, rules):\n rs = []\n status = []\n for r in rules:\n # replace empty strings by the corresponding regexp \"^$\", otherwise \"\" matches with all strings.\n for i in range(len(r.grippers)):\n if r.grippers[i] == \"\": r.grippers[i] = \"^$\"\n for i in range(len(r.handles)):\n if r.handles[i] == \"\": r.handles[i] = \"^$\"\n handlesRegex = [ None ] * len(grippers)\n for j, gr in enumerate (r.grippers):\n grc = re.compile (gr)\n for i, g in enumerate (grippers):\n if grc.match (g):\n assert handlesRegex[i] is None\n handlesRegex[i] = re.compile(r.handles[j])\n status.append(r.link)\n\n rs.append (tuple(handlesRegex))\n self.rules = tuple(rs)\n self.status = tuple(status)\n self.handles = tuple(handles)\n self.defaultAcceptation = False\n\n def __call__ (self, grasps):\n for r, s in zip(self.rules, self.status):\n apply = True\n for i, h in enumerate(r):\n if h is not None and not h.match(\"\" if grasps[i] is None else self.handles[grasps[i]]):\n # This rule does not apply\n apply = False\n break\n if apply: return s\n return self.defaultAcceptation\n\nif sys.version_info.major == 2:\n class ABC:\n \"\"\" Python 2.7 equivalent to abc.ABC Python 3 class.\"\"\"\n __metaclass__ = abc.ABCMeta\nelse:\n from abc import ABC\n\n## An abstract class which is loops over the different (gripper, handle) associations.\n#\n# The behaviour can be tuned by setting the callback functions:\n# - \\ref graspIsAllowed (redundant with \\ref setRules)\n# - \\ref constraint_graph_factory_algo_callbacks \"Algorithm steps\"\nclass GraphFactoryAbstract(ABC):\n def __init__(self):\n\n ## Reduces the problem combinatorial.\n # Function called to check whether a grasps is allowed.\n # It takes as input a list of handle indices (or None) such\n # that i-th \\ref grippers grasps `grasps[i]`-th \\ref handles.\n # It must return a boolean\n #\n # It defaults to: \\code lambda x : True\n self.graspIsAllowed = lambda x : True\n\n ## \\name Internal variables\n # \\{\n\n self.states = dict()\n self.transitions = set()\n ## the handle names\n self.handles = tuple() # strings\n ## the gripper names\n self.grippers = tuple() # strings\n ## the names of contact on the environment\n self.envContacts = tuple () # strings\n ## the object names\n self.objects = tuple () # strings\n ## See \\ref setObjects\n self.handlesPerObjects = tuple () # object index to handle indixes\n ## See \\ref setObjects\n self.objectFromHandle = tuple () # handle index to object index\n ## See \\ref setObjects\n self.contactsPerObjects = tuple ()# object index to contact names\n ## \\}\n\n ## \\name Main API\n # \\{\n\n ## \\param grippers list of gripper names to be considered\n def setGrippers(self, grippers):\n assert isinstance (grippers, (list, tuple))\n self.grippers = tuple(grippers)\n\n ## \\param objects list of object names to be considered\n ## \\param handlesPerObjects a list of list of handle names.\n ## \\param contactsPerObjects a list of list of contact names.\n ## handlesPerObjects and contactsPerObjects must have one list for each object, in the same order.\n def setObjects(self, objects, handlesPerObjects, contactsPerObjects):\n self.objects = tuple(objects)\n handles = []\n hpo = []\n cpo = []\n ofh = []\n for io, o in enumerate (self.objects):\n hpo.append( tuple(range(len(handles), len(handles) + len(handlesPerObjects[io])) ) )\n handles.extend(handlesPerObjects[io])\n ofh.extend( [ io, ] * len(handlesPerObjects[io]) )\n cpo.append( tuple(contactsPerObjects[io]) )\n\n self.handles = tuple(handles)\n self.handlesPerObjects = tuple(hpo)\n self.objectFromHandle = tuple(ofh)\n self.contactsPerObjects = tuple(cpo)\n\n ## \\param envContacts contact on the environment to be considered.\n def environmentContacts (self, envContacts):\n self.envContacts = tuple(envContacts)\n\n ## Set the function \\ref graspIsAllowed\n ## \\param rules a list of Rule objects\n def setRules (self, rules):\n self.graspIsAllowed = Rules(self.grippers, self.handles, rules)\n\n ## Go through the combinatorial defined by the grippers and handles\n # and create the states and transitions.\n def generate(self):\n grasps = ( None, ) * len(self.grippers)\n self._recurse(self.grippers, self.handles, grasps, 0)\n\n ## \\}\n\n ## \\name Abstract methods of the algorithm\n # \\anchor constraint_graph_factory_algo_callbacks\n # \\{\n\n ## Create a new state.\n # \\param grasps a handle index for each gripper, as in GraphFactoryAbstract.graspIsAllowed.\n # \\param priority the state priority.\n # \\return an object representing the state.\n @abc.abstractmethod\n def makeState(self, grasps, priority): return grasps\n\n ## Create a loop transition.\n # \\param state: an object returned by \\ref makeState which represent the state\n @abc.abstractmethod\n def makeLoopTransition(self, state): pass\n\n ## Create two transitions between two different states.\n # \\param stateFrom: same as grasps in \\ref makeState\n # \\param stateTo: same as grasps in \\ref makeState\n # \\param ig: index if the grasp vector that changes, i.e. such that\n # - \\f$ stateFrom.grasps[i_g] \\neq stateTo.grasps[i_g] \\f$\n # - \\f$ \\forall i \\neq i_g, stateFrom.grasps[i] = stateTo.grasps[i] \\f$\n @abc.abstractmethod\n def makeTransition(self, stateFrom, stateTo, ig): pass\n\n ## \\}\n\n def _makeState(self, grasps, priority):\n if grasps not in self.states:\n state = self.makeState (grasps, priority)\n self.states[grasps] = state\n\n # Create loop transition\n self.makeLoopTransition (state)\n else:\n state = self.states [grasps]\n return state\n\n def _isObjectGrasped(self, grasps, object):\n for h in self.handlesPerObjects[object]:\n if h in grasps:\n return True\n return False\n\n def _stateName (self, grasps, abbrev = False):\n sepGH = \"-\" if abbrev else \" grasps \"\n sep = \":\" if abbrev else \" : \"\n name = sep.join([ (str(ig) if abbrev else self.grippers[ig]) + sepGH + (str(ih) if abbrev else self.handles[ih]) for ig,ih in enumerate(grasps) if ih is not None ])\n if len(name) == 0: return \"f\" if abbrev else \"free\"\n return name\n\n def _transitionNames (self, sFrom, sTo, ig):\n g = self.grippers[ig]\n h = self.handles[sTo.grasps[ig]]\n sep = \" | \"\n return (g + \" > \" + h + sep + self._stateName(sFrom.grasps, True),\n g + \" < \" + h + sep + self._stateName(sTo.grasps, True),)\n\n def _loopTransitionName (self, grasps):\n return \"Loop | \" + self._stateName(grasps, True)\n\n def _recurse(self, grippers, handles, grasps, depth):\n isAllowed = self.graspIsAllowed (grasps)\n if isAllowed: current = self._makeState (grasps, depth)\n\n if len(grippers) == 0 or len(handles) == 0: return\n for ig, g in enumerate(grippers):\n ngrippers = grippers[:ig] + grippers[ig+1:]\n\n isg = self.grippers.index(g)\n for ih, h in enumerate(handles):\n nhandles = handles[:ih] + handles[ih+1:]\n\n ish = self.handles.index(h)\n nGrasps = grasps[:isg] + (ish, ) + grasps[isg+1:]\n\n nextIsAllowed = self.graspIsAllowed (nGrasps)\n if nextIsAllowed: next = self._makeState (nGrasps, depth + 1)\n\n if isAllowed and nextIsAllowed:\n self.makeTransition (current, next, isg)\n\n self._recurse (ngrippers, nhandles, nGrasps, depth + 2)\n\n## An abstract class which stores the constraints.\n#\n# Child classes are responsible for building them.\n# - \\ref buildGrasp\n# - \\ref buildPlacement\nclass ConstraintFactoryAbstract(ABC):\n def __init__(self, graphfactory):\n self._grasp = dict()\n self._placement = dict()\n\n self.graphfactory = graphfactory\n\n ## \\name Accessors to the different elementary constraints\n # \\{\n def getGrasp(self, gripper, handle):\n if isinstance(gripper, str): ig = self.graphfactory.grippers.index(gripper)\n else: ig = gripper\n if isinstance(handle, str): ih = self.graphfactory.handles.index(handle)\n else: ih = handle\n k = (ig, ih)\n if k not in self._grasp:\n self._grasp[k] = self.buildGrasp(self.graphfactory.grippers[ig], None if ih is None else self.graphfactory.handles[ih])\n assert isinstance (self._grasp[k], dict)\n return self._grasp[k]\n\n def g (self, gripper, handle, what):\n return self.getGrasp(gripper, handle)[what]\n\n def getPlacement(self, object):\n if isinstance(object, str): io = self.graphfactory.objects.index(object)\n else: io = object\n k = io\n if k not in self._placement:\n self._placement[k] = self.buildPlacement(self.graphfactory.objects[io])\n return self._placement[k]\n\n def p (self, object, what):\n return self.getPlacement(object)[what]\n ## \\}\n\n ## Function called to create grasp constraints.\n # Must return a tuple of Constraints objects as:\n # - constraint that validates the grasp\n # - constraint that parameterizes the graph\n # - constraint that validates the pre-grasp\n # \\param g gripper string\n # \\param h handle string\n @abc.abstractmethod\n def buildGrasp (self, g, h):\n return (None, None, None,)\n\n ## Function called to create placement constraints.\n # Must return a tuple of Constraints objects as:\n # - constraint that validates placement\n # - constraint that parameterizes placement\n # - constraint that validates pre-placement\n # \\param o string\n @abc.abstractmethod\n def buildPlacement (self, o):\n return (None, None, None,)\n\n## Default implementation of ConstraintFactoryAbstract\nclass ConstraintFactory(ConstraintFactoryAbstract):\n gfields = ('grasp', 'graspComplement', 'preGrasp')\n pfields = ('placement', 'placementComplement', 'prePlacement')\n\n def __init__ (self, graphfactory, graph):\n super (ConstraintFactory, self).__init__(graphfactory)\n self.graph = graph\n ## Select whether placement should be strict or relaxed.\n # \\sa buildStrictPlacement, buildRelaxedPlacement\n self.strict = False\n\n ## Calls ConstraintGraph.createGraph and ConstraintGraph.createPreGrasp\n ## \\param g gripper string\n ## \\param h handle string\n def buildGrasp (self, g, h):\n n = g + \" grasps \" + h\n pn = g + \" pregrasps \" + h\n self.graph.createGrasp (n, g, h)\n self.graph.createPreGrasp (pn, g, h)\n return dict ( list(zip (self.gfields, (\n Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ n, ])),\n Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ n + \"/complement\", ])),\n Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ pn, ])),\n ))))\n\n def buildPlacement (self, o):\n if self.strict:\n return self.buildStrictPlacement (o)\n else:\n return self.buildRelaxedPlacement (o)\n\n ## This implements strict placement manifolds,\n ## where the parameterization constraints is the complement\n ## of the placement constraint.\n ## \\param o string\n def buildStrictPlacement (self, o):\n n = \"place_\" + o\n pn = \"preplace_\" + o\n width = 0.05\n io = self.graphfactory.objects.index(o)\n placeAlreadyCreated = n in self.graph.clientBasic.problem.getAvailable (\"numericalconstraint\")\n if (len(self.graphfactory.contactsPerObjects[io]) == 0 or len(self.graphfactory.envContacts) == 0) and not placeAlreadyCreated:\n ljs = []\n for n in self.graph.clientBasic.robot.getJointNames():\n if n.startswith(o + \"/\"):\n ljs.append(n)\n q = self.graph.clientBasic.robot.getJointConfig(n)\n self.graph.clientBasic.problem.createLockedJoint(n, n, q)\n return dict ( list(zip (self.pfields, (Constraints (), Constraints (lockedJoints = ljs), Constraints (),))))\n if not placeAlreadyCreated:\n self.graph.client.problem.createPlacementConstraint (n, self.graphfactory.contactsPerObjects[io], self.graphfactory.envContacts)\n if not pn in self.graph.clientBasic.problem.getAvailable (\"numericalconstraint\"):\n self.graph.client.problem.createPrePlacementConstraint (pn, self.graphfactory.contactsPerObjects[io], self.graphfactory.envContacts, width)\n return dict ( list(zip (self.pfields, (\n Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ n, ])),\n Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ n + \"/complement\", ])),\n Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ pn, ])),\n ))))\n\n ## This implements relaxed placement manifolds,\n ## where the parameterization constraints is the LockedJoint of\n ## the object root joint\n ## \\param o string\n def buildRelaxedPlacement (self, o):\n n = \"place_\" + o\n pn = \"preplace_\" + o\n width = 0.05\n io = self.graphfactory.objects.index(o)\n ljs = []\n for jn in self.graph.clientBasic.robot.getJointNames():\n if jn.startswith(o + \"/\"):\n ljs.append(jn)\n q = self.graph.clientBasic.robot.getJointConfig(jn)\n self.graph.clientBasic.problem.createLockedJoint(jn, jn, q)\n placeAlreadyCreated = n in self.graph.clientBasic.problem.getAvailable (\"numericalconstraint\")\n if (len(self.graphfactory.contactsPerObjects[io]) == 0 or len(self.graphfactory.envContacts) == 0) and not placeAlreadyCreated:\n return dict ( list(zip (self.pfields, (Constraints (), Constraints (lockedJoints = ljs), Constraints (),))))\n if not placeAlreadyCreated:\n self.graph.client.problem.createPlacementConstraint (n, self.graphfactory.contactsPerObjects[io], self.graphfactory.envContacts)\n if not pn in self.graph.clientBasic.problem.getAvailable (\"numericalconstraint\"):\n self.graph.client.problem.createPrePlacementConstraint (pn, self.graphfactory.contactsPerObjects[io], self.graphfactory.envContacts, width)\n return dict ( list(zip (self.pfields, (\n Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ n, ])),\n Constraints (lockedJoints = ljs),\n Constraints (numConstraints = _removeEmptyConstraints(self.graph.clientBasic.problem, [ pn, ])),))))\n\n## Default implementation of ConstraintGraphFactory\n#\n# The minimal usage is the following:\n# \\code\n# graph = ConstraintGraph (robot, \"graph\")\n#\n# # Required calls\n# factory = ConstraintGraphFactory (graph)\n# factory.setGrippers ([\"gripper1\", ... ])\n# factory.setObjects ([\"object1\", ], [ [ \"object1/handle1\", ... ] ], [ [] ])\n#\n# # Optionally\n# factory.environmentContacts ([\"contact1\", ... ])\n# factory.setRules ([ Rule ([\"gripper1\", ..], [\"handle1\", ...], True), ... ])\n#\n# factory.generate ()\n# # graph is initialized\n# \\endcode\nclass ConstraintGraphFactory(GraphFactoryAbstract):\n class StateAndManifold:\n def __init__ (self, factory, grasps, id, name):\n self.grasps = grasps\n self.id = id\n self.name = name\n self.manifold = Constraints()\n self.foliation = Constraints()\n # Add the grasps\n for ig, ih in enumerate(grasps):\n if ih is not None:\n self.manifold += factory.constraints.g (ig, ih, 'grasp')\n self.foliation += factory.constraints.g (ig, ih, 'graspComplement')\n # Add the placement constraints\n for io, object in enumerate(factory.objects):\n if not factory._isObjectGrasped(grasps, io):\n self.manifold += factory.constraints.p (object, 'placement')\n self.foliation += factory.constraints.p (object, 'placementComplement')\n\n ## \\param graph an instance of ConstraintGraph\n def __init__(self, graph):\n super (ConstraintGraphFactory, self).__init__()\n\n ## Stores the constraints in a child class of ConstraintFactoryAbstract\n self.constraints = ConstraintFactory (self, graph)\n\n self.graph = graph\n\n ## \\name Default functions\n # \\{\n\n def makeState(self, grasps, priority):\n # Create state\n name = self._stateName (grasps)\n nid = self.graph.createNode (name, False, priority)\n state = ConstraintGraphFactory.StateAndManifold (self, grasps, nid, name)\n\n # Add the constraints\n self.graph.addConstraints (node = name, constraints = state.manifold)\n return state\n\n def makeLoopTransition(self, state):\n n = self._loopTransitionName (state.grasps)\n self.graph.createEdge (state.name, state.name, n, weight = 0, isInNode = state.name)\n self.graph.addConstraints (edge = n, constraints = state.foliation)\n\n def makeTransition(self, stateFrom, stateTo, ig):\n sf = stateFrom\n st = stateTo\n grasps = sf.grasps\n nGrasps = st.grasps\n names = self._transitionNames(sf, st, ig)\n if names in self.transitions:\n return\n\n iobj = self.objectFromHandle [st.grasps[ig]]\n obj = self.objects[iobj]\n noPlace = self._isObjectGrasped (sf.grasps, iobj)\n\n gc = self.constraints.g (ig, st.grasps[ig], 'grasp')\n gcc = self.constraints.g (ig, st.grasps[ig], 'graspComplement')\n pgc = self.constraints.g (ig, st.grasps[ig], 'preGrasp')\n if noPlace:\n pc = Constraints()\n pcc = Constraints()\n ppc = Constraints()\n else:\n pc = self.constraints.p (self.objectFromHandle[st.grasps[ig]], 'placement')\n pcc = self.constraints.p (self.objectFromHandle[st.grasps[ig]], 'placementComplement')\n ppc = self.constraints.p (self.objectFromHandle[st.grasps[ig]], 'prePlacement')\n manifold = sf.manifold - pc\n\n # The different cases:\n pregrasp = not pgc.empty()\n intersec = (not gc.empty()) and (not pc.empty())\n preplace = not ppc.empty()\n\n nWaypoints = pregrasp + intersec + preplace\n nTransitions = 1 + nWaypoints\n nStates = 2 + nWaypoints\n\n def _createWaypointState (name, constraints):\n self.graph.createNode (name, True)\n self.graph.addConstraints (node = name, constraints = constraints)\n return name\n\n # Create waypoint states\n intersection = 0\n wStates = [ sf.name, ]\n if pregrasp:\n wStates.append (_createWaypointState (names[0] + \"_pregrasp\",\n pc + pgc + manifold))\n if intersec:\n wStates.append (_createWaypointState (names[0] + \"_intersec\",\n pc + gc + manifold))\n if preplace:\n wStates.append (_createWaypointState (names[0] + \"_preplace\",\n ppc + gc + manifold))\n wStates.append(st.name)\n\n # Link waypoints\n transitions = names[:]\n if nWaypoints > 0:\n self.graph.createWaypointEdge (sf.name, st.name, names[0], nWaypoints, automaticBuilder = False)\n self.graph.createWaypointEdge (st.name, sf.name, names[1], nWaypoints, automaticBuilder = False)\n wTransitions = []\n for i in range(nTransitions):\n nf = \"{0}_{1}{2}\".format(names[0], i, i+1)\n nb = \"{0}_{2}{1}\".format(names[1], i, i+1)\n self.graph.createEdge (wStates[i], wStates[i+1], nf, -1)\n self.graph.createEdge (wStates[i+1], wStates[i], nb, -1)\n self.graph.graph.setWaypoint (self.graph.edges[transitions[0]],\n i, self.graph.edges[nf], self.graph.nodes[wStates[i+1]])\n self.graph.graph.setWaypoint (self.graph.edges[transitions[1]],\n nTransitions - 1 - i, self.graph.edges[nb], self.graph.nodes[wStates[i]])\n wTransitions.append ( (nf, nb) )\n\n # Set states\n M = 0 if gc.empty() else 1 + pregrasp\n for i in range(M):\n self.graph.setContainingNode (wTransitions[i][0], sf.name)\n self.graph.addConstraints (edge = wTransitions[i][0], constraints = sf.foliation)\n self.graph.setContainingNode (wTransitions[i][1], sf.name)\n self.graph.addConstraints (edge = wTransitions[i][1], constraints = sf.foliation)\n for i in range(M, nTransitions):\n self.graph.setContainingNode (wTransitions[i][0], st.name)\n self.graph.addConstraints (edge = wTransitions[i][0], constraints = st.foliation)\n self.graph.setContainingNode (wTransitions[i][1], st.name)\n self.graph.addConstraints (edge = wTransitions[i][1], constraints = st.foliation)\n\n # Set all to short except first one.\n for i in range(nTransitions - 1):\n self.graph.setShort (wTransitions[i + 1][0], True)\n self.graph.setShort (wTransitions[i ][1], True)\n else:\n #TODO This case will likely never happen\n raise NotImplementedError(\"This case has not been implemented\")\n self.graph.createEdge (sf.name, st.name, names[0])\n self.graph.createEdge (st.name, sf.name, names[1])\n\n self.transitions.add(names)\n\n ## \\}\n","repo_name":"EricWang1hitsz/hpp_source_code","sub_path":"install/lib/python2.7/dist-packages/hpp/corbaserver/manipulation/constraint_graph_factory.py","file_name":"constraint_graph_factory.py","file_ext":"py","file_size_in_byte":22475,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"33"} +{"seq_id":"39798537248","text":"import numpy as np\r\nimport pandas as pd\r\nfrom flask import Flask, request, jsonify, render_template\r\nimport pickle\r\n\r\napp = Flask(__name__)\r\nmodel_log= pickle.load(open('model_log.pkl', 'rb'))\r\n\r\ndf = pd.read_csv('diabetes.csv')\r\nX=df.drop(['Outcome'],axis=1)\r\n\r\ny=df['Outcome']\r\n\r\n@app.route('/')\r\ndef home():\r\n return render_template('resultp.html')\r\n\r\n@app.route('/predict',methods=['POST'])\r\ndef predict():\r\n '''\r\n For rendering results on HTML GUI\r\n '''\r\n float_features = [int(x) for x in request.form.values()]\r\n final_features = [np.array(float_features)]\r\n prediction = model_log.predict(final_features)\r\n\r\n if prediction == 1:\r\n pred = \"You have Diabetes.\"\r\n elif prediction == 0:\r\n pred = \"You don't have diabetes.\"\r\n output = pred\r\n\r\n return render_template('resultp.html', prediction_text='{}'.format(output))\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","repo_name":"Rahini23/Diabetes","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"41081861012","text":"from autofocus_system import autofocus_PI\nimport matplotlib.pyplot as plt\n\nt_step = 0.0\nt1 = 0.05\nstep = 1\ndt = 0.0001\ntitle = \"\"\n\ndef conf_plot(title = \"Time Response\"):\n title = title\n print(f\"Configuring autofocus system for {title} plots\")\n _system = autofocus_PI(250,55)\n t, u = _system.get_step_input(t_step,t1,step,dt)\n t = _system.time_to_ms(t)\n plt.figure()\n plt.title(title)\n plt.plot(t, u, \"b--\", label=\"u(s)\")\n plt.xlabel(\"time [ms]\")\n plt.ylabel(\"lens displacement [mm]\")\n\ndef plot_response(kp, ki, color = \"blue\", label = \"z(t)\"):\n system = autofocus_PI(kp, ki)\n system.print_tf()\n (t, y) = system.step_response(t_step,t1,step,dt)\n\n plt.plot(t, y, color, label=label)\n\n# Print student data\nprint(\"Magdiel Martínez\")\nprint(\"1660362\\n\")\n\n# Configure plot\nconf_plot(\"Time Response (ki = 55)\")\n\n# Generate responses\nfixed_ki = [(100, \"black\"), (250, \"brown\"), (500, \"red\"), (750, \"green\"), (900, \"y\")]\n\nfor kp, color in fixed_ki:\n plot_response(kp,55,color,f\"z(t), kp={kp}\")\n\n# Display plot\nplt.legend()\nplt.savefig(\"fixed_ki.png\")\nplt.show()\n\n# Configure plot\nconf_plot(\"Time Response (kp = 500)\")\n\n# Generate responses\nfixed_kp = [(20, \"black\"), (35, \"brown\"), (55, \"red\"), (75, \"green\"), (90, \"yellow\")]\n\nfor ki, color in fixed_kp:\n plot_response(500,ki,color,f\"z(t), ki={ki}\")\n\n# Display plot\nplt.legend()\nplt.savefig(\"fixed_kp.png\")\nplt.show()\n\n# Explosion\nt1 = 0.5\n# Configure plot\nconf_plot(\"Time Response (kp = 500, ki = 750)\")\nplot_response(500,750,\"r\",f\"z(t), kp=500 ki=750\")\n# Display plot\nplt.legend()\nplt.savefig(\"chaos.png\")\nplt.show()\n","repo_name":"Magdiel3/labmc_autofocus","sub_path":"Practica5.py","file_name":"Practica5.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"32543946190","text":"import logging\nfrom packit_service.constants import (\n INTERNAL_TF_BUILDS_AND_TESTS_NOT_ALLOWED,\n INTERNAL_TF_TESTS_NOT_ALLOWED,\n)\n\nfrom packit_service.worker.checker.abstract import ActorChecker, Checker\nfrom packit_service.worker.events.gitlab import MergeRequestGitlabEvent\nfrom packit_service.worker.events.enums import GitlabEventAction\nfrom packit_service.worker.handlers.mixin import (\n GetTestingFarmJobHelperMixin,\n GetCoprBuildMixin,\n GetGithubCommentEventMixin,\n)\nfrom packit_service.worker.reporting import BaseCommitStatus\n\nlogger = logging.getLogger(__name__)\n\n\nclass IsEventOk(\n Checker, GetTestingFarmJobHelperMixin, GetCoprBuildMixin, GetGithubCommentEventMixin\n):\n def pre_check(self) -> bool:\n if (\n self.data.event_type == MergeRequestGitlabEvent.__name__\n and self.data.event_dict[\"action\"] == GitlabEventAction.closed.value\n ):\n # Not interested in closed merge requests\n return False\n\n if self.testing_farm_job_helper.is_test_comment_pr_argument_present():\n return self.testing_farm_job_helper.check_comment_pr_argument_and_report()\n\n return not (\n self.testing_farm_job_helper.skip_build\n and self.testing_farm_job_helper.is_copr_build_comment_event()\n )\n\n\nclass IsEventForJob(Checker):\n def pre_check(self) -> bool:\n if self.data.identifier != self.job_config.identifier:\n logger.debug(\n f\"Skipping reporting, identifiers don't match \"\n f\"(identifier of the test job to report: {self.data.identifier}, \"\n f\"identifier from job config: {self.job_config.identifier}).\"\n )\n return False\n return True\n\n\nclass CanActorRunJob(ActorChecker, GetTestingFarmJobHelperMixin):\n \"\"\"For external contributors, we need to be more careful when running jobs.\n This is a handler-specific permission check\n for a user who trigger the action on a PR.\n\n The job is not allowed for external contributors when using internal TF.\n \"\"\"\n\n def _pre_check(self) -> bool:\n any_internal_test_job_build_required = (\n any(\n test_job.use_internal_tf and not test_job.skip_build\n for test_job in self.testing_farm_job_helper.job_tests_all\n )\n and self.testing_farm_job_helper.build_required()\n )\n if (\n (self.job_config.use_internal_tf or any_internal_test_job_build_required)\n and not self.project.can_merge_pr(self.actor)\n and self.actor not in self.service_config.admins\n ):\n message = (\n INTERNAL_TF_BUILDS_AND_TESTS_NOT_ALLOWED\n if self.testing_farm_job_helper.job_build\n else INTERNAL_TF_TESTS_NOT_ALLOWED\n )\n self.testing_farm_job_helper.report_status_to_tests(\n description=message[0].format(actor=self.actor),\n state=BaseCommitStatus.neutral,\n markdown_content=message[1].format(\n packit_comment_command_prefix=self.service_config.comment_command_prefix\n ),\n )\n return False\n return True\n","repo_name":"LecrisUT/packit-service","sub_path":"packit_service/worker/checker/testing_farm.py","file_name":"testing_farm.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"33"} +{"seq_id":"23664054436","text":"import logging\n\nfrom pandas import DataFrame\nfrom ta.momentum import RSIIndicator\nfrom ta.trend import EMAIndicator, PSARIndicator, SMAIndicator\nfrom ta.volatility import AverageTrueRange\nfrom typing import Tuple\n\nlogger = logging.getLogger(__name__)\n\n\nclass Indicators():\n \"\"\"Adds technical analysis indicators to pandas DataFrame.\n It uses ta 3rd party module for technical analysis.\n\n Methods:\n add_psar(self, df: DataFrame):\n Add to DataFrame the Parabolic Stop and reverse indicator.\n add_rsi(df):\n Add to DataFrame the Relative Strength index indicator.\n add_sma(df, periods):\n Add to DataFrame the Simple Moving Average indicator.\n add_ema(df, periods):\n Add to DataFrame the Exponential Moving Average indicator.\n add_atr(df):\n Add to DataFrame the Average True Range indicator.\n find_lowest_near(df, i, l, next_no=5):\n Find lowest value in number of next candles.\n def find_highest_near(df, i, h, next_no=5):\n Find highiest value in number of next candles.\"\"\"\n\n def add_psar(self, df: DataFrame)-> None:\n \"\"\"Add to DataFrame the Parabolic Stop and reverse indicator.\n \n Params:\n df(DataFrame): Data.\n \"\"\"\n psar = PSARIndicator(df[\"high\"], df[\"low\"], df[\"close\"], 0.01, 0.20)\n df[\"psar\"] = psar.psar()\n df[\"psar_up_ind\"] = psar.psar_up_indicator()\n df[\"psar_down_ind\"] = psar.psar_down_indicator()\n\n def add_rsi(self, df: DataFrame)-> None:\n \"\"\"Add to DataFrame the Relative Strength index indicator.\n \n Params:\n df(DataFrame): Data.\n \"\"\"\n rsi = RSIIndicator(df[\"close\"])\n df[\"rsi\"] = rsi.rsi()\n\n def add_sma(self, df: DataFrame, periods: int)-> None:\n \"\"\"Add to DataFrame the Simple Moving Average indicator.\n \n Params:\n df(DataFrame): Data.\n periods(int): Periods for SMA. Like SMA20, SMA50.\n \"\"\"\n sma_str = \"sma\" + str(periods)\n df[sma_str] = SMAIndicator(\n close=df[\"close\"],\n window=periods,\n fillna=True\n ).sma_indicator()\n\n def add_ema(self, df: DataFrame, periods: int)-> None:\n \"\"\"Add to DataFrame the Exponential Moving Average indicator.\n \n Params:\n df(DataFrame): Data.\n periods(int): Periods for EMA. Like EMA20, EMA50.\n \"\"\"\n ema_str = \"ema\" + str(periods)\n df[ema_str] = EMAIndicator(\n close=df[\"close\"],\n window=periods,\n fillna=True\n ).ema_indicator()\n\n def add_atr(self, df: DataFrame)-> None:\n \"\"\"Add to DataFrame the Average True Range indicator.\n \n Params:\n df(DataFrame): Data.\n \"\"\"\n if(len(df) > 14): # ATR is calculated from last 14 values.\n df[\"atr\"] = AverageTrueRange(\n high=df[\"high\"],\n low=df[\"low\"],\n close=df[\"close\"],\n fillna=True\n ).average_true_range()\n else:\n logger.warning(\n \"Failed adding ATR to data which lenght is lower than 14.\")\n\n def find_lowest_near(\n self,\n df: DataFrame,\n i: int,\n l: float,\n next_no: int = 5\n ) -> Tuple[int, float]:\n \"\"\"Find lowest value in number of next candles.\n \n Params:\n df(DataFrame): Data.\n i(int): Index of candle with input lowest value.\n l(float): Input lowest value actually found in area.\n next_no(int): Number of next candles to check.\n\n Returns:\n tuple: Index and value pair of canlde with lowest low.\n \"\"\"\n lowsCount = 0\n idx = i\n for index, val in enumerate(df['low'][i:]):\n if val > l:\n lowsCount += 1\n if val <= l:\n l = val\n idx = i + index\n lowsCount = 0\n if lowsCount == next_no:\n break\n return (idx, l)\n\n def find_highest_near(\n self,\n df: DataFrame,\n i: int,\n h: float,\n next_no: int = 5\n ) -> Tuple[int, float]:\n \"\"\"Find highiest value in number of next candles.\n \n Params:\n df(DataFrame): Data.\n i(int): Index of candle with input highiest value.\n l(float): Input highiest value actually found in area.\n next_no(int): Number of next candles to check.\n\n Returns:\n tuple: Index and value pair of canlde with highiest high.\n \"\"\"\n highsCount = 0\n idx = i\n for index, val in enumerate(df['high'][i:]):\n if val < h:\n highsCount += 1\n if val >= h:\n h = val\n idx = i + index\n highsCount = 0\n if highsCount == next_no:\n break\n return (idx, h)\n\n\n","repo_name":"zawada92/trading_bot","sub_path":"trading_bot/indicators.py","file_name":"indicators.py","file_ext":"py","file_size_in_byte":5099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"39435462651","text":"\"\"\"\nTest the generalized fact layer\n\"\"\"\nfrom __future__ import with_statement\n\nfrom twisted.trial import unittest\n\nfrom playtools import fact\nfrom playtools.test.pttestutil import pluginsLoadedFromTest\n\nfrom . import gameplugin\n\n__all__ = []\n\nclass TestFactPluginLoading(unittest.TestCase):\n \"\"\"\n Tests for the plugin-loading apparatus itself.\n \"\"\"\n def test_getSystems(self):\n \"\"\"\n The getSystems function finds systems we have set up\n \"\"\"\n with pluginsLoadedFromTest(fact):\n systems = fact.getSystems()\n\n self.assertTrue('Buildings & Badgers' in systems)\n self.assertTrue(('Buildings & Badgers', '2.06') in systems)\n\n badgers = systems[('Buildings & Badgers', '2.06')]\n # verify that we can access by either name or name-version tuple\n self.assertIdentical(badgers, systems['Buildings & Badgers'])\n self.assertEqual(badgers.__doc__.strip(),\n 'The Buildings & Badgers role-playing game')\n self.assertEqual(badgers.version, '2.06')\n self.assertEqual(badgers.searchIndexPath, 'test-badgers-index')\n\n def _importRuleCollections(self, game):\n \"\"\"\n Set up and run the importRuleCollections, which is boilerplate for\n several tests.\n \"\"\"\n systems = {'Buildings & Badgers': game,\n ('Buildings & Badgers', '2.06'): game,\n }\n with pluginsLoadedFromTest(fact):\n fact.importRuleCollections(systems)\n\n def test_importRuleCollections(self):\n \"\"\"\n Make sure importRuleCollections puts actual RuleCollections into the\n game systems\n \"\"\"\n game = gameplugin.BuildingsAndBadgersSystem()\n self._importRuleCollections(game)\n self.assertTrue('building' in game.facts)\n self.assertTrue('badger' in game.facts)\n\n def test_lookup(self):\n \"\"\"\n For some domain, we can lookup an item in that domain\n \"\"\"\n game = gameplugin.BuildingsAndBadgersSystem()\n self._importRuleCollections(game)\n badgers = game.facts['badger']\n self.assertEqual(badgers.lookup(u'73').name, u'Giant Man-Eating Badger')\n\n def test_getitem(self):\n \"\"\"\n We can pull an item out of the collection by key\n \"\"\"\n game = gameplugin.BuildingsAndBadgersSystem()\n self._importRuleCollections(game)\n badgers = game.facts['badger']\n self.assertEqual(badgers[u'73'].name, u'Giant Man-Eating Badger')\n self.assertEqual(badgers[u'Giant Man-Eating Badger'].name, \n u'Giant Man-Eating Badger')\n\n def test_dumpObject(self):\n \"\"\"\n We can get a dump of all objects from a domain\n \"\"\"\n game = gameplugin.BuildingsAndBadgersSystem()\n self._importRuleCollections(game)\n badgers = game.facts['badger']\n dumped = badgers.dump()\n self.assertEqual(len(dumped), 2)\n self.assertEqual(dumped[0].name, u'Small Badger')\n\n\nclass TestGameSystems(unittest.TestCase):\n \"\"\"\n Tests for the plugins that get loaded by default\n \"\"\"\n def test_systems(self):\n \"\"\"\n We can get a dict of plugin systems with metadata\n \"\"\"\n ss = fact.systems\n self.assertTrue(('Pathfinder', '1.0') in ss)\n self.assertTrue(('D20 SRD', '3.5') in ss)\n\n def test_facts(self):\n \"\"\"\n We can get a dict of fact domains that exist in a particular system\n \"\"\"\n srd = fact.systems['D20 SRD']\n pathfinder = fact.systems['Pathfinder']\n self.assertTrue('spell' in srd.facts)\n self.assertTrue('monster' in srd.facts)\n # test that fact collections are not inserted willy-nilly into random\n # systems\n self.assertFalse('spell' in pathfinder.facts)\n\n","repo_name":"corydodt/Playtools","sub_path":"playtools/test/test_fact.py","file_name":"test_fact.py","file_ext":"py","file_size_in_byte":3796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"71356199455","text":"from person.models import Character, Artist\nfrom django.contrib import admin\nfrom django import forms\n\n\n# Register your models here.\nadmin.site.register(Character)\n\n# Register your models here.\nclass ArtistForm(forms.ModelForm):\n aliases_str = forms.CharField(label='Aliases', required=False)\n class Meta:\n model = Artist\n fields = [\n 'name',\n 'romanized_name',\n 'aliases_str',\n ]\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n instance = kwargs.get(\"instance\")\n if instance:\n self.fields['aliases_str'].initial = \", \".join(x.romanized_name for x in instance.aliases.all() )\n\nclass ArtistAdmin(admin.ModelAdmin):\n form = ArtistForm\n search_fields = ['romanized_name','name']\n\n class Media:\n js = (\n 'https://cdnjs.cloudflare.com/ajax/libs/tinymce/5.6.2/tinymce.min.js',\n 'tinymce-init.js'\n )\n def save_model(self, request, obj, form, change):\n aliases_str = form.cleaned_data.get('aliases_str')\n aliases = Artist.objects.comma_to_qs(aliases_str)\n if not obj.id:\n obj.save()\n obj.aliases.clear()\n obj.aliases.add(*aliases)\n obj.save()\n\nadmin.site.register(Artist, ArtistAdmin)","repo_name":"Damillora/IRIS","sub_path":"person/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"72102642975","text":"def matrix_multiply(matrix1, matrix2):\n print_matrix(matrix1)\n print_matrix(matrix2)\n\n r1 = len(matrix1)\n c1 = len(matrix1[0])\n r2 = len(matrix2)\n c2 = len(matrix2[0])\n\n rv = [[0 for _ in range(c2)] for _ in range(r1)]\n\n for i in range(r1):\n for j in range(c2):\n sum = 0\n for k in range(c1):\n sum += matrix1[i][k] * matrix2[k][j]\n rv[i][j] = sum\n return rv\n\ndef print_matrix(matrix):\n print(\"\\n\")\n for i in range(len(matrix)):\n print(\" \".join(str(x) for x in matrix[i]))\n print(\"\\n\")\n\n\ntm1 = [[1,2],[3,4],[5,6],[7,8]]\ntm2 = [[1,2,3],[4,5,6]]\n\nprint_matrix(matrix_multiply(tm1, tm2))\n","repo_name":"kkjang/algorithms","sub_path":"matrix_mutiply.py","file_name":"matrix_mutiply.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"12565698251","text":"\nimport sqlite3\nfrom tkinter import ttk\nfrom tkinter import *\nfrom tkinter import messagebox\n\n\n\n\nclass User:\n def __init__(self,mainw):\n self.mainw=mainw\n\n def user_mainmenu(self,a,b):\n self.mainw.iconbitmap(r'C:\\Sistema_vendas_tkinter_copia\\images\\icon.ico')\n self.mainframe = LabelFrame(self.mainw, width=800, height=140, bg=\"#f7f7f7\")\n self.mainframe.place(x=330, y=120)\n mi = PhotoImage(file=\"images/carrinho.png\")\n mi = mi.subsample(a, b)\n self.aitems = Button(self.mainframe, text=\"ITEMS\",bd=0,font=\"roboto 11 bold\", image=mi)\n self.aitems.image = mi\n self.aitems.place(x=260, y=17)\n mi = PhotoImage(file=\"images/nota.png\")\n mi = mi.subsample(a,b)\n self.aitems = Button(self.mainframe, text=\"NOTAS\",bd=0,font=\"roboto 11 bold\", image=mi)\n self.aitems.image = mi\n self.aitems.place(x=62, y=17)\n mi = PhotoImage(file=\"images/usertrocar.png\")\n mi = mi.subsample(a, b)\n self.changeuser = Button(self.mainframe, text=\"SAIR\",bd=0,font=\"roboto 11 bold\", image=mi)\n self.changeuser.image = mi\n self.changeuser.place(x=460, y=17)\n mi = PhotoImage(file=\"images/sair.png\")\n mi = mi.subsample(a, b)\n self.logout = Button(self.mainframe, text=\"FECHAR\",bd=0,font=\"roboto 11 bold\", image=mi)\n self.logout.image = mi\n self.logout.place(x=670, y=17)\n self.tableframe1 =Frame(self.mainw, width=150, height=400,bg=\"#9ACD32\")\n self.tableframe1.place(x=1230, y=270, anchor=NE)\n self.tableframe1info=self.tableframe1.place_info()\n self.tableframe =Frame(self.mainw, width=350, height=700,bg=\"#9ACD32\")\n self.tableframe.place(x=1110, y=300, anchor=NE)\n self.tableframeinfo = self.tableframe.place_info()\n self.entryframe = Frame(self.mainw, width=800, height=350, bg=\"#9ACD32\")\n self.entryframe.place(x=810, y=460+20)\n self.entryframeinfo = self.entryframe.place_info()\n self.entryframe1 = Frame(self.mainw, width=500, height=350, bg=\"#9ACD32\")\n self.entryframe1.place(x=230, y=470+20)\n self.entryframe1info=self.entryframe1.place_info()\n\n","repo_name":"sangiorgiovba/Sistema_tkinter_2021","sub_path":"User_menu.py","file_name":"User_menu.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"33"} +{"seq_id":"5910038304","text":"import torch\nimport triton\nimport triton.language as tl\n\nSTATE_SIZE = 2048\nSEQUENCE_LENGTH = 8192\nN_HEADS = 1024\n\n@triton.jit\ndef ssm_kernel_perhead(u_ptr, a_ptr, b_ptr, c_ptr, output_ptr, U_LENGTH: tl.constexpr, N: tl.constexpr, N_HEADS: tl.constexpr):\n i = tl.program_id(axis=0)\n outputs = tl.zeros((U_LENGTH,), dtype=tl.float32)\n X = tl.zeros((N,), dtype=tl.float32)\n A = tl.load(a_ptr + i * N + tl.arange(0, N))\n B = tl.load(b_ptr + i * N + tl.arange(0, N))\n C = tl.load(c_ptr + i * N + tl.arange(0, N))\n u = tl.load(u_ptr + tl.arange(0, U_LENGTH))\n for j in range(U_LENGTH):\n u_t = tl.load(u_ptr + j)\n X = X*A + B*u_t\n value = tl.sum(X*C, axis=0)\n tl.store(output_ptr + (i * U_LENGTH + j), value)\n\ndef triton_ssm(sequence, A_DIAG, B, C, N_HEADS, STATE_SIZE, SEQUENCE_LENGTH: int):\n triton_outputs = torch.empty((N_HEADS, len(sequence)), device=\"cuda\", dtype=sequence.dtype)\n asm = ssm_kernel_perhead[(N_HEADS,)](sequence, A_DIAG, B, C, triton_outputs, len(sequence), STATE_SIZE, N_HEADS)\n return triton_outputs, asm\n\nstate = torch.zeros((STATE_SIZE))\nA = torch.eye(STATE_SIZE, dtype=torch.float32, device=\"cuda\")[None, :, :].repeat(N_HEADS, 1, 1)\nB = torch.ones((N_HEADS, STATE_SIZE, 1), dtype=torch.float32, device=\"cuda\")\nC = torch.ones((N_HEADS, 1, STATE_SIZE), dtype=torch.float32, device=\"cuda\")\n# A *= torch.ones(N_HEADS, STATE_SIZE, STATE_SIZE, device=\"cuda\")\nA_DIAG = torch.stack([torch.diagonal(A[i]) for i in range(len(A))])\noutputs = torch.zeros((N_HEADS, SEQUENCE_LENGTH), dtype=torch.float32, device=\"cuda\")\nsequence = torch.ones(SEQUENCE_LENGTH, dtype=torch.float32, device=\"cuda\")[:, None]\n\nB_bf16 = B.to(dtype=torch.bfloat16)\nC_bf16 = C.to(dtype=torch.bfloat16)\nA_DIAG_bf16 = A_DIAG.to(dtype=torch.bfloat16)\nsequence_bf16 = sequence.to(dtype=torch.bfloat16)\n\nfor i in range(8):\n # triton_outputs, asm = triton_ssm(sequence_bf16, A_DIAG_bf16, B_bf16, C_bf16, N_HEADS, STATE_SIZE, SEQUENCE_LENGTH)\n triton_outputs, asm = triton_ssm(sequence, A_DIAG, B, C, N_HEADS, STATE_SIZE, SEQUENCE_LENGTH)\n print(triton_outputs.sum())\n\nbreakpoint()\n","repo_name":"sophiawisdom/ssms","sub_path":"run_nonbatched.py","file_name":"run_nonbatched.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"33"} +{"seq_id":"15208615183","text":"#!/usr/bin/env python\n# -*-coding:utf-8-*-\n# File Name : parse.py\n# Description :\n# Author :\n# Creation Date : 2019-03-26\n# Last Modified : 2019年03月27日 星期三 14时31分23秒\n# Created By : lsl\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nplt.rcParams[\"font.sans-serif\"] = [\"SimHei\"] # 用来正常显示中文标签\nplt.rcParams[\"axes.unicode_minus\"] = False # 用来正常显示负号\n\n\ndef f(x):\n if x == \"当前房源\":\n return \"可入住\"\n else:\n return x\n\n\ndef main():\n df = pd.read_csv(\"./roommate.csv\")\n df[\"性别\"] = df[\"性别\"].map(lambda x: x.strip())\n df = pd.read_csv(\"./roommate.csv\")\n df[\"状态\"] = df[\"状态\"].map(f)\n df[\"状态\"].value_counts().plot.pie()\n plt.show()\n df[\"性别\"] = df[\"性别\"].map(lambda x: x.strip())\n df = df[(df[\"性别\"] == \"man\") | (df[\"性别\"] == \"woman\")]\n df[\"性别\"].value_counts().plot.pie()\n plt.show()\n df[(df[\"职业\"] != \"…\") & (df[\"职业\"] != \"...\") & (df[\"职业\"] != \"未知\")][\n \"职业\"\n ].value_counts().head(10).plot.pie()\n plt.show()\n df[df[\"价格\"] != 1][\"价格\"].plot.hist()\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"uxlsl/ziroom","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"16891820641","text":"from __future__ import print_function\nfrom pyspark import SparkContext\nfrom pyspark.sql.session import SparkSession\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\nfrom pyspark.ml.feature import VectorAssembler\nfrom pyspark.ml.classification import LogisticRegressionModel\nfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator\nfrom pyspark.ml.feature import StringIndexerModel, IndexToString, StandardScaler, MinMaxScaler, PolynomialExpansion\nfrom pyspark.ml import PipelineModel\nfrom pyspark.ml.tuning import CrossValidator, ParamGridBuilder\nfrom pyspark.sql import Row\n\nkafka_topic = 'from-pubsub'\n\nzk = '10.138.0.2:2181' # Apache ZooKeeper quorum\n\napp_name = 'from-pubsub' # Can be some other name\nsc = SparkContext(appName= \"KafkaPubsub\" )\nssc = StreamingContext(sc, 50 )\nspark = SparkSession(sc)\n\nkafkaStream = KafkaUtils.createStream(ssc, zk, app_name, {kafka_topic: 1})\n\n#parse the kafka stream\n\ndef getSparkSessionInstance(sparkConf):\n if (\"sparkSessionSingletonInstance\" not in globals()):\n globals()[\"sparkSessionSingletonInstance\"] = SparkSession \\\n .builder \\\n .config(conf=sparkConf) \\\n .getOrCreate()\n return globals()[\"sparkSessionSingletonInstance\"]\n\ndef process(rdd):\n\n spark = getSparkSessionInstance(rdd.context.getConf())\n\n dota = rdd.map(lambda x: x[1])\n featuresdata = dota.map(lambda x: x.split(':')[2])\n actualdata = featuresdata.map(lambda x: x.split(','))\n rowRdd = actualdata.map(lambda x: Row(sl=float(x[0][1:]), sw=float(x[1]), pl=float(x[2]), pw=float(x[3]), stringlabel=x[4][:-4]))\n features = spark.createDataFrame(rowRdd)\n features.show()\n rowRdd = actualdata.map(lambda x: Row(sl=float(x[0]), sw=float(x[1]), pl=float(x[2]), pw=float(x[3]), stringlabel=x[4]))\n \n indexer = StringIndexerModel()\n assembler = VectorAssembler()\n lr = LogisticRegressionModel()\n\n pipe = PipelineModel(stages=[indexer,assembler,lr]).load('gs://suryasuresh/lab8output')\n\n result = pipe.transform(features)\n\n f1score = MulticlassClassificationEvaluator(metricName='f1')\n precision = MulticlassClassificationEvaluator(metricName='weightedPrecision')\n recall = MulticlassClassificationEvaluator(metricName='weightedRecall')\n accuracy = MulticlassClassificationEvaluator(metricName='accuracy')\n\n print(result.values)\n print(\"Accuracy:\\t\",accuracy.evaluate(result),\"\\nF1score:\\t\",f1score.evaluate(result),\"\\nWeighted Recall:\\t\",recall.evaluate(result),\"\\nWeighted Precision:\\t\",precision.evaluate(result))\n\nkafkaStream.foreachRDD(process)\n\n\nssc.start() # Start the computation\nssc.awaitTermination() # Wait for the computation to terminate\n","repo_name":"VishnuHarshith/CS4830-Big-Data-Lab-2020","sub_path":"lab_8_kafka.py","file_name":"lab_8_kafka.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"71709925535","text":"from gui.Scaleform.genConsts.BLOCKS_TOOLTIP_TYPES import BLOCKS_TOOLTIP_TYPES\nfrom gui.impl import backport\nfrom gui.impl.gen import R\nfrom gui.shared.formatters import text_styles\nfrom gui.shared.tooltips import TOOLTIP_TYPE\nfrom gui.shared.tooltips import formatters\nfrom gui.shared.tooltips.common import BlocksTooltipData\nfrom helpers import dependency\nfrom items import vehicles\nfrom skeletons.gui.battle_session import IBattleSessionProvider\n\nclass BattleOptDeviceTooltipData(BlocksTooltipData):\n guiSessionProvider = dependency.descriptor(IBattleSessionProvider)\n\n def __init__(self, context):\n super(BattleOptDeviceTooltipData, self).__init__(context, TOOLTIP_TYPE.EQUIPMENT)\n self.item = None\n self._setContentMargin(top=0, left=0, bottom=20, right=20)\n self._setMargins(10, 15)\n self._setWidth(400)\n return\n\n def _packBlocks(self, itemCD, itemStatus):\n items = super(BattleOptDeviceTooltipData, self)._packBlocks()\n _, _, deviceID = vehicles.parseIntCompactDescr(itemCD)\n itemInBattle = self.guiSessionProvider.shared.optionalDevices.getOptDeviceInBattle(deviceID)\n if not itemInBattle:\n return items\n descriptor = itemInBattle.getDescriptor()\n leftPadding = 20\n rightPadding = 20\n topPadding = 20\n battleDescr = R.strings.artefacts.dyn(descriptor.groupName).battle_descr\n if battleDescr:\n desc = backport.text(battleDescr())\n else:\n desc = descriptor.shortDescriptionSpecial.format(colorTagOpen='', colorTagClose='')\n items.append(formatters.packBuildUpBlockData([\n formatters.packTitleDescBlock(title=text_styles.middleTitle(backport.text(R.strings.artefacts.dyn(descriptor.tierlessName).name())), desc=text_styles.main(desc), padding=formatters.packPadding(bottom=-10))], padding=formatters.packPadding(left=leftPadding, right=rightPadding, top=topPadding)))\n battleStatuses = itemInBattle.getBattleStatus()\n for ind, statusStr in enumerate(battleStatuses):\n items.append(formatters.packBuildUpBlockData([\n formatters.packAlignedTextBlockData(text=statusStr, align=BLOCKS_TOOLTIP_TYPES.ALIGN_CENTER, padding=formatters.packPadding(bottom=-26 if ind + 1 != len(battleStatuses) else -10))]))\n\n return items","repo_name":"IzeBerg/wot-src","sub_path":"sources/res/scripts/client/gui/shared/tooltips/battle_opt_devices.py","file_name":"battle_opt_devices.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"33"} +{"seq_id":"30579100157","text":"import sys, os\nfrom collections import defaultdict\n\nPROG_NAME = 'ncc_convert'\nVERSION = '1.0.0'\nDESCRIPTION = 'Convert NCC format Hi-C contact files to other bioinformatics formats'\n\nFORMATS = set(['BED',])\nAVAIL_FORMATS = ', '.join(sorted(FORMATS))\n\ndef convert_ncc(ncc_in, out_fmt, report_freq=100000):\n \n from nuc_tools import util, io\n \n file_root, file_ext = os.path.splitext(ncc_in)\n file_ext = out_fmt.lower()\n \n file_out = f'{file_root}.{file_ext}' \n temp_file_out = file_out + '_ncc_conv_temp'\n \n group_sizes = defaultdict(int)\n \n out_file_obj = io.open_file(temp_file_out, 'w')\n write = out_file_obj.write\n \n mapq = 37\n \n with io.open_file(ncc_in) as in_file_obj:\n util.info(f'Reading {ncc_in}')\n \n for i, line in enumerate(in_file_obj):\n chr_a, f_start_a, f_end_a, start_a, end_a, strand_a, \\\n chr_b, f_start_b, f_end_b, start_b, end_b, strand_b, \\\n ambig_code, read_id, swap_pair = line.split()\n group_sizes[ambig_code] += 1\n read_name = f'READ_{int(read_id):010d}'\n \n if i % report_freq == 0:\n util.info(f' .. processed {i:,} NCC lines', line_return=True)\n \n if out_fmt == 'BED':\n write(f'{chr_a}\\t{start_a}\\t{end_a}\\t{read_name}/1\\t{mapq}\\t{strand_a}\\n')\n write(f'{chr_b}\\t{start_b}\\t{end_b}\\t{read_name}/2\\t{mapq}\\t{strand_b}\\n')\n \n util.info(f' .. processed {i:,} NCC lines', line_return=True)\n \n out_file_obj.close()\n \n util.info(f'Sorting output')\n \n cmd_args = ['sort','-k','4',temp_file_out]\n util.call(cmd_args, stdin=None, stdout=file_out, stderr=None, verbose=True, wait=True, path=None, shell=False)\n \n os.unlink(temp_file_out)\n \n util.info('Converted {:,} input lines to file {}, corresponding to {:,} ambiguity/read groups'.format(i+1, file_out, len(group_sizes)))\n \n\ndef main(argv=None):\n \n from argparse import ArgumentParser\n from nuc_tools import util, io\n\n if argv is None:\n argv = sys.argv[1:]\n \n epilog = 'For further help email tjs23@cam.ac.uk or wb104@cam.ac.uk'\n arg_parse = ArgumentParser(prog='nuc_tools ' + PROG_NAME, description=DESCRIPTION,\n epilog=epilog, prefix_chars='-', add_help=True)\n \n arg_parse.add_argument(nargs=1, metavar='IN_NCC_FILE', dest='i',\n help='Input NCC format file containing Hi-C contact data')\n\n arg_parse.add_argument(nargs=1, metavar='OUT_FORMAT', dest='f',\n help=f'Output file format to write reformatted contact data to. Must be one of {AVAIL_FORMATS}.')\n\n args = vars(arg_parse.parse_args(argv))\n \n ncc_in = args['i'][0]\n out_fmt = args['f'][0]\n \n invalid_msg = io.check_invalid_file(ncc_in)\n \n if invalid_msg:\n util.critical(invalid_msg)\n \n out_fmt = out_fmt.upper()\n \n if out_fmt not in FORMATS:\n util.critical(f'Output format {out_fmt} is not one of {AVAIL_FORMATS}')\n \n convert_ncc(ncc_in, out_fmt)\n \n \nif __name__ == '__main__':\n\n sys.path.append(os.path.dirname(os.path.dirname(__file__)))\n \n main()\n\n\n#/data/old/nucleus/processing/nuc_processing/paper_ncc/P2J8.ncc\n","repo_name":"tjs23/nuc_tools","sub_path":"tools/ncc_convert.py","file_name":"ncc_convert.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"16903624452","text":"#!/usr/bin/python3\n\"\"\"\nAprès avoir tracer la plateforme, les salles et les couloirs\nnous allons manipuler le personnage, son affichage et son déplacement\n\"\"\"\nfrom point import Point\nfrom salle import Salle\nimport os\nimport curses\n\n\nclass Personnage(Point):\n def __init__(self):\n self.pers = '@'\n\n def afficher_personnage(self, salle, plateforme):\n '''\n Afficher le caractère @ dans la liste\n qui représentera le personnage.\n '''\n plateforme[salle.y][salle.x] = self.pers\n self.x = salle.x\n self.y = salle.y\n return plateforme\n\n def verification_deplacement(self, p, L):\n '''\n Méthode qui assure l'existence d'une position p\n à l'intérieur de la zone de jeu L\n et que la position ne coïncide pas avec\n un mur.\n p = position possible du personnage\n '''\n return (p.x > len(L[0])) or (p.x < 0) or (p.y < 0) or (p.y > len(L)) or (L[p.y][p.x] == 'I')\n\n def deplacement(self, c, L):\n '''\n Méthode qui contrôle le déplacement\n du personnage dans la zone du jeu L\n c = une chaîne de caractère qui prend les\n valeurs (G, D, H, B, Q)\n Si le déplacement est impossible, la méthode\n ne retourne rien, et si l'utilisateur choisit\n Q (Quitter), on quitte le jeu.\n '''\n x, y = self.x, self.y\n haut = Point(x, y-1)\n droite = Point(x+1, y)\n bas = Point(x, y+1)\n gauche = Point(x-1, y)\n if c == curses.KEY_UP and not(self.verification_deplacement(haut, L)):\n L[y][x], L[y-1][x] = ' ', self.pers\n self.x, self.y = x, y-1\n return L\n elif c == curses.KEY_RIGHT and not(self.verification_deplacement(droite, L)):\n L[y][x], L[y][x+1] = ' ', self.pers\n self.x, self.y = x+1, y\n return L\n elif c == curses.KEY_DOWN and not(self.verification_deplacement(bas, L)):\n L[y][x], L[y+1][x] = ' ', self.pers\n self.x, self.y = x, y+1\n return L\n elif c == curses.KEY_LEFT and not(self.verification_deplacement(gauche, L)):\n L[y][x], L[y][x-1] = ' ', self.pers\n self.x, self.y = x-1, y\n return L\n elif c == 27:\n os._exit(1)\n else:\n return None\n\n\nif __name__ == '__main__':\n print(9)\n","repo_name":"elouatih/pyhack_python","sub_path":"Pyhack_Python/personnage.py","file_name":"personnage.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"22890507184","text":"write_style = ['w']\ndescriptions = 'The ASCII matrix of the ciphertext is multiplied by the inverse of the key matrix to obtain the ASCII matrix of the plaintext, which is then converted from ASCII to characters to decrypt the plaintext.'\n\n\ndef decrypt(self):\n mat_decrypt = self.filedialog.askopenfilename(title='Choose key file',\n filetypes=((\"All files\",\n \"*\"), ))\n if mat_decrypt:\n with open(mat_decrypt, encoding='utf-8') as f:\n data = f.read()\n if not (data[0] == '(' and data[-1] == ')'):\n self.current_msg.configure(text='Incorrect key file format')\n return\n mat_list, overflow = eval(data)\n mat_size = int(len(mat_list)**(1 / 2))\n length = mat_size**2\n mat_decrypt = form(mat_list, mat_size, mat_size)\n whole_file_size = os.path.getsize(self.choose_filename_path)\n convert_times = whole_file_size // length\n with open(self.choose_filename_path,\n encoding=decrypt_file_format,\n errors=errors_settings) as f, open(self.filenames[0],\n 'w',\n encoding='utf-8',\n errors='ignore') as file:\n for i in range(convert_times):\n text = f.read(length)\n if not text:\n if overflow != 0:\n file.seek(file.tell() - overflow, os.SEEK_SET)\n file.truncate()\n self.current_msg.configure(text='decrypt progress: 100 %')\n self.current_msg.update()\n break\n current = decrypt2(text, mat_decrypt, mat_size)\n file.write(current)\n self.current_msg.configure(\n text=\n f'decrypt progress: {round(((i+1)/convert_times)*100, 3)} %'\n )\n self.current_msg.update()\n self.current_msg.configure(\n text=f'Decrypt successfully, saved at {self.filenames[0]}')\n\n\ndef decrypt2(text, mat, sizes):\n text_list = [ord(i) for i in text]\n text_mat = form(text_list, sizes, sizes)\n decrypt_mat = (text_mat * mat.inv_lu()).formated()\n decrypt_mat_element = decrypt_mat.element()\n return ''.join([chr(x) for x in decrypt_mat_element])","repo_name":"Rainbow-Dreamer/matrix-encrypt","sub_path":"scripts/decrypt_1.py","file_name":"decrypt_1.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"7932377695","text":"import functools\nfrom functools import total_ordering\n\nimport sys\n\n###############################################################################\n# Classes\n###############################################################################\n\n# abstracts a list into a priority queue\nclass Priorityq:\n def __init__(self):\n self.q = list()\n\n def __repr__(self):\n return str(self.q)\n\n def __bool__(self):\n return len(self.q) != 0\n\n def dequeue(self):\n return self.q.pop(0)\n\n def queue(self, item):\n self.q.append(item)\n self.q.sort() # might not the most efficient, but...\n\n# information contained by each vertex\nclass Vertex:\n def __init__(self, coordinates, height, dist = float('inf')):\n self.coordinates = coordinates\n self.dist = dist\n self.visited = False\n self.height = height\n\n def __lt__(self, obj):\n return self.dist < obj.dist\n\n def __repr__(self):\n return str([self.coordinates, self.height, self.dist])\n\n# information contained about the vertices and edges of the graph\nclass Graph:\n def __init__(self):\n self.g = []\n self.start = tuple()\n self.end = tuple()\n self.lookup = {}\n\n def __repr__(self):\n s = str()\n delim = ''\n for i in self.g:\n s += delim + str(i)\n delim = '\\n'\n return s\n\n def at(self, coordinates):\n return self.g[coordinates[0]][coordinates[1]]\n\n def shape(self):\n return len(self.g), len(self.g[0])\n\n def reset(self):\n for v in self.lookup.values():\n # account for out of bound coordinates that were set to false\n if v:\n v.visited = False\n v.dist = float('inf')\n\n###############################################################################\n# Functions\n###############################################################################\n\n# dijkstra's shortest path algorithm\ndef dijkstra(graph, start):\n current = start\n current.dist = 0\n pq = Priorityq()\n pq.queue(current)\n\n while pq:\n current = pq.dequeue()\n reachable(graph, current, pq)\n current.visited = True\n graph.g[current.coordinates[0]][current.coordinates[1]] = str(current.dist)\n\n# updates the priority queue based on reachable vertices from the current vertex\ndef reachable(graph, vertex, priorityq):\n surroundings = ((1,0), (-1,0), (0, -1), (0, 1))\n for k in surroundings:\n temp = [x + y for x,y in zip(vertex.coordinates, k)]\n next = graph.lookup.setdefault(tuple(temp), False)\n \n if next and not(next.visited) and next.height <= (vertex.height + 1) \\\n and (vertex.dist + 1) < next.dist:\n next.dist = vertex.dist + 1\n priorityq.queue(next) \n\n###############################################################################\n# Implementation\n###############################################################################\n\ninfile = open('input.txt', 'r')\n\ngraph = Graph()\nline = []\n[i, j] = [0, 0] # starting values for coordinates\n\n# for part 2\npart2 = False\nstarts = list() \nends = list()\n\n# for command line arguments (part1 or part2)\nif len(sys.argv) == 1:\n part2 = False\nelse:\n test = {'part1' : False, 'part2' : True}\n part2 = test.setdefault(sys.argv[1], False)\n\nch = infile.read(1)\n\n# build graph\nwhile ch:\n line.append(ch)\n v = Vertex((i, j), 0)\n\n # set height of vertex based on character\n if ch == 'S':\n graph.start = graph.lookup[tuple([i,j])] = v\n elif ch == 'E':\n graph.end = graph.lookup[tuple([i,j])] = v\n v.height = 25\n else:\n graph.lookup[tuple([i,j])] = v\n v.height = ord(ch) - ord('a')\n\n if v.height == 0:\n starts.append(v)\n\n j += 1\n ch = infile.read(1)\n\n # if we have reached the end of the line or eof:\n if ch == '\\n' or ch == '':\n graph.g.append(line)\n ch = infile.read(1)\n line = []\n \n i += 1\n j = 0\n\n# if part 2, run dijkstra on every starting value,\n# else just on 'S'\nif part2:\n for s in starts:\n dijkstra(graph, s)\n ends.append(graph.end.dist)\n graph.reset()\n\n print(min(ends))\nelse:\n dijkstra(graph, graph.start)\n print(graph.end.dist) \n\ninfile.close","repo_name":"bryceForrest/Advent_of_Code_2022","sub_path":"day12/day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":4331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"11268561423","text":"from ftplib import FTP\nfrom data import direction\nfrom sql import get_contracts_numbers\n\n\ndef ftp_connect():\n \"\"\"Функция подключения к FTP госзакупок\n :return: Возвращает соединение\"\"\"\n ftp = False\n for i in range(0, 5):\n try:\n ftp = FTP(host='ftp.zakupki.gov.ru', user='free', passwd='free') # Устанавливаем соединение\n break\n except Exception as e:\n text = f'Неудачная попытка соединения #{i+1}\\n{e}'\n print(text)\n with open(direction + 'logs/log.txt', 'a') as reg:\n reg.write(text)\n continue\n return ftp\n\n\ndef ftp_cwd(ftp, dir):\n \"\"\"Функция получения списка файлов и папок в директории на FTP\n :param ftp: FTP-соединение\n :param dir: Директория, из которой нужно получить список файлов и папок\n :return: Возвращает список файлов и папок\"\"\"\n ftp.cwd(dir) # Переходим в нужную директорию\n return ftp.nlst()\n\n\ndef ftp_list_of_download(ftp, server_files, local_files):\n \"\"\"Функция создания списка незагруженных файлов\n :param ftp: FTP-соединение\n :param server_files: Файлы на сервере\n :param local_files: Файлы скачанные\n :return: Возвращает список файлов для скачивания\"\"\"\n list_files = set()\n files = dict()\n for file in local_files:\n if f'currMonth/{file}' in server_files:\n files[f'currMonth/{file}'] = local_files[file]\n elif f'prevMonth/{file}' in server_files:\n files[f'prevMonth/{file}'] = local_files[file]\n elif file in server_files:\n files[file] = local_files[file]\n for file in files:\n try:\n size = ftp.size(file)\n if size == files[file]:\n list_files.add(file)\n except:\n continue\n return server_files - list_files\n\n\ndef ftp_list_of_new(server_files, table_name, region_name):\n \"\"\"Функция создания списка новых файлов\n :param server_files: Файлы на сервере\n :param table_name: Название SQL таблицы\n :return: Возвращает список файлов для скачивания\"\"\"\n oldest_archive = ''\n new_list_files = []\n contract_numbers = get_contracts_numbers(table_name, region_name)\n for contract in contract_numbers:\n tmp_data = contract_numbers[contract]['Название_архива']\n if oldest_archive < tmp_data:\n oldest_archive = tmp_data\n if not oldest_archive:\n return server_files\n publish_date = oldest_archive.split('/')[-1]\n for archive in server_files:\n if publish_date < archive.replace('prevMonth/', '').replace('currMonth/', ''):\n new_list_files.append(archive)\n return new_list_files\n\n\ndef ftp_list_of_new_temp(server_files, table_name, region_name):\n \"\"\"Функция создания списка новых файлов\n :param server_files: Файлы на сервере\n :param table_name: Название SQL таблицы\n :return: Возвращает список файлов для скачивания\"\"\"\n oldest_archive = []\n new_list_files = []\n contract_numbers = get_contracts_numbers(table_name, region_name) # те что на sql строчки\n for contract in contract_numbers:\n try:\n tmp = contract_numbers[contract]['Название_архива'].split('/')[-1]\n if tmp in oldest_archive:\n continue\n oldest_archive.append(tmp) # список sql отработанных архивов\n except Exception as e:\n print(f'{e}\\n{contract_numbers[contract]}')\n continue\n print(len(oldest_archive))\n print(oldest_archive)\n for idx, archive in enumerate(server_files): # Пройтись по всем файлам с госзакупок\n tmp_file = archive.replace('prevMonth/', '').replace('currMonth/', '') #\n if tmp_file not in oldest_archive and tmp_file not in new_list_files:\n new_list_files.append(archive)\n return new_list_files\n\n\ndef ftp_download(ftp, file, path_tmp=direction + 'tmp/'):\n \"\"\"Функция скачивания файла с FTP\n :param ftp: FTP-соединение\n :param file: Путь до файла, относительно текущей директории (устонавливается перед запуском функции)\n :param path_tmp: Расположение временой папки\n :return: Возвращает путь до файла во временной папке\"\"\"\n # Дописываем в путь дополнительные префиксы при наличии вложенных папок\n if 'currMonth/' in file or 'prevMonth/' in file:\n file_to = file.split('/')[1]\n else:\n file_to = file\n\n # Сохраняем файл на сервере\n with open(path_tmp + file_to, \"wb\") as f:\n ftp.retrbinary(\"RETR \" + file, f.write)\n\n return path_tmp + file_to\n\n\ndef ftp_make_list_files(ftp, reg):\n \"\"\"Функция создания списка скачиваемых файлов\n :param ftp: FTP-соединение\n :param reg: Название региона\n :return: Возвращает список файлов для скачивания\"\"\"\n try:\n list_files = []\n\n # Переходим в папку с текущим регионом и получаем список архивов\n file_list_curr = ftp_cwd(ftp, '/fcs_regions/' + reg + '/contracts/currMonth')\n file_list_prev = ftp_cwd(ftp, '/fcs_regions/' + reg + '/contracts/prevMonth')\n file_list = ftp_cwd(ftp, '/fcs_regions/' + reg + '/contracts')\n for file in range(len(file_list_curr)):\n file_list_curr[file] = 'currMonth/' + file_list_curr[file]\n\n for file in range(len(file_list_prev)):\n if file_list_prev[file] in file_list:\n del file_list_prev[file]\n else:\n file_list_prev[file] = 'prevMonth/' + file_list_prev[file]\n\n file_list.remove('currMonth')\n file_list.remove('prevMonth')\n\n file_list += file_list_curr + file_list_prev\n del file_list_prev\n del file_list_curr\n for file in file_list:\n # Пропускаем все архивы, кроме 2021 года и более\n year = file.replace('prevMonth/', '').replace('currMonth/', '').replace('contract_', '').replace(\n 'control99doc_', '').replace(reg + '_', '').split('_')[0][:4]\n if year.isdigit():\n year = int(year)\n if year != 2022:\n continue\n list_files.append(file)\n return list_files\n except Exception as error:\n with open(direction + 'logs/error.txt', 'a') as log:\n log.write(f'Error of making a list (ftp)\\n{reg}\\n{error}\\n\\n')\n","repo_name":"zarossa/test_tasks","sub_path":"_2022_10_IR2000/ftp.py","file_name":"ftp.py","file_ext":"py","file_size_in_byte":7323,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"22607478837","text":"from itertools import groupby\n\n\ndef repeating_fractions(numerator, denominator):\n integer, fractional = str(numerator / float(denominator)).split('.')\n grouped = []\n for k, g in groupby(fractional):\n try:\n next(g)\n next(g)\n grouped.append('({})'.format(k))\n except StopIteration:\n grouped.append(k)\n return '{}.{}'.format(integer, ''.join(grouped))\n","repo_name":"the-zebulan/CodeWars","sub_path":"katas/kyu_6/group_repeating_fractions.py","file_name":"group_repeating_fractions.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"33"} +{"seq_id":"38195197719","text":"import pytest\nfrom .pages.main_page import MainPage\nfrom .pages.login_page import LoginPage\nfrom .pages.basket_page import BasketPage\n\nlink = \"http://selenium1py.pythonanywhere.com\"\n\n\n@pytest.mark.login_quest\nclass TestLoginFromMainPage:\n\n @pytest.mark.skip\n def test_guest_can_go_to_login_page(self, browser):\n page = MainPage(browser, link)\n page.open()\n page.go_to_login_page()\n login_page = LoginPage(browser, browser.current_url)\n login_page.should_be_login_page()\n\n @pytest.mark.skip\n def test_guest_should_see_login_link(self, browser):\n page = MainPage(browser, link)\n page.open()\n page.should_be_login_link()\n\n\ndef test_guest_cant_see_product_in_basket_opened_from_main_page(browser):\n page = MainPage(browser, link)\n page.open()\n page.go_to_basket_page()\n basket_page = BasketPage(browser, browser.current_url)\n basket_page.should_be_no_product_in_cart()\n basket_page.should_be_empty_cart_message()\n","repo_name":"pehom/stepik_autotest_4","sub_path":"test_main_page.py","file_name":"test_main_page.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"25520802813","text":"import yaml\nimport os\nimport os.path\nimport pickle\n\nimport torch\n\ndef load_blunder_model_config(config_dir_path):\n with open(os.path.join(config_dir_path, 'config.yaml')) as f:\n config = yaml.safe_load(f.read())\n if config['engine'] == 'sklearn':\n weightsPath = os.path.join(config_dir_path, config['options']['weightsPath'])\n with open(weightsPath, 'rb') as f:\n model = pickle.load(f)\n elif config['engine'] == 'torch':\n weightsPath = os.path.join(config_dir_path, config['options']['weightsPath'])\n model = torch.load(weightsPath)\n else:\n raise NotImplementedError(f\"{config['engine']} is not a known engine type\")\n return model, config\n","repo_name":"CSSLab/maia-chess","sub_path":"blunder_prediction/maia_chess_backend/torch/model_loader.py","file_name":"model_loader.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":833,"dataset":"github-code","pt":"33"} +{"seq_id":"37604266592","text":"from copy import deepcopy\n\nfrom library_analyzer.processing.annotations.model import (\n AbstractAnnotation,\n DescriptionAnnotation,\n EnumReviewResult,\n TodoAnnotation,\n)\nfrom library_analyzer.processing.api.model import Attribute, Parameter, Result\nfrom library_analyzer.processing.migration.model import (\n Mapping,\n)\n\nfrom ._constants import migration_author\nfrom ._get_annotated_api_element import get_annotated_api_element\nfrom ._get_migration_text import get_migration_text\n\n\ndef migrate_description_annotation(\n origin_annotation: DescriptionAnnotation,\n mapping: Mapping,\n) -> list[AbstractAnnotation]:\n description_annotation = deepcopy(origin_annotation)\n authors = description_annotation.authors\n authors.append(migration_author)\n description_annotation.authors = authors\n\n annotated_apiv1_element = get_annotated_api_element(description_annotation, mapping.get_apiv1_elements())\n if annotated_apiv1_element is None:\n return []\n\n description_annotations: list[AbstractAnnotation] = []\n for element in mapping.get_apiv2_elements():\n if isinstance(element, type(annotated_apiv1_element)) and not isinstance(element, Attribute | Result):\n documentationv1 = (\n annotated_apiv1_element.docstring.description\n if isinstance(element, Parameter)\n else element.docstring.full_docstring\n )\n documentationv2 = (\n element.docstring.description if isinstance(element, Parameter) else element.docstring.full_docstring\n )\n if documentationv1 != documentationv2 and documentationv2 != description_annotation.newDescription:\n description_annotations.append(\n DescriptionAnnotation(\n element.id,\n authors,\n description_annotation.reviewers,\n description_annotation.comment,\n EnumReviewResult.UNSURE,\n newDescription=description_annotation.newDescription,\n ),\n )\n continue\n description_annotations.append(\n DescriptionAnnotation(\n element.id,\n authors,\n description_annotation.reviewers,\n description_annotation.comment,\n EnumReviewResult.NONE,\n newDescription=description_annotation.newDescription,\n ),\n )\n elif not isinstance(element, Attribute | Result):\n description_annotations.append(\n TodoAnnotation(\n element.id,\n authors,\n description_annotation.reviewers,\n description_annotation.comment,\n EnumReviewResult.NONE,\n get_migration_text(description_annotation, mapping, for_todo_annotation=True),\n ),\n )\n return description_annotations\n","repo_name":"Safe-DS/Library-Analyzer","sub_path":"src/library_analyzer/processing/migration/annotations/_migrate_description_annotation.py","file_name":"_migrate_description_annotation.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"33"} +{"seq_id":"75244373215","text":"'''\r\nAuthor : Artur Assis Alves\r\nDate : 10/05/2020\r\nTitle : Question 10\r\n'''\r\nimport sys\r\n\r\n#Decorators:\r\ndef debugging(f):\r\n ''' Decorator that shows the line and the arguments of the function which is being debugged. '''\r\n def decorator_function(*args, **kwargs):\r\n linenum = sys._getframe(1).f_lineno # Get the caller's line number.\r\n print('Calling '+f.__name__+' at line '+str(linenum)+' with input :'+str(args)+ ' and '+str(kwargs))\r\n return f(*args, **kwargs)\r\n return decorator_function\r\n\r\ndef is_integer(f):\r\n ''' Decorator that verifies if the arguments of a function are integer. If they are not, it returns None. '''\r\n def decorator_function(*args, **kwargs):\r\n for i in args:\r\n if not(isinstance(i, int)):\r\n print('The arguments must be integers.')\r\n return None\r\n for i in kwargs:\r\n if not(isinstance(i, int)):\r\n print('The arguments must be integers.')\r\n return None\r\n return f(*args, **kwargs)\r\n return decorator_function\r\n\r\n#Methods\r\n@debugging\r\ndef adder(*args):\r\n result = 0\r\n for i in args:\r\n result += i\r\n return result\r\n\r\n@is_integer\r\ndef integer_adder(*args):\r\n result = 0\r\n for i in args:\r\n result += i\r\n return result\r\n \r\n#Main:\r\nif __name__=='__main__':\r\n print('1+2+3 = {}\\n'.format(adder(1, 2, 3)))\r\n print('2+3.5 = {}\\n'.format(adder(2, 3.5)))\r\n\r\n print('1+2+3 = {}\\n'.format(integer_adder(1, 2, 3)))\r\n print('2+3.5 = {}\\n'.format(integer_adder(2, 3.5)))\r\n \r\n","repo_name":"ArturAssisComp/ITA","sub_path":"ces22(POO)/Lista2/Question10.py","file_name":"Question10.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"39468487606","text":"#!/usr/bin/env python3\n\"\"\"\nPython OpenGL practical application.\n\"\"\"\n# Python built-in modules\nimport os # os function, i.e. checking file status\nfrom itertools import cycle\nimport sys\n\n# External, non built-in modules\nimport OpenGL.GL as GL # standard Python OpenGL wrapper\nimport glfw # lean window system wrapper for OpenGL\nimport numpy as np # all matrix manipulations & OpenGL args\nimport pyassimp # 3D resource loader\nimport pyassimp.errors # Assimp error management + exceptions\n\nfrom mesh import *\nfrom shader import *\n\nfrom transform import Trackball, identity, translate, rotate, scale, lerp, vec\nfrom transform import (quaternion_slerp, quaternion_matrix, quaternion,\n quaternion_from_euler)\nfrom bisect import bisect_left\nfrom itertools import cycle\n\nfrom space import SystemeSolaire\nfrom node import Node\nfrom projectile import *\nfrom skybox import *\nfrom particlesbis import *\n\n# ------------ low level OpenGL object wrappers ----------------------------\n\n\n# -------------- OpenGL Texture Wrapper ---------------------------------------\n\n\n\n# ------------ simple color fragment shader demonstrated in Practical 1 ------\nCOLOR_VERT = \"\"\"#version 330 core\nlayout(location = 0) in vec3 position;\nlayout(location = 1) in vec3 normal;\n\n\nuniform mat4 model; \nuniform mat4 view;\nuniform mat4 projection;\n\n\nuniform mat3 transinvmod;\n\nout vec3 monde_normal;\nout vec4 positionFrag;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1);\n monde_normal = transinvmod * normal;\n positionFrag = vec4(position, 1);\n}\"\"\"\n\nCOLOR_FRAG = \"\"\"#version 330 core\n\nin vec3 monde_normal;\nin vec4 positionFrag;\nuniform mat4 invview;\n\nuniform vec3 lightDirection;\n\nuniform vec3 color;\nuniform vec3 Ks;\nuniform vec3 Ka;\nuniform float s;\n\nout vec4 outColor;\n\nvec3 colorFinal;\nvec3 v;\n\nvoid main() {\n float scalarProduct=dot(normalize(monde_normal),\n normalize(lightDirection));\n if(scalarProduct < 0){\n scalarProduct = 0.;\n }\n v = -vec3(invview*positionFrag);\n float scalar_product2 = dot(reflect(normalize(lightDirection),\n normalize(monde_normal)),normalize(v));\n if(scalar_product2 < 0){\n scalar_product2 = 0;\n }\n colorFinal = Ka + color*scalarProduct +\n Ks*pow(scalar_product2,s);\n outColor = vec4(colorFinal,1);\n}\"\"\"\n\n# -------------- Skybox texture shaders ---------------------------------------\nTEXTURE_SKYBOX_VERT = \"\"\"#version 330 core\nuniform mat4 viewprojection;\nlayout(location = 0) in vec3 position;\nout vec3 fragTexCoord;\n\nvoid main() {\n gl_Position = viewprojection * vec4(position, 1);\n // fragTexCoord = position.xy;\n fragTexCoord = position;\n}\"\"\"\n\nTEXTURE_SKYBOX_FRAG = \"\"\"#version 330 core\nuniform samplerCube skybox; // each such OpenGL sampler is meant to be associated to an active texture unit\nin vec3 fragTexCoord;\nout vec4 outColor;\nvoid main() {\n // access the texture and retrieve an RGBA color from it\n // (automatically filtered/interpolated according to the parameters passed at initialization)\n // a set of texture coordinates is passed in [0,1]^2 (vec2 type) to address which texel is retrieved\n outColor = texture(skybox, fragTexCoord); \n}\"\"\"\n\n# -------------- Particle texture shaders -------------------------------------\nTEXTURE_PARTICLE_VERT = \"\"\"#version 330 core\n\nuniform mat4 projection;\nuniform vec2 offset;\nuniform vec4 color;\n\nlayout(location = 0) in vec2 position;\nlayout(location = 1) in vec2 texCoords;\n\nout vec2 fragTexCoord;\nout vec4 particleColor;\n\nvoid main() {\n float scale = 10.0f;\n gl_Position = projection * vec4((position * scale) + offset, 0.0, 1.0);\n particleColor = color;\n fragTexCoord = texCoords;\n}\"\"\"\n\nTEXTURE_PARTICLE_FRAG = \"\"\"#version 330 core\nuniform sampler2D sprite;\n\nin vec2 fragTexCoord;\nin vec4 particleColor;\nout vec4 outColor;\n\nvoid main() {\n outColor = (texture(sprite, fragTexCoord) * particleColor);\n}\"\"\"\n\n\n\n\n\n# ------------ Scene object classes ------------------------------------------\n\n\n\n\n\n\n\n\nclass Cylinder(Node):\n \"\"\" Very simple cylinder based on practical 2 load function \"\"\"\n def __init__(self):\n super().__init__()\n self.add(*load('cylinder.obj')) # just load the cylinder from file\n\n\n\n\n\n\n\n\n\n\n# ------------ Viewer class & window management ------------------------------\nclass GLFWTrackball(Trackball):\n \"\"\" Use in Viewer for interactive viewpoint control \"\"\"\n\n def __init__(self, win):\n \"\"\" Init needs a GLFW window handler 'win' to register callbacks \"\"\"\n super().__init__()\n self.mouse = (0, 0)\n glfw.set_cursor_pos_callback(win, self.on_mouse_move)\n glfw.set_scroll_callback(win, self.on_scroll)\n\n def on_mouse_move(self, win, xpos, ypos):\n \"\"\" Rotate on left-click & drag, pan on right-click & drag \"\"\"\n old = self.mouse\n self.mouse = (xpos, glfw.get_window_size(win)[1] - ypos)\n if glfw.get_mouse_button(win, glfw.MOUSE_BUTTON_LEFT):\n self.drag(old, self.mouse, glfw.get_window_size(win))\n if glfw.get_mouse_button(win, glfw.MOUSE_BUTTON_RIGHT):\n self.pan(old, self.mouse)\n\n def on_scroll(self, win, _deltax, deltay):\n \"\"\" Scroll controls the camera distance to trackball center \"\"\"\n self.zoom(deltay, glfw.get_window_size(win)[1])\n\n\nclass Viewer:\n \"\"\" GLFW viewer window, with classic initialization & graphics loop \"\"\"\n\n def __init__(self, width=640, height=480):\n\n # version hints: create GL window with >= OpenGL 3.3 and core profile\n glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)\n glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)\n glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL.GL_TRUE)\n glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)\n glfw.window_hint(glfw.RESIZABLE, False)\n self.win = glfw.create_window(width, height, 'Viewer', None, None)\n\n # make win's OpenGL context current; no OpenGL calls can happen before\n glfw.make_context_current(self.win)\n\n # register event handlers\n glfw.set_key_callback(self.win, self.on_key)\n\n # useful message to check OpenGL renderer characteristics\n print('OpenGL', GL.glGetString(GL.GL_VERSION).decode() + ', GLSL',\n GL.glGetString(GL.GL_SHADING_LANGUAGE_VERSION).decode() +\n ', Renderer', GL.glGetString(GL.GL_RENDERER).decode())\n\n # initialize GL by setting viewport and default render characteristics\n GL.glClearColor(0.1, 0.1, 0.1, 0.1)\n GL.glEnable(GL.GL_DEPTH_TEST) # depth test now enabled (TP2)\n GL.glEnable(GL.GL_CULL_FACE) # backface culling enabled (TP2)\n\n # compile and initialize shader programs once globally\n self.color_shader = Shader(COLOR_VERT, COLOR_FRAG)\n self.texture_shader_skybox = Shader(TEXTURE_SKYBOX_VERT, TEXTURE_SKYBOX_FRAG)\n self.texture_shader_particle = Shader(TEXTURE_PARTICLE_VERT, TEXTURE_PARTICLE_FRAG)\n\n # initially empty list of object to draw\n self.drawables = []\n\n # initialize trackball\n self.trackball = GLFWTrackball(self.win)\n\n # cyclic iterator to easily toggle polygon rendering modes\n self.fill_modes = cycle([GL.GL_LINE, GL.GL_POINT, GL.GL_FILL])\n \n def run(self, lastFrame=0):\n \"\"\" Main render loop for this OpenGL window \"\"\"\n while not glfw.window_should_close(self.win):\n # clear draw buffer and depth buffer (<-TP2)\n GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)\n\n currentFrame = glfw.get_time()\n deltaTime = currentFrame - lastFrame\n lastFrame = currentFrame\n for d in self.drawables:\n if isinstance(d, ParticleGenerator):\n d.update(dt=deltaTime)\n\n winsize = glfw.get_window_size(self.win)\n view = self.trackball.view_matrix()\n projection = self.trackball.projection_matrix(winsize)\n\n # draw our scene objects\n for drawable in self.drawables:\n drawable.draw(projection, view, identity(),\n color_shader=self.color_shader,\n win=self.win,\n texture_shader_skybox=self.texture_shader_skybox, \n texture_shader_particle=self.texture_shader_particle)\n\n # flush render commands, and swap draw buffers\n glfw.swap_buffers(self.win)\n\n # Poll for and process events\n glfw.poll_events()\n\n def add(self, *drawables):\n \"\"\" add objects to draw in this window \"\"\"\n self.drawables.extend(drawables)\n\n def on_key(self, _win, key, _scancode, action, _mods):\n \"\"\" 'Q' or 'Escape' quits \"\"\"\n if action == glfw.PRESS or action == glfw.REPEAT:\n if key == glfw.KEY_ESCAPE or key == glfw.KEY_Q:\n glfw.set_window_should_close(self.win, True)\n if key == glfw.KEY_W:\n GL.glPolygonMode(GL.GL_FRONT_AND_BACK, next(self.fill_modes))\n if key == glfw.KEY_SPACE: glfw.set_time(0)\n\n\n# -------------- main program and scene setup --------------------------------\ndef main():\n \"\"\" create a window, add scene objects, then run rendering loop \"\"\"\n viewer = Viewer()\n\n file = [\"ame_nebula/right.tga\", \"ame_nebula/left.tga\", \"ame_nebula/top.tga\", \n \"ame_nebula/bottom.tga\", \"ame_nebula/front.tga\", \"ame_nebula/back.tga\"]\n viewer.add(Skybox(file=file))\n\n particles = ParticleGenerator(file=\"particle/p.png\")\n viewer.add(particles)\n\n system = SystemeSolaire()\n viewer.add(system)\n viewer.run()\n\n\nif __name__ == '__main__':\n glfw.init() # initialize window system glfw\n main() # main function keeps variables locally scoped\n glfw.terminate() # destroy all glfw windows and GL contexts\n\n\n","repo_name":"Sylfid/Graphique3D","sub_path":"viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":10004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"28915948479","text":"from django.template import RequestContext\nfrom django.shortcuts import render_to_response\nfrom stratosource.models import Repo, Branch, Commit, Delta, TranslationDelta\n\n\n\ndef repos(request):\n data = {'repos': Repo.objects.all() }\n return render_to_response('repos.html', data)\n\ndef branches(request, repo_id):\n repo = Repo.objects.get(id=repo_id)\n branches = Branch.objects.filter(repo=repo)\n data = {'repo': repo, 'branches':branches }\n return render_to_response('branches.html', data)\n\ndef commits(request, branch_id):\n branch = Branch.objects.get(id=branch_id)\n commits = Commit.objects.filter(branch=branch).order_by('-date_added')\n\n for commit in commits:\n adds = Delta.objects.filter(commit=commit,delta_type__exact='a').count() + \\\n TranslationDelta.objects.filter(commit=commit,delta_type__exact='a').count()\n dels = Delta.objects.filter(commit=commit,delta_type__exact='d').count() + \\\n TranslationDelta.objects.filter(commit=commit,delta_type__exact='d').count()\n updt = Delta.objects.filter(commit=commit,delta_type__exact='u').count() + \\\n TranslationDelta.objects.filter(commit=commit,delta_type__exact='u').count()\n commit.__dict__['adds'] = adds\n commit.__dict__['dels'] = dels\n commit.__dict__['updt'] = updt\n data = {'branch': branch, 'commits':commits }\n return render_to_response('commits.html', data)\n\ndef commit(request, commit_id):\n commit = Commit.objects.get(id=commit_id)\n deltas = Delta.objects.filter(commit=commit).order_by('object__type','object__filename','object__el_type','object__el_subtype','object__el_name','commit__date_added')\n data = {'commit': commit, 'deltas':deltas }\n for delta in deltas:\n delta.__dict__['type'] = delta.object.type\n delta.__dict__['filename'] = delta.object.filename\n delta.__dict__['el_name'] = delta.object.el_name\n return render_to_response('commit.html', data)\n\n","repo_name":"StratoSource/StratoSource","sub_path":"stratosource/admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"33"} +{"seq_id":"42157608153","text":"#!/usr/bin/env python\n\nimport unittest\nfrom dominion import Game, Card, Piles\n\n\nclass Card_Bureaucrat(Card.Card):\n def __init__(self):\n Card.Card.__init__(self)\n self.cardtype = [Card.CardType.ACTION, Card.CardType.ATTACK]\n self.base = Card.CardExpansion.DOMINION\n self.desc = \"\"\" Gain a Silver; put it on top of your deck. Each\n other player reveals a victory card from his hand and puts\n it on his deck (or reveals a hand with no victory cards)\"\"\"\n self.name = \"Bureaucrat\"\n self.cost = 4\n\n def special(self, game, player):\n player.gain_card(\"Silver\", \"topdeck\")\n player.output(\"Added silver to deck\")\n\n for pl in player.attack_victims():\n for card in pl.piles[Piles.HAND]:\n if card.isVictory():\n pl.reveal_card(card)\n pl.move_card(card, \"topdeck\")\n pl.output(\n f\"Moved {card.name} to deck due to Bureaucrat played by {player.name}\"\n )\n player.output(f\"Player {pl.name} moved a {card.name} to the top\")\n break\n else:\n player.output(f\"Player {pl.name} has no victory cards in hand\")\n\n\n###############################################################################\nclass TestBureaucrat(unittest.TestCase):\n def setUp(self):\n self.g = Game.TestGame(numplayers=2, initcards=[\"Bureaucrat\", \"Moat\"])\n self.g.start_game()\n self.plr, self.victim = self.g.player_list()\n self.bcard = self.g.get_card_from_pile(\"Bureaucrat\")\n self.plr.add_card(self.bcard, Piles.HAND)\n\n def test_hasvictory(self):\n self.victim.piles[Piles.HAND].set(\"Estate\", \"Copper\", \"Copper\")\n self.victim.piles[Piles.DECK].set(\"Silver\")\n self.plr.play_card(self.bcard)\n self.assertEqual(self.victim.piles[Piles.DECK][-1].name, \"Estate\")\n self.assertNotIn(\"Estate\", self.victim.piles[Piles.HAND])\n self.assertEqual(self.plr.piles[Piles.DECK][-1].name, \"Silver\")\n\n def test_novictory(self):\n self.victim.piles[Piles.HAND].set(\"Copper\", \"Copper\", \"Copper\")\n self.victim.piles[Piles.DECK].set(\"Province\")\n self.plr.piles[Piles.DECK].set(\"Province\")\n self.plr.play_card(self.bcard)\n self.assertEqual(self.victim.piles[Piles.DECK][-1].name, \"Province\")\n self.assertEqual(self.plr.piles[Piles.DECK][-1].name, \"Silver\")\n\n def test_defense(self):\n self.victim.piles[Piles.DECK].set(\"Province\")\n self.victim.piles[Piles.HAND].set(\"Estate\", \"Duchy\", \"Moat\")\n self.plr.play_card(self.bcard)\n self.assertEqual(self.plr.piles[Piles.DECK][-1].name, \"Silver\")\n self.assertEqual(self.victim.piles[Piles.DECK][-1].name, \"Province\")\n self.assertIn(\"Estate\", self.victim.piles[Piles.HAND])\n\n\n###############################################################################\nif __name__ == \"__main__\": # pragma: no cover\n unittest.main()\n\n# EOF\n","repo_name":"dwagon/pydominion","sub_path":"dominion/cards/Card_Bureaucrat.py","file_name":"Card_Bureaucrat.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"6581266011","text":"import argparse\nimport os\nimport platform\nimport subprocess\nimport tempfile\nfrom contextlib import contextmanager\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Iterator, List, Optional, Set\n\nfrom common import banner, die, green, travis_section\n\n\ndef main() -> None:\n banner(\"CI BEGINS\")\n\n args = create_parser().parse_args()\n setup_environment(python_version=args.python_version)\n\n if args.bootstrap:\n bootstrap(clean=args.bootstrap_clean, python_version=args.python_version)\n set_run_from_pex()\n\n if args.githooks:\n run_githooks()\n if args.sanity_checks:\n run_sanity_checks()\n if args.lint:\n run_lint()\n if args.doc_gen:\n run_doc_gen_tests()\n if args.clippy:\n run_clippy()\n if args.cargo_audit:\n run_cargo_audit()\n if args.python_tests_v1:\n run_python_tests_v1()\n if args.python_tests_v2:\n run_python_tests_v2(remote_execution_enabled=args.remote_execution_enabled)\n if args.rust_tests:\n run_rust_tests()\n if args.jvm_tests:\n run_jvm_tests()\n if args.integration_tests:\n run_integration_tests(shard=args.integration_shard)\n if args.plugin_tests:\n run_plugin_tests()\n if args.platform_specific_tests:\n run_platform_specific_tests()\n\n banner(\"CI ENDS\")\n print()\n green(\"SUCCESS\")\n\n# -------------------------------------------------------------------------\n# Options\n# -------------------------------------------------------------------------\n\nclass PythonVersion(Enum):\n py36 = \"3.6\"\n py37 = \"3.7\"\n\n def __str__(self) -> str:\n return str(self.value)\n\n\ndef create_parser() -> argparse.ArgumentParser:\n parser = argparse.ArgumentParser(description=\"Runs commons tests for local or hosted CI.\")\n parser.add_argument(\n \"--python-version\",\n type=PythonVersion,\n choices=list(PythonVersion),\n default=PythonVersion.py36,\n help=\"Run Pants with this version (defaults to 3.6).\"\n )\n parser.add_argument(\n \"--remote-execution-enabled\", action=\"store_true\",\n help=\"Pants will use remote build execution remote where possible (for now, the V2 unit tests). \"\n \"If running locally, you must be logged in via the `gcloud` CLI to an account with remote \"\n \"build execution permissions. If running in CI, the script will ping the secure token \"\n \"generator at https://github.com/pantsbuild/rbe-token-server.\"\n )\n parser.add_argument(\n \"--bootstrap\", action=\"store_true\", help=\"Bootstrap a pants.pex from local sources.\"\n )\n parser.add_argument(\n \"--bootstrap-clean\", action=\"store_true\",\n help=\"Before bootstrapping, clean the environment so that it's like a fresh git clone.\"\n )\n parser.add_argument(\"--githooks\", action=\"store_true\", help=\"Run pre-commit githook.\")\n parser.add_argument(\n \"--sanity-checks\", action=\"store_true\",\n help=\"Run sanity checks of bootstrapped Pants and repo BUILD files.\"\n )\n parser.add_argument(\"--lint\", action=\"store_true\", help=\"Run lint over whole codebase.\")\n parser.add_argument(\"--doc-gen\", action=\"store_true\", help=\"Run doc generation tests.\")\n parser.add_argument(\"--clippy\", action=\"store_true\", help=\"Run Clippy on Rust code.\")\n parser.add_argument(\n \"--cargo-audit\", action=\"store_true\", help=\"Run Cargo audit of Rust dependencies.\"\n )\n # TODO(#7772): Simplify below to always use V2 and drop the blacklist.\n parser.add_argument(\n \"--python-tests-v1\", action=\"store_true\",\n help=\"Run Python unit tests with V1 test runner over the blacklist and contrib tests.\"\n )\n parser.add_argument(\n \"--python-tests-v2\", action=\"store_true\",\n help=\"Run Python unit tests with V2 test runner.\"\n )\n parser.add_argument(\"--rust-tests\", action=\"store_true\", help=\"Run Rust tests.\")\n parser.add_argument(\"--jvm-tests\", action=\"store_true\", help=\"Run JVM tests.\")\n parser.add_argument(\n \"--integration-tests\", action=\"store_true\", help=\"Run Python integration tests.\"\n )\n parser.add_argument(\n \"--integration-shard\", metavar=\"SHARD_NUMBER/TOTAL_SHARDS\", default=None,\n help=\"Divide integration tests into TOTAL_SHARDS shards and just run those in SHARD_NUMBER. \"\n \"E.g. `-i 0/2` and `-i 1/2` will split the tests in half.\"\n )\n parser.add_argument(\"--plugin-tests\", action=\"store_true\", help=\"Run tests for pants-plugins.\")\n parser.add_argument(\n \"--platform-specific-tests\", action=\"store_true\", help=\"Test platform-specific behavior.\"\n )\n return parser\n\n# -------------------------------------------------------------------------\n# Set up the environment\n# -------------------------------------------------------------------------\n\ndef setup_environment(*, python_version: PythonVersion):\n set_cxx_compiler()\n set_pants_dev()\n setup_python_interpreter(python_version)\n\n\ndef set_pants_dev() -> None:\n \"\"\"We do this because we are running against a Pants clone.\"\"\"\n os.environ[\"PANTS_DEV\"] = \"1\"\n\n\ndef set_cxx_compiler() -> None:\n compiler = \"g++\" if platform.system() != \"Darwin\" else \"clang++\"\n os.environ[\"CXX\"] = compiler\n\n\ndef setup_python_interpreter(version: PythonVersion) -> None:\n if \"PY\" not in os.environ:\n os.environ[\"PY\"] = f\"python{version}\"\n constraints_env_var = \"PANTS_PYTHON_SETUP_INTERPRETER_CONSTRAINTS\"\n if constraints_env_var not in os.environ:\n os.environ[constraints_env_var] = f\"['CPython=={version}.*']\"\n banner(f\"Setting interpreter constraints to {os.environ[constraints_env_var]}\")\n\n\ndef set_run_from_pex() -> None:\n # We want all invocations of ./pants (apart from the bootstrapping one above) to delegate\n # to ./pants.pex, and not themselves attempt to bootstrap.\n # In this file we invoke ./pants.pex directly anyway, but some of those invocations will run\n # integration tests that shell out to `./pants`, so we set this env var for those cases.\n os.environ[\"RUN_PANTS_FROM_PEX\"] = \"1\"\n\n\n@contextmanager\ndef get_remote_execution_oauth_token_path() -> Iterator[str]:\n command = (\n [\"./pants.pex\", \"--quiet\", \"run\", \"build-support/bin:get_rbe_token\"]\n if os.getenv(\"CI\")\n else [\"gcloud\", \"auth\", \"application-default\", \"print-access-token\"]\n )\n token: str = subprocess.run(\n command, encoding=\"utf-8\", stdout=subprocess.PIPE, check=True\n ).stdout\n if not os.getenv(\"CI\"):\n token = token.splitlines()[0]\n with tempfile.NamedTemporaryFile(mode=\"w+\") as tf:\n tf.write(token)\n tf.seek(0)\n yield tf.name\n\n# -------------------------------------------------------------------------\n# Blacklists\n# -------------------------------------------------------------------------\n\ndef get_blacklisted_targets(filename: str) -> Set[str]:\n return {\n line.strip()\n for line in Path(f\"build-support/ci_blacklists/{filename}\").read_text().splitlines()\n }\n\n\ndef get_all_python_tests(*, tag: Optional[str] = None) -> Set[str]:\n command = [\n \"./pants.pex\",\n \"--filter-type=python_tests\",\n \"filter\",\n \"src/python::\",\n \"tests/python::\",\n \"contrib::\"\n ]\n if tag is not None:\n command.insert(1, f\"--tag={tag}\")\n return set(subprocess.run(\n command, stdout=subprocess.PIPE, encoding=\"utf-8\", check=True\n ).stdout.strip().split(\"\\n\"))\n\n# -------------------------------------------------------------------------\n# Bootstrap pants.pex\n# -------------------------------------------------------------------------\n\ndef bootstrap(*, clean: bool, python_version: PythonVersion) -> None:\n with travis_section(\"Bootstrap\", f\"Bootstrapping Pants as a Python {python_version} PEX\"):\n if clean:\n try:\n subprocess.run([\"./build-support/python/clean.sh\"], check=True)\n except subprocess.CalledProcessError:\n die(\"Failed to clean before bootstrapping Pants.\")\n\n try:\n subprocess.run([\"./pants\", \"binary\", \"src/python/pants/bin:pants_local_binary\"], check=True)\n Path(\"dist/pants_local_binary.pex\").rename(\"pants.pex\")\n subprocess.run([\"./pants.pex\", \"--version\"], check=True)\n except subprocess.CalledProcessError:\n die(\"Failed to bootstrap Pants.\")\n\n\ndef check_pants_pex_exists() -> None:\n if not Path(\"pants.pex\").is_file():\n die(\"pants.pex not found! Either run `./build-support/bin/ci.py --bootstrap` or check that \"\n \"AWS is properly downloading the uploaded `pants.pex`.\")\n\n# -------------------------------------------------------------------------\n# Test commands\n# -------------------------------------------------------------------------\n\n# We only want to output failures and skips.\n# See https://docs.pytest.org/en/latest/usage.html#detailed-summary-report.\nPYTEST_PASSTHRU_ARGS = [\"--\", \"-q\", \"-rfa\"]\n\n\ndef _run_command(\n command: List[str], *, slug: str, start_message: str, die_message: str, requires_pex: bool = True\n) -> None:\n with travis_section(slug, start_message):\n if requires_pex:\n check_pants_pex_exists()\n try:\n subprocess.run(command, check=True)\n except subprocess.CalledProcessError:\n die(die_message)\n\n\ndef run_githooks() -> None:\n _run_command(\n [\"./build-support/githooks/pre-commit\"],\n slug=\"PreCommit\",\n start_message=\"Running pre-commit checks\",\n die_message=\"Pre-commit checks failed.\"\n )\n\n\ndef run_sanity_checks() -> None:\n def run_check(command: List[str]) -> None:\n print(f\"* Executing `./pants.pex {' '.join(command)}` as a sanity check\")\n try:\n subprocess.run(\n [\"./pants.pex\"] + command,\n stdout=subprocess.DEVNULL,\n stderr=subprocess.STDOUT,\n check=True\n )\n except subprocess.CalledProcessError:\n die(f\"Failed to execute `./pants {command}`.\")\n\n checks = [\n [\"bash-completion\"],\n [\"reference\"],\n [\"clean-all\"],\n [\"goals\"],\n [\"list\", \"::\"],\n [\"roots\"],\n [\"targets\"]\n ]\n with travis_section(\"SanityCheck\", \"Sanity checking bootstrapped Pants and repo BUILD files\"):\n check_pants_pex_exists()\n for check in checks:\n run_check(check)\n\n\ndef run_lint() -> None:\n targets = [\"contrib::\", \"examples::\", \"src::\", \"tests::\", \"zinc::\"]\n _run_command(\n [\"./pants.pex\", \"--tag=-nolint\", \"lint\"] + targets,\n slug=\"Lint\",\n start_message=\"Running lint checks\",\n die_message=\"Lint check failure.\"\n )\n\n\ndef run_doc_gen_tests() -> None:\n _run_command(\n [\"build-support/bin/publish_docs.sh\"],\n slug=\"DocGen\",\n start_message=\"Running site doc generation test\",\n die_message=\"Failed to generate site docs.\"\n )\n\n\ndef run_clippy() -> None:\n _run_command(\n [\"build-support/bin/check_clippy.sh\"],\n slug=\"RustClippy\",\n start_message=\"Running Clippy on Rust code\",\n die_message=\"Clippy failure.\",\n requires_pex=False,\n )\n\n\ndef run_cargo_audit() -> None:\n with travis_section(\"CargoAudit\", \"Running Cargo audit on Rust code\"):\n try:\n subprocess.run([\n \"build-support/bin/native/cargo\",\n \"ensure-installed\",\n \"--package=cargo-audit\",\n \"--version=0.7.0\",\n ], check=True)\n subprocess.run([\n \"build-support/bin/native/cargo\",\n \"audit\",\n \"-f\", \"src/rust/engine/Cargo.lock\",\n # TODO(John Sirois): Kill --ignore RUSTSEC-2019-0003 when we can upgrade to an official\n # released version of protobuf with a fix.\n # See: https://github.com/pantsbuild/pants/issues/7760 for context.\n \"--ignore\", \"RUSTSEC-2019-0003\"\n ], check=True)\n except subprocess.CalledProcessError:\n die(\"Cargo audit failure\")\n\n\ndef run_python_tests_v1() -> None:\n check_pants_pex_exists()\n\n blacklisted_v2_targets = get_blacklisted_targets(\"unit_test_v2_blacklist.txt\")\n blacklisted_chroot_targets = get_blacklisted_targets(\"unit_test_chroot_blacklist.txt\")\n chrooted_targets = blacklisted_v2_targets - blacklisted_chroot_targets\n\n with travis_section(\"PythonTestsV1\", \"Running Python unit tests with V1 test runner\"):\n\n try:\n subprocess.run(\n [\"./pants.pex\", \"--test-pytest-chroot\", \"test.pytest\"] + sorted(chrooted_targets) + PYTEST_PASSTHRU_ARGS,\n check=True\n )\n subprocess.run(\n [\"./pants.pex\", \"test.pytest\"] + sorted(blacklisted_chroot_targets) + PYTEST_PASSTHRU_ARGS,\n check=True\n )\n except subprocess.CalledProcessError:\n die(\"Python unit test failure (V1 test runner\")\n else:\n green(\"V1 unit tests passed.\")\n\n\ndef run_python_tests_v2(*, remote_execution_enabled: bool) -> None:\n check_pants_pex_exists()\n\n blacklisted_v2_targets = get_blacklisted_targets(\"unit_test_v2_blacklist.txt\")\n blacklisted_remote_targets = get_blacklisted_targets(\"unit_test_remote_blacklist.txt\")\n all_targets = get_all_python_tests(tag=\"-integration\")\n v2_compatible_targets = all_targets - blacklisted_v2_targets\n if remote_execution_enabled:\n remote_execution_targets = v2_compatible_targets - blacklisted_remote_targets\n local_execution_targets = blacklisted_remote_targets\n else:\n remote_execution_targets = set()\n local_execution_targets = v2_compatible_targets\n\n def run_v2_tests(\n *, targets: Set[str], execution_strategy: str, oauth_token_path: Optional[str] = None\n ) -> None:\n try:\n command = (\n [\"./pants.pex\", \"--no-v1\", \"--v2\", \"test.pytest\"] + sorted(targets) + PYTEST_PASSTHRU_ARGS\n )\n if oauth_token_path is not None:\n command[3:3] = [\n \"--pants-config-files=pants.remote.ini\",\n # We turn off speculation to reduce the risk of flakiness, where a test passes locally but\n # fails remoting and we have a race condition for which environment executes first.\n \"--process-execution-speculation-strategy=none\",\n f\"--remote-oauth-bearer-token-path={oauth_token_path}\"\n ]\n subprocess.run(command, check=True)\n except subprocess.CalledProcessError:\n die(f\"V2 unit tests failure ({execution_strategy} build execution).\")\n else:\n green(f\"V2 unit tests passed ({execution_strategy} build execution).\")\n\n if remote_execution_enabled:\n with travis_section(\n \"PythonTestsV2Remote\", \"Running Python unit tests with V2 test runner and remote build execution\"\n ), get_remote_execution_oauth_token_path() as oauth_token_path:\n run_v2_tests(\n targets=remote_execution_targets,\n execution_strategy=\"remote\",\n oauth_token_path=oauth_token_path\n )\n with travis_section(\n \"PythonTestsV2Local\", \"Running Python unit tests with V2 test runner and local build execution\"\n ):\n run_v2_tests(targets=local_execution_targets, execution_strategy=\"local\")\n\n\ndef run_rust_tests() -> None:\n command = [\n \"build-support/bin/native/cargo\",\n \"test\",\n \"--all\",\n # We pass --tests to skip doc tests, because our generated protos contain invalid doc tests in\n # their comments.\n \"--tests\",\n \"--manifest-path=src/rust/engine/Cargo.toml\",\n \"--\",\n \"--nocapture\"\n ]\n if platform.system() == \"Darwin\":\n # The osx travis environment has a low file descriptors ulimit, so we avoid running too many\n # tests in parallel.\n command.append(\"--test-threads=1\")\n with travis_section(\"RustTests\", \"Running Rust tests\"):\n try:\n subprocess.run(command, env={**os.environ, \"RUST_BACKTRACE\": \"all\"}, check=True)\n except subprocess.CalledProcessError:\n die(\"Rust test failure.\")\n\n\ndef run_jvm_tests() -> None:\n targets = [\"src/java::\", \"src/scala::\", \"tests/java::\", \"tests/scala::\", \"zinc::\"]\n _run_command(\n [\"./pants.pex\", \"doc\", \"test\"] + targets,\n slug=\"CoreJVM\",\n start_message=\"Running JVM tests\",\n die_message=\"JVM test failure.\"\n )\n\n\ndef run_integration_tests(*, shard: Optional[str]) -> None:\n check_pants_pex_exists()\n all_targets = get_all_python_tests(tag=\"+integration\")\n command = [\"./pants.pex\", \"test.pytest\"]\n if shard is not None:\n command.append(f\"--test-pytest-test-shard={shard}\")\n with travis_section(\"IntegrationTests\", f\"Running Pants Integration tests {shard if shard is not None else ''}\"):\n try:\n subprocess.run(command + sorted(all_targets) + PYTEST_PASSTHRU_ARGS, check=True)\n except subprocess.CalledProcessError:\n die(\"Integration test failure.\")\n\n\ndef run_plugin_tests() -> None:\n _run_command(\n [\"./pants.pex\",\n \"test.pytest\",\n \"pants-plugins/src/python::\",\n \"pants-plugins/tests/python::\",\n ] + PYTEST_PASSTHRU_ARGS,\n slug=\"BackendTests\",\n start_message=\"Running internal backend Python tests\",\n die_message=\"Internal backend Python test failure.\"\n )\n\n\ndef run_platform_specific_tests() -> None:\n targets = [\"src/python/::\", \"tests/python::\"]\n _run_command(\n [\"./pants.pex\",\n \"--tag=+platform_specific_behavior\",\n \"test\"\n ] + targets + PYTEST_PASSTHRU_ARGS,\n slug=\"PlatformSpecificTests\",\n start_message=f\"Running platform-specific tests on platform {platform.system()}\",\n die_message=\"Pants platform-specific test failure.\"\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Furchin/pants","sub_path":"build-support/bin/ci.py","file_name":"ci.py","file_ext":"py","file_size_in_byte":16672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"33"} +{"seq_id":"28162345316","text":"import os\nfrom dotenv import load_dotenv\nfrom databases import Database\nfrom sqlalchemy import create_engine, MetaData\nfrom sqlalchemy import (\n Column,\n DateTime,\n Integer,\n MetaData,\n String,\n Table,\n create_engine\n)\nfrom sqlalchemy.sql import func\n\nload_dotenv()\nDATABASE_URL = os.getenv(\"DATABASE_URL\")\n# SQLAlchemy \nengine = create_engine(DATABASE_URL) # used for communicating with the database\nmetadata = MetaData() # used for creating the database schema\n\n# create table notes\nnotes = Table(\n \"notes\",\n metadata,\n Column(\"id\", Integer, primary_key=True),\n Column(\"title\", String(50)),\n Column(\"description\", String(50)),\n Column(\"created_date\", DateTime, default=func.now(), nullable=False),\n)\n\n# databases query builder\ndatabase = Database(DATABASE_URL)","repo_name":"anapolima/fastapi-crud","sub_path":"src/app/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"8603799259","text":"# To demo:\n# python demo.py\n\nimport os\n\nimport woodchipper\nfrom woodchipper.configs import DevLogToStdout\nfrom woodchipper.context import LoggingContext\n\nos.environ[\"WOODCHIPPER_KEY_PREFIX\"] = \"tkl\"\n\nwoodchipper.configure(config=DevLogToStdout, facilities={\"\": \"INFO\"})\n\nlogger = woodchipper.get_logger(__name__)\n\n\n@LoggingContext(vendor=\"product.vendor\")\ndef decorated_func(product: dict):\n logger.info(\"Decorated.\")\n\n\ndef ctx_func(product: dict):\n with LoggingContext(vendor=product[\"vendor\"]):\n logger.info(\"Context one.\")\n with LoggingContext(product=product[\"id\"]):\n logger.info(\"Context two.\")\n logger.info(\"Context three.\")\n logger.info(\"Context four.\")\n\n\ndef demo():\n product = dict(vendor=\"DEMOVENDOR\", id=\"DEMOPRODUCT\")\n decorated_func(product)\n ctx_func(product)\n\n\nif __name__ == \"__main__\":\n demo()\n","repo_name":"tackle-io/woodchipper","sub_path":"demo/context_demo/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"44"} +{"seq_id":"3331455661","text":"import eel\n\nfrom common.desktop import start\nfrom ranking_fetch_data import scraping\n\napp_name = \"web\"\nend_point = \"ranking_fetch_data.html\"\nsize = (600, 700)\n\n\n@eel.expose\ndef fetch_data(ranking_url: str) -> None:\n scraping(ranking_url=ranking_url)\n eel.enable_btn()\n\n\nif __name__ == \"__main__\":\n start(app_name, end_point, size)\n","repo_name":"daisuke131/python_scraping_amazon_eel","sub_path":"ranking_run.py","file_name":"ranking_run.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"13100513633","text":"from ultralytics import YOLO\nimport cv2\nimport cvzone\nimport math\nimport time\nfrom gmail import*\n# from roboflow import Roboflow\n# rf = Roboflow(api_key=\"f1Ws9sCH12W5dEbGfVEk\")\n# project = rf.workspace().project(\"final_lids\")\n# model = project.version(1).model\n\n\n#cap=cv2.VideoCapture('rtsp://admin:isdr@432@192.168.50.252:554/PSIA/streaming/channels/102')\n#cap=cv2.VideoCapture('rtsp://admin:isdr@431@192.168.51.213:554/PSIA/streaming/channels/102')\n#cap=cv2.VideoCapture('rtsp://admin:isdr@433@192.168.50.131:554/PSIA/streaming/channels/102')\n#cap=cv2.VideoCapture('rtsp://admin:isdr@430@192.168.50.180:558/PSIA/streaming/channels/102')\ndef detector(dist,angle):\n cap=cv2.VideoCapture(0)\n cap.set(3,640)\n cap.set(4,480)\n ptime=0\n wait=0\n detect=False\n model=YOLO('best.pt')\n\n mycolor=(0,0,255)\n\n classNames = ['drone']\n\n while(True):\n success,img=cap.read()\n results=model(img,stream=True)\n detect=False\n ntime=time.time()\n fps=int(1/(ntime-ptime))\n for r in results:\n boxes=r.boxes\n for box in boxes:\n #Bounding boxes\n x1,y1,x2,y2=box.xyxy[0]\n x1,y1,x2,y2=int(x1),int(y1),int(x2),int(y2)\n w,h=x2-x1,y2-y1\n\n #confidence\n conf=(math.ceil(box.conf[0]*100))/100\n conf=str(conf)\n #cvzone.cornerRect(img,(x1,y1,w,h))\n # cv2.putText(img,conf,(x1,y1-30),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2,cv2.LINE_AA)\n #Classes\n cls=int(box.cls[0])\n #cv2.putText(img,str(classNames[cls]),(x1,y1+30),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2,cv2.LINE_AA)\n currentclass=classNames[cls]\n #print(len(boxes))\n mycolor=(255,0,0)\n if(currentclass=='drone'):\n wait=0\n detect=True\n cvzone.putTextRect(img, f'{classNames[cls]} {conf}', (x1+10,y1-20), scale=1, thickness=1,colorT=(255,255,255),colorR=mycolor)\n cv2.rectangle(img,(x1,y1),(x2,y2),mycolor,3)\n \n\n else:\n \n print(wait)\n detect=False\n \n \n \n if(detect==False):\n wait=wait+1\n print(wait)\n \n else:\n email_alert(dist,angle)\n #cv2.putText(img,str(fps),(0,50),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2,cv2.LINE_AA)\n ptime=ntime\n if(angle>=0)&(angle<90):\n nm='Camera 1'\n else:\n nm='Camera 2'\n cv2.imshow(nm,img) \n if(cv2.waitKey(10)&0xFF==ord('d'))|(wait>50):\n break\n\n\n\n cap.release()\n cv2.destroyAllWindows()\n\n#detector(23,120)\n\n\n\n","repo_name":"faeq209/UAV_Detection_LIDAR","sub_path":"drone.py","file_name":"drone.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"21977532289","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport os\n\nfrom flask import current_app\n\nclass Grapher:\n\n def progress_scatter(data, path, dot_size=5):\n\n def apply_color(row):\n return \"Red\" if not row[\"pass\"] else \"DarkBlue\"\n data[\"c\"] = data.apply(lambda row: apply_color(row), axis=1)\n\n fig, axs = plt.subplots(figsize=(20, 6))\n data.plot.scatter(\n ax=axs, x=\"x\", y=\"y\", c=\"c\", s=dot_size)\n\n axs.set_ylabel(\"throughput\")\n axs.set_xlabel(\"timestamp\")\n\n path = os.path.join(current_app.config[\"GRAPH_FOLDER\"], path)\n fig.savefig(path)\n\n return True\n \n def progress_stacked_area(data, path):\n fig, axs = plt.subplots(figsize=(20, 6))\n data.plot.area(ax=axs, linewidth=0.5)\n axs.set_ylabel(\"number of failed tests\")\n axs.set_xlabel(\"timestamp (res=1hr)\")\n \n # Shrink current axis by 20%\n box = axs.get_position()\n axs.set_position([box.x0, box.y0, box.width * 0.8, box.height])\n\n # Put a legend to the right of the current axis\n axs.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\n path = os.path.join(current_app.config[\"GRAPH_FOLDER\"], path)\n fig.savefig(path)\n\n return True\n\n","repo_name":"esbif/gestionate_web","sub_path":"app/main/grapher.py","file_name":"grapher.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"24497543299","text":"from flask import request, current_app, abort\nfrom flask_api import status\nfrom functools import wraps\nfrom jose import jwt\n\nfrom Server.users.models import User\n\n## AuthError Exception\n'''\nAuthError Exception\nA standardized way to communicate auth failure modes\n'''\nclass AuthError(Exception):\n def __init__(self, error, status_code):\n self.error = error\n self.status_code = status_code\n\n\n## Auth Header\n\n\ndef get_token_auth_header():\n \"\"\"\n Obtains the Access Token from the Authorization Header\n \"\"\"\n auth = request.headers.get('Authorization', None)\n if not auth:\n raise AuthError({\n 'code': 'authorization_header_missing',\n 'description': 'Authorization header is expected.'\n }, 401)\n\n parts = auth.split()\n\n if parts[0].lower() != 'bearer':\n raise AuthError({\n 'code' : 'Invalid_header',\n 'description' : 'Authorization header must start with Bearer'\n },401)\n elif len(parts) == 1:\n raise AuthError({\n 'code' : 'Invalid_header',\n 'description' : 'Token not found'\n }, 401)\n elif len(parts) > 2:\n raise AuthError({\n 'code' : 'Invalid_header',\n 'description' : 'Authorization header must be Bearer token'\n }, 401)\n\n token = parts[1]\n return token\n\ndef verify_decode_jwt(token):\n # unverified_header = jwt.get_unverified_header(token)\n # print(f'unverified_header: {unverified_header}')\n try:\n payload = jwt.decode(\n token,\n current_app.config.get('SECRET_KEY')\n )\n return payload\n\n except jwt.ExpiredSignatureError:\n raise AuthError({\n 'code': 'token_expired',\n 'description': 'Token expired.'\n }, 401)\n\n except jwt.JWTClaimsError:\n raise AuthError({\n 'code': 'invalid_claims',\n 'description': 'Incorrect claims. Please, check the audience and issuer.'\n }, 401)\n except Exception:\n raise AuthError({\n 'code': 'invalid_header',\n 'description': 'Unable to parse authentication token.'\n }, 400)\n\n\n\ndef requires_auth(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n token = get_token_auth_header()\n payload = verify_decode_jwt(token)\n current_user = User.query.filter(User.id==payload['id']).first_or_404(\"User Not Found: Login Again\")\n return f(current_user, *args, **kwargs)\n\n return wrapper\n\ndef requires_admin(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n token = get_token_auth_header()\n payload = verify_decode_jwt(token)\n if not payload['admin']:\n abort(status.HTTP_403_FORBIDDEN, 'Forbidden Access To Resource')\n current_user = User.query.filter(User.id==payload['id']).first_or_404(\"User Not Found: Login Again\")\n return f(current_user, *args, **kwargs)\n\n return wrapper","repo_name":"adelelwan24/Semantic-Search-project","sub_path":"BackEnd/Server/auth/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"21136199903","text":"#!env/python3\r\n# coding: utf-8\r\nimport os\r\nimport json\r\n\r\nfrom core.framework.common import *\r\nfrom core.framework.postgresql import *\r\n\r\n\r\n\r\ndef filter_init(self, loading_depth=0):\r\n \"\"\"\r\n Init properties of a filter :\r\n - id : int : the unique id of the filter in the database\r\n - analysis_id : int : the id of the analysis that owns this analysis\r\n - name : str : the name of the filter\r\n - description : str : an optional description\r\n - filter : json : the json source of the filter\r\n - total_variants : int : count of distinct variants filtered\r\n - total_results : int : count of total result (variants+trx) filtered\r\n - progress : float : progress of the saving (as we need to update wt of the analysis, it may take some time)\r\n If loading_depth is > 0, Following properties fill be loaded : (Max depth level is 2)\r\n - analysis : Analysis : The list of Job owns by the project\r\n\r\n \"\"\"\r\n from core.model.analysis import Analysis, AnalysisSample\r\n # With depth loading, sqlalchemy may return several time the same object. Take care to not erase the good depth level)\r\n if hasattr(self, \"loading_depth\"):\r\n self.loading_depth = max(self.loading_depth, min(2, loading_depth))\r\n else:\r\n self.loading_depth = min(2, loading_depth)\r\n if self.loading_depth > 0:\r\n try:\r\n self.analysis = Analysis.from_id(self.analysis_id, self.loading_depth-1)\r\n except Exception as ex:\r\n raise RegovarException(\"Filter data corrupted (id={}).\".format(self.id), \"\", ex)\r\n\r\n\r\n\r\n\r\ndef filter_from_id(filter_id, loading_depth=0):\r\n \"\"\"\r\n Retrieve Filter with the provided id in the database\r\n \"\"\"\r\n filter = Session().query(Filter).filter_by(id=filter_id).first()\r\n if filter : \r\n Session().refresh(filter)\r\n filter.init(loading_depth)\r\n return filter\r\n\r\n return Session().query(Filter).filter_by(id=filter_id).first()\r\n\r\n\r\n\r\ndef filter_to_json(self, fields=None, loading_depth=-1):\r\n \"\"\"\r\n export the filter into json format with only requested fields\r\n \"\"\"\r\n result = {}\r\n if loading_depth < 0:\r\n loading_depth = self.loading_depth\r\n if fields is None:\r\n fields = Filter.public_fields\r\n for f in fields:\r\n result.update({f: eval(\"self.\" + f)})\r\n return result\r\n\r\n\r\n\r\ndef filter_load(self, data):\r\n \"\"\"\r\n Helper to update several paramters at the same time. Note that dynamics properties like project and analysis\r\n cannot be updated with this method. However, you can update analysis_id which will force the reloading of \r\n the dynamic property analysis.\r\n \"\"\"\r\n try:\r\n if \"name\" in data.keys(): self.name = check_string(data['name'])\r\n if \"analysis_id\" in data.keys(): self.analysis_id = check_int(data['analysis_id'])\r\n if \"filter\" in data.keys(): self.filter = data['filter']\r\n if \"description\" in data.keys(): self.description = check_string(data['description'])\r\n if \"total_variants\" in data.keys(): self.total_variants = check_int(data['total_variants'])\r\n if \"total_results\" in data.keys(): self.total_results = check_int(data['total_results'])\r\n if \"progress\" in data.keys(): self.progress = check_float(data['progress'])\r\n self.save()\r\n \r\n except Exception as err:\r\n raise RegovarException('Invalid input data to load.', \"\", err)\r\n return self\r\n\r\n\r\n\r\ndef filter_delete(filter_id):\r\n \"\"\"\r\n Delete the filter with the provided id in the database\r\n \"\"\"\r\n Session().query(Filter).filter_by(id=filter_id).delete()\r\n Session().commit()\r\n \r\n\r\n\r\n\r\ndef filter_new():\r\n \"\"\"\r\n Create a new filter and init/synchronise it with the database\r\n \"\"\"\r\n f = Filter()\r\n f.save()\r\n f.init()\r\n return f\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\nFilter = Base.classes.filter\r\nFilter.public_fields = [\"id\", \"analysis_id\", \"name\", \"filter\", \"description\", \"total_variants\", \"total_results\", \"progress\"]\r\nFilter.init = filter_init\r\nFilter.from_id = filter_from_id\r\nFilter.to_json = filter_to_json\r\nFilter.load = filter_load\r\nFilter.new = filter_new\r\nFilter.delete = filter_delete\r\nFilter.save = generic_save\r\n\r\n\r\n\r\n\r\n","repo_name":"REGOVAR/Regovar","sub_path":"regovar/core/model/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"44"} +{"seq_id":"13442296791","text":"import vtk\nimport numpy as np\nimport pandas as pd\n\nfrom constants import EARTH_RADIUS, GLIDER_PATH_TUBE_RADIUS, GLIDER_PATH_LUT_RANGE, GLIDER_PATH_WEIGHTED_SEGMENTS\nfrom utils import RT90ToWGS84, toCartesian\n\ndef prepareData(file):\n '''\n Read and transforme glider path data to be usable.\n Return a list of cartesian coords for each point in the path\n and another list with the associated elevation diffs between\n two measure.\n '''\n\n # Read coordinates and elevations\n df = pd.read_table(file, header=None, skiprows=[0], usecols=[1,2,3,4,5],\n delim_whitespace=True, dtype={1:np.int32, 2:np.int32, 3:np.float64})\n # Compute time interval between two measures\n df[5] = pd.to_datetime((df[4] + \"T\" + df[5]).astype(\"str\"), format=\"%m/%d/%yT%H:%M:%S\")\n df[5] = df[5].diff().dt.seconds\n # Compute elevation difference between two position\n df[4] = df[3].diff() / df[5] * df[5].mean() if GLIDER_PATH_WEIGHTED_SEGMENTS else df[3].diff()\n df[4] = df[4].fillna(0) # Remove NaN\n df[4] = - df[4] # Inverse max and min to fit LUT colors\n # Transform data to WGS84\n df[1], df[2] = RT90ToWGS84(df[1], df[2])\n # Transform to Spherical coords\n df[6] = df.apply(lambda x: toCartesian(x[1], x[2], x[3] + EARTH_RADIUS), axis=1)\n\n return df[6], df[4]\n\ndef getActor(file):\n '''\n Return an actor showing the glider path with elevation differences highlighted\n '''\n\n # Retrieve data\n coords, diffs = prepareData(file)\n\n # Geometry\n points = vtk.vtkPoints()\n # Scalar attributes\n elevationDiffs = vtk.vtkFloatArray()\n\n for coord, diff in zip(coords, diffs):\n points.InsertNextPoint(coord)\n elevationDiffs.InsertNextValue(diff)\n\n # Create the path as lines in a polydata\n source = vtk.vtkLineSource()\n source.SetPoints(points)\n source.Update()\n\n # Settings scalars to the generated polydata\n polydata = source.GetOutput()\n polydata.GetPointData().SetScalars(elevationDiffs)\n\n # To have something nice to display\n mesh = vtk.vtkTubeFilter()\n mesh.SetRadius(GLIDER_PATH_TUBE_RADIUS)\n mesh.SetInputConnection(source.GetOutputPort())\n\n # Need to use a custom range and not to compute it\n # since some big diffs can quickly make hard to really\n # highlight the average diffs which will be all green\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputConnection(mesh.GetOutputPort())\n mapper.SetScalarRange(GLIDER_PATH_LUT_RANGE)\n\n actor = vtk.vtkActor()\n actor.SetMapper(mapper)\n\n return actor","repo_name":"ChatDeBlofeld/VTK_labo4","sub_path":"glider_path.py","file_name":"glider_path.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"32013720713","text":"from config_handler import ConfigHandler\nfrom web3 import Web3\nimport os\nimport errno\n\nZERO_VALUE = '0x' + '0' * 64\n_TEST_CONFIG = 'testcase/etc/test_config.conf'\n\nTEST_PAIR_LENGTH = 2\nTEST_PAIR_PERIOD = 2\n\n\ndef get_db_path(config):\n config_handler = ConfigHandler(config)\n return config_handler.get_chain_config('DB', 'db_path')\n\n\ndef calculate_submit_hash(input_vals):\n compose_hash = []\n for vals in input_vals:\n hash_sums = [Web3.toInt(Web3.sha3(text=str(val)))\n for val in vals]\n compose_hash.append(Web3.toInt(Web3.sha3(sum(hash_sums) & (2 ** 256 - 1))))\n\n return Web3.toHex(Web3.sha3(sum(compose_hash) & (2 ** 256 - 1)))\n\n\ndef unlink_silence(path):\n try:\n os.unlink(path)\n return True\n except OSError as e:\n if e.errno == errno.ENOENT:\n return True\n return False\n","repo_name":"sfffaaa/proved_db","sub_path":"backend/testcase/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"39004705132","text":"\"\"\"\nThis file contains the translator for Bamboo. It converts the reponse of the Bamboo REST API into a Windfile.\n\"\"\"\nimport re\nimport typing\nfrom typing import Optional, Tuple, Any\n\nimport yaml\n\nfrom classes.bamboo_client import BambooClient\nfrom classes.bamboo_specs import (\n BambooSpecs,\n BambooPlan,\n BambooJob,\n BambooStage,\n BambooCheckoutTask,\n BambooTask,\n BambooRepository,\n BambooSpecialTask,\n BambooDockerConfig,\n BambooArtifact,\n)\nfrom classes.ci_credentials import CICredentials\nfrom classes.generated.definitions import (\n Target,\n WindfileMetadata,\n ScriptAction,\n Repository,\n Docker,\n Api,\n Author,\n Environment,\n Lifecycle,\n Action,\n Dictionary,\n PlatformAction,\n Parameters,\n Result,\n)\nfrom classes.generated.environment import EnvironmentSchema\nfrom classes.generated.windfile import WindFile\nfrom classes.input_settings import InputSettings\nfrom classes.output_settings import OutputSettings\nfrom classes.pass_settings import PassSettings\nfrom classes.yaml_dumper import YamlDumper\nfrom cli_utils import logger, utils\n\n\ndef parse_docker(docker_config: Optional[BambooDockerConfig], environment: EnvironmentSchema) -> Optional[Docker]:\n \"\"\"\n Converts the given docker configuration into a Docker object.\n :param docker_config: Config from Bamboo\n :param environment: Environment variables to replace\n :return: Docker object or None\n \"\"\"\n if docker_config is not None:\n volume_list: list[str] = []\n for volume in docker_config.volumes:\n host: str = utils.replace_bamboo_environment_variable_with_aeolus(environment=environment, haystack=volume)\n container: str = utils.replace_bamboo_environment_variable_with_aeolus(\n environment=environment, haystack=docker_config.volumes[volume]\n )\n volume_list.append(f\"{host}:{container}\")\n arguments: list[str] = utils.replace_bamboo_environment_variables_with_aeolus(\n environment=environment, haystack=docker_config.docker_run_arguments\n )\n docker = Docker(\n image=docker_config.image if \":\" not in docker_config.image else docker_config.image.split(\":\")[0],\n tag=docker_config.image.split(\":\")[1] if \":\" in docker_config.image else \"latest\",\n volumes=volume_list,\n parameters=arguments,\n )\n return docker\n return None\n\n\ndef parse_env_variables(\n environment: EnvironmentSchema, variables: dict[Any, int | str | float | bool | list[Any] | None]\n) -> Environment:\n \"\"\"\n Converts the given environment variables into a Environment object.\n :param environment: Environment variables to replace\n :param variables: Environment variables from Bamboo\n :return:\n \"\"\"\n dictionary: Dictionary = Dictionary(root={})\n for key, value in variables.items():\n dictionary.root[key] = (\n utils.replace_bamboo_environment_variable_with_aeolus(environment=environment, haystack=value)\n if isinstance(value, str)\n else value\n )\n return Environment(root=dictionary)\n\n\ndef parse_arguments(environment: EnvironmentSchema, task: BambooTask) -> Parameters:\n \"\"\"\n Converts the given arguments into a Parameters object.\n :param environment: Environment variables to replace\n :param task: Task containing the arguments\n :return: Parameters object\n \"\"\"\n param_dictionary: dict[Any, str | float | bool | list | None] = {}\n for value in task.arguments:\n param_dictionary[value] = utils.replace_bamboo_environment_variable_with_aeolus(\n environment=environment, haystack=value\n )\n if isinstance(task, BambooSpecialTask):\n for key in task.parameters:\n if key in [\"working_dir\"]:\n continue\n updated: Optional[str | float | bool | list] = task.parameters[key]\n if task.task_type == \"maven\":\n # clean up unnecessary parameters\n if key in [\"executable\", \"jdk\", \"goal\", \"tests\"]:\n continue\n if isinstance(updated, str):\n updated = utils.replace_bamboo_environment_variable_with_aeolus(\n environment=environment, haystack=updated\n )\n param_dictionary[key] = updated\n return Parameters(root=Dictionary(root=param_dictionary))\n\n\ndef extract_action_name(task: BambooTask) -> str:\n \"\"\"\n Extracts the name of the given task of the given Job.\n :param task: Task to convert\n :return: name of the task\n \"\"\"\n if isinstance(task, BambooSpecialTask):\n return task.task_type\n if isinstance(task, BambooTask):\n return task.description.replace(\" \", \"_\").lower()\n return task.description.replace(\" \", \"_\").lower()\n\n\ndef extract_action(job: BambooJob, task: BambooTask, environment: EnvironmentSchema) -> Optional[Action]:\n \"\"\"\n Converts the given task of the given Job into an Action.\n Setting the conditions and environment variables fetched from Bamboo\n :param job: Job containing the task we want to convert\n :param task: Task to convert\n :param environment: Environment variables to replace\n :return: converted Action\n \"\"\"\n exclude: list[Lifecycle] = []\n if task.condition is not None:\n for condition in task.condition.variables:\n for match in condition.matches:\n regex = re.compile(r\"[^a-zA-Z |_]\")\n lifecycle = condition.matches[match]\n for entry in regex.sub(\"\", lifecycle).split(\"|\"):\n exclude.append(Lifecycle[entry])\n docker: Optional[Docker] = parse_docker(docker_config=job.docker, environment=environment)\n envs: Environment = parse_env_variables(environment=environment, variables=task.environment)\n params: Parameters = parse_arguments(environment=environment, task=task)\n action: Optional[Action] = None\n if isinstance(task, BambooSpecialTask):\n if isinstance(task, BambooSpecialTask):\n if task.task_type == \"maven\":\n action = Action( # type: ignore\n ScriptAction(\n name=extract_action_name(task=task),\n script=f\"mvn {task.goal}\",\n excludeDuring=exclude,\n workdir=str(task.parameters[\"working_dir\"]) if \"working_dir\" in task.parameters else None,\n docker=docker,\n parameters=params,\n environment=envs,\n results=None,\n platform=None,\n runAlways=task.always_execute,\n )\n )\n else:\n action = Action(\n root=PlatformAction(\n name=extract_action_name(task=task),\n parameters=params,\n kind=task.task_type,\n excludeDuring=exclude,\n workdir=str(task.parameters[\"working_dir\"]) if \"working_dir\" in task.parameters else None,\n file=None,\n function=None,\n docker=docker,\n results=None,\n environment=envs,\n platform=Target.bamboo,\n runAlways=task.always_execute,\n )\n )\n else:\n script: str = \"\".join(task.scripts)\n code: str = utils.replace_bamboo_environment_variable_with_aeolus(environment=environment, haystack=script)\n code = code.lstrip('\"').rstrip('\"')\n action = Action(\n root=ScriptAction(\n name=task.description.replace(\" \", \"_\").lower(),\n script=code,\n excludeDuring=exclude,\n workdir=task.workdir if task.workdir else None,\n docker=docker,\n parameters=params,\n environment=envs,\n results=None,\n platform=None,\n runAlways=task.always_execute,\n )\n )\n return action\n\n\ndef convert_results(artifacts: typing.List[BambooArtifact]) -> typing.List[Result]:\n \"\"\"\n Convert the artifacts from the Bamboo response into easy to work with objects.\n :param artifacts: list of artifacts from Bamboo\n :return: list of BambooArtifact objects\n \"\"\"\n results: list[Result] = []\n for artifact in artifacts:\n results.append(\n Result(\n name=artifact.name,\n path=artifact.location + \"/\" + artifact.pattern,\n ignore=artifact.exclusion,\n type=None,\n before=False,\n )\n )\n return results\n\n\ndef add_results_to_action(junit_action: PlatformAction, actions: list[Action], results: list[Result]) -> None:\n \"\"\"\n Adds the given junit result to the given list of actions.\n :param junit_action: junit action that needs to be added\n :param actions: list of actions\n :param results: results to add\n \"\"\"\n could_be_added: bool = False\n for action in reversed(list(actions)):\n if isinstance(action.root, ScriptAction):\n if (\n action.root.excludeDuring == junit_action.excludeDuring\n and action.root.runAlways == junit_action.runAlways\n and action.root.workdir == junit_action.workdir\n ):\n could_be_added = True\n if action.root.results is None:\n action.root.results = results\n else:\n for result in results:\n action.root.results.append(result)\n break\n if not could_be_added:\n actions.append(\n Action(\n root=ScriptAction(\n name=junit_action.name,\n script=\"#empty script action, just for the results\",\n excludeDuring=junit_action.excludeDuring,\n workdir=junit_action.workdir,\n docker=junit_action.docker,\n parameters=None,\n environment=None,\n results=results,\n platform=None,\n runAlways=junit_action.runAlways,\n )\n )\n )\n\n\ndef convert_junit_tasks_to_results(actions: list[Action], homeless_junit_actions: list[PlatformAction]) -> None:\n \"\"\"\n Converts the given list of junit tasks into a list of results.\n :param actions: list of actions\n :param homeless_junit_actions: list of junit tasks\n \"\"\"\n if len(homeless_junit_actions) == 0:\n return\n for junit_action in homeless_junit_actions:\n if (\n junit_action.parameters is None\n or junit_action.parameters.root is None\n or junit_action.parameters.root.root is None\n or junit_action.parameters.root.root[\"test_results\"] is None\n ):\n # we don't want to add empty junit actions with no parameter test_results\n continue\n paths: list[str] = []\n if isinstance(junit_action.parameters.root.root[\"test_results\"], list):\n paths = junit_action.parameters.root.root[\"test_results\"]\n elif isinstance(junit_action.parameters.root.root[\"test_results\"], str):\n paths.append(junit_action.parameters.root.root[\"test_results\"])\n results: list[Result] = []\n for path in paths:\n results.append(\n Result(name=f\"{junit_action.name}_{path}\", path=path, type=\"junit\", ignore=None, before=True)\n )\n add_results_to_action(junit_action=junit_action, actions=actions, results=results)\n\n\ndef extract_actions(stages: dict[str, BambooStage], environment: EnvironmentSchema) -> list[Action]:\n \"\"\"\n Converts all jobs and tasks from the given stages (from the REST API)\n into a dictionary of ScriptActions.\n :param stages: dict of stages from the REST API\n :param environment: Environment variables from the REST API\n :return: dict of ScriptActions\n \"\"\"\n actions: list[Action] = []\n for _, stage in stages.items():\n for job_name in stage.jobs:\n job: BambooJob = stage.jobs[job_name]\n homeless_junit_actions: list[PlatformAction] = []\n for task in job.tasks:\n if not isinstance(task, BambooTask):\n continue\n action: Optional[Action] = extract_action(job=job, task=task, environment=environment)\n if not action:\n continue\n remove: bool = False\n if isinstance(action.root, PlatformAction):\n if action.root.kind in [\"junit\", \"test_parser\"]:\n homeless_junit_actions.append(action.root)\n remove = True\n if not remove:\n actions.append(action)\n # we have a different abstraction for artifacts, so we simply append them to the last action\n if job.artifacts is not None:\n if len(actions) > 0:\n actions[-1].root.results = convert_results(job.artifacts)\n # we also don't want any orphaned junit actions, so we add them to the last action with the same\n # excludeDuring and runAlways\n convert_junit_tasks_to_results(actions=actions, homeless_junit_actions=homeless_junit_actions)\n\n return actions\n\n\ndef extract_repositories(\n stages: dict[str, BambooStage], repositories: dict[str, BambooRepository]\n) -> dict[str, Repository]:\n \"\"\"\n Extracts the repositories from the given stages. So we can add them to the windfile.\n :param stages: stages that possibly contain repositories in its tasks\n :param repositories: repositories defined in the Build Plan\n :return: dict of parsed repositories\n \"\"\"\n found: dict[str, Repository] = {}\n for _, stage in stages.items():\n for job_name in stage.jobs:\n job: BambooJob = stage.jobs[job_name]\n for task in job.tasks:\n if isinstance(task, BambooCheckoutTask):\n checkout: BambooCheckoutTask = task\n repository: Repository = Repository(\n url=repositories[checkout.repository].url,\n branch=repositories[checkout.repository].branch,\n path=checkout.path,\n )\n found[checkout.repository] = repository\n return found\n\n\nclass BambooTranslator(PassSettings):\n source: Target = Target.bamboo\n client: BambooClient\n environment: EnvironmentSchema\n\n def __init__(self, input_settings: InputSettings, output_settings: OutputSettings, credentials: CICredentials):\n input_settings.target = Target.bamboo\n env: typing.Optional[EnvironmentSchema] = utils.get_ci_environment(\n target=input_settings.target, output_settings=output_settings\n )\n if env is None:\n raise ValueError(f\"No environment found for target {input_settings.target.value}\")\n self.environment = env\n super().__init__(input_settings=input_settings, output_settings=output_settings)\n self.client = BambooClient(credentials=credentials)\n\n def replace_environment_variables(self, windfile: WindFile) -> None:\n \"\"\"\n Replaces the environment variables in the given windfile.\n :param windfile: Windfile to replace\n \"\"\"\n if windfile.metadata.docker is not None:\n windfile.metadata.docker.volumes = utils.replace_bamboo_environment_variables_with_aeolus(\n environment=self.environment, haystack=windfile.metadata.docker.volumes\n )\n windfile.metadata.docker.parameters = utils.replace_bamboo_environment_variables_with_aeolus(\n environment=self.environment, haystack=windfile.metadata.docker.parameters\n )\n for action in windfile.actions:\n if isinstance(action.root, ScriptAction):\n action.root.script = utils.replace_bamboo_environment_variable_with_aeolus(\n environment=self.environment, haystack=action.root.script\n )\n\n def translate(self, plan_key: str) -> Optional[WindFile]:\n \"\"\"\n Translate the given build plan into a windfile.\n :return: Windfile\n \"\"\"\n optional: Optional[Tuple[BambooSpecs, dict[str, Any]]] = self.client.get_plan_yaml(plan_key=plan_key)\n if optional is None:\n return None\n specs: BambooSpecs = optional[0]\n # raw: dict[str, str] = optional[1]\n plan: BambooPlan = specs.plan\n actions: list[Action] = extract_actions(stages=specs.stages, environment=self.environment)\n repositories: dict[str, Repository] = extract_repositories(stages=specs.stages, repositories=specs.repositories)\n metadata: WindfileMetadata = WindfileMetadata(\n name=plan.name,\n description=plan.description,\n author=Author(root=\"bamboo\"),\n id=plan_key,\n docker=None,\n targets=None,\n gitCredentials=specs.repositories[list(specs.repositories.keys())[0]].shared_credentials,\n resultHook=None,\n moveResultsTo=None,\n )\n windfile: WindFile = WindFile(\n api=Api(root=\"v0.0.1\"), metadata=metadata, actions=actions, repositories=repositories\n )\n utils.clean_up(windfile=windfile, output_settings=self.output_settings)\n # work-around as enums do not get cleanly printed with model_dump\n json: str = windfile.model_dump_json(exclude_none=True)\n logger.info(\"🪄\", \"Translated windfile\", self.output_settings.emoji)\n print(yaml.dump(yaml.safe_load(json), sort_keys=False, Dumper=YamlDumper, default_flow_style=False))\n return windfile\n","repo_name":"ls1intum/Aeolus","sub_path":"cli/classes/translator.py","file_name":"translator.py","file_ext":"py","file_size_in_byte":18025,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"44"} +{"seq_id":"33081271428","text":"\"\"\"A Pipeline module.\n\nThis module contains the definition of the `Pipeline` class and `PipelineManager` class.\n\nClasses:\n Pipeline: A Class that encapsulates the pipeline information.\n PipelineManager: A class that manage the pipeline with runtime database.\n\"\"\"\n\nimport uuid\nimport logging\nfrom typing import Dict, Iterator, Any, Tuple\n\nfrom core.stream import StreamProvider\nfrom core.infereng import InferenceInfo\nfrom core.rtdb import RuntimeDatabaseBase\n\nLOG = logging.getLogger(__name__)\n\nclass Pipeline:\n \"\"\"A Class that encapsulates the pipeline information.\n\n This class defines the pipeline information, including the pipeline ID, stream provider and\n inference engine information.\n\n Attributes:\n _id (str): The pipeline ID.\n _provider (StreamProvider): The stream provider of pipeline.\n _infer_engine_dict (dict): The dict of inference engines inforamtion of pipeline.\n \"\"\"\n\n def __init__(self, provider: StreamProvider, infer_engine_info: InferenceInfo):\n \"\"\"Initialize a Pipeline object.\n\n This constructor initializes a Pipeline object with the given stream provider and\n inference engine information.\n\n Args:\n provider (StreamProvider): The stream provider of pipeline.\n infer_engine_info (InferenceInfo): The inference engine inforamtion of pipeline.\n \"\"\"\n self._id = None\n self._provider = provider\n self._infer_engine_dict = {infer_engine_info.id: {'infer_info': dict(infer_engine_info),\n 'infer_fps': 0}}\n\n @property\n def id(self) -> str:\n \"\"\"str: The pipeline ID (string of UUID).\"\"\"\n if self._id is None:\n self._id = uuid.uuid1()\n return str(self._id)\n\n @id.setter\n def id(self, new_str: str) -> None:\n \"\"\"Set pipeline ID from string.\"\"\"\n self._id = uuid.UUID(new_str)\n\n def __iter__(self) -> Iterator[Tuple[str, Dict[str, Any]]]:\n \"\"\"The Iterator for Pipeline class.\"\"\"\n yield 'provider', dict(self._provider)\n yield 'infer_engine_dict', self._infer_engine_dict\n\n\nclass PipelineManager:\n \"\"\"A class that manage the pipeline with runtime database.\n\n This class manage the pipeline with runtime database, provides the `register_pipeline`\n and `unregister_pipeline` methods.\n\n Attributes:\n _db (RuntimeDatabaseBase): The runtime database used by pipeline manager.\n \"\"\"\n\n PIPELINE_TABLE = \"Pipeline-table\"\n\n def __init__(self, db: RuntimeDatabaseBase):\n \"\"\"Initialize a PipelineManager object.\n\n This constructor initializes a PipelineManager object with the given runtime database.\n\n Args:\n db (RuntimeDatabaseBase): The runtime database used by pipeline manager.\n \"\"\"\n self._db = db\n\n def register_pipeline(self, pipeline_obj: Pipeline) -> None:\n \"\"\"Register a new pipeline.\n\n Args:\n pipeline_obj (Pipeline): The pipeline object to register.\n\n Raises:\n ValueError: Propagates the ValueError raised by `save_table_object_dict` if some cases\n are met.\n \"\"\"\n LOG.debug(\"Register Pipeline: %s\", str(dict(pipeline_obj)))\n try:\n self._db.lock(f\"{self.PIPELINE_TABLE}-lock\")\n self._db.save_table_object_dict(\n PipelineManager.PIPELINE_TABLE,\n pipeline_obj.id,\n dict(pipeline_obj)\n )\n finally:\n self._db.unlock()\n\n def unregister_pipeline(self, pipeline_id: str) -> None:\n \"\"\"Unregister an existing pipeline.\n\n Args:\n pipeline_id (str): The id of pipeline to unregister.\n\n Raises:\n ValueError: Propagates the ValueError raised by `del_table_object` if some cases are\n met.\n \"\"\"\n LOG.debug(\"Unregister Pipeline: %s\", pipeline_id)\n try:\n self._db.lock(f\"{self.PIPELINE_TABLE}-lock\")\n self._db.del_table_object(PipelineManager.PIPELINE_TABLE, pipeline_id)\n finally:\n self._db.unlock()\n\n def set_infer_fps(self, pipeline_id: str, infer_info: InferenceInfo, infer_fps: int) -> None:\n \"\"\"Set inference fps for a pipeline.\n\n Args:\n pipeline_id (str): The id of pipeline to set inference fps.\n infer_info (InferenceInfo): The inference info to set inference fps.\n infer_fps (int): The inference fps to set.\n\n Raises:\n ValueError: Propagates the ValueError raised by `get_table_object_dict`\n or `save_table_object_dict` if some cases are met.\n \"\"\"\n LOG.debug(\"Set inference fps: %d for pipeline: %s and inference service: %s\",\n infer_fps, pipeline_id, infer_info.id)\n try:\n self._db.lock(f\"{self.PIPELINE_TABLE}-lock\")\n if self._db.check_table_object_exist(PipelineManager.PIPELINE_TABLE, pipeline_id):\n pipeline_dict = self._db.get_table_object_dict(PipelineManager.PIPELINE_TABLE,\n pipeline_id)\n # Add inference engine to infer_engine_dict if not exist.\n if infer_info.id not in pipeline_dict['infer_engine_dict']:\n pipeline_dict['infer_engine_dict'][infer_info.id] = \\\n {'infer_info': dict(infer_info),\n 'infer_fps': infer_fps}\n else:\n pipeline_dict['infer_engine_dict'][infer_info.id]['infer_fps'] = infer_fps\n self._db.save_table_object_dict(\n PipelineManager.PIPELINE_TABLE,\n pipeline_id,\n pipeline_dict\n )\n else:\n LOG.debug(\"Pipeline: %s has been unregistered.\", pipeline_id)\n finally:\n self._db.unlock()\n\n def clean_infer_engine(self, infer_info_id: str) -> None:\n \"\"\"Clean inference engine in infer_engine_dict.\n\n Args:\n infer_info_id (str): The id of inference info to clear inference fps.\n\n Raises:\n ValueError: Propagates the ValueError raised by `get_all_table_objects_dict`\n or `save_table_object_dict` if some cases are met.\n \"\"\"\n try:\n self._db.lock(f\"{self.PIPELINE_TABLE}-lock\")\n pipeline_dicts = self._db.get_all_table_objects_dict(PipelineManager.PIPELINE_TABLE)\n for pipeline_id, pipeline_dict in pipeline_dicts.items():\n if infer_info_id in pipeline_dict['infer_engine_dict']:\n del pipeline_dict['infer_engine_dict'][infer_info_id]\n if self._db.check_table_object_exist(PipelineManager.PIPELINE_TABLE,\n pipeline_id):\n self._db.save_table_object_dict(\n PipelineManager.PIPELINE_TABLE,\n pipeline_id,\n pipeline_dict\n )\n else:\n LOG.debug(\"Pipeline: %s has been unregistered.\", pipeline_id)\n finally:\n self._db.unlock()\n","repo_name":"intel/cloud-native-ai-pipeline","sub_path":"cnap/core/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":7284,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"44"} +{"seq_id":"13982989481","text":"import json\n\nfrom prosd.graph import railgraph, routing\nfrom prosd.models import MasterScenario, RailwayLine, TimetableTrainGroup, RouteTraingroup, ProjectContent, TimetableTrain, RailwayStation, TimetableTrainPart, TimetableCategory\nfrom prosd.manage_db import version\nfrom prosd import db\n\n\n# Create a scenario -> create_scenario()\nscenario_id = 7\nrg = railgraph.RailGraph()\ngraph = rg.load_graph(rg.filepath_save_with_station_and_parallel_connections)\nscenario = MasterScenario.query.get(scenario_id)\n\nfilepath_block = f'../../example_data/railgraph/blocked_scenarios/s-{scenario_id}.json'\n\n\ndef save_additional_project_info(pc, additional_ignore_ocp, traingroups_to_reroute):\n \"\"\"\n\n :param pc:\n :param additional_ignore_ocp: additional ocp that gets ignored for routing\n :return:\n \"\"\"\n try:\n with open(filepath_block, 'r') as openfile:\n geojson_data = json.load(openfile)\n except json.decoder.JSONDecodeError:\n geojson_data = dict()\n\n geojson_data[pc.id] = {\n \"additional_ignore_ocp\": additional_ignore_ocp,\n \"traingroups_to_reroute\": traingroups_to_reroute\n }\n\n with open(filepath_block, 'w') as outfile:\n json.dump(geojson_data, outfile)\n\n\ndef read_additional_project_info():\n with open(filepath_block, 'r') as openfile:\n geojson_data = json.load(openfile)\n\n return geojson_data\n\n\ndef create_project():\n from_ocp = 'ALBG'\n to_ocp = 'HU'\n stations_via = []\n reroute_train_categories = ['sgv', 'spfv']\n project_content_number = f\"s-{scenario_id} Sperrung {from_ocp} – {to_ocp}\"\n project_content_name = 'Sperrung Lüneburg – Uelzen'\n additional_ignore_ocp = [\n 'ASTE',\n 'AASA',\n 'AWI',\n 'ARH',\n 'ABAD',\n 'ALBG',\n 'ADEV'\n 'HGAR',\n 'HESD',\n 'HUNL',\n 'HSUD',\n 'HKSU'\n ]\n\n infra_version = version.Version(scenario=scenario)\n route = routing.GraphRoute(graph=graph, infra_version=infra_version)\n path = route.route_line(station_from=from_ocp, station_to=to_ocp, stations_via=stations_via)\n\n blocked_lines_id = path['edges']\n blocked_lines = RailwayLine.query.filter(RailwayLine.id.in_(blocked_lines_id)).all()\n\n blocked_ocp = set()\n blocked_ocp.update(RailwayStation.query.filter(RailwayStation.db_kuerzel.in_(additional_ignore_ocp)).all())\n\n for stations in [line.stations for line in blocked_lines]:\n for station in stations:\n if station.db_kuerzel == from_ocp or station.db_kuerzel == to_ocp:\n continue\n blocked_ocp.add(station)\n\n pc = ProjectContent(\n name=project_content_name,\n project_number=project_content_number,\n closure=True\n )\n pc.railway_lines = blocked_lines\n pc.railway_stations = list(blocked_ocp)\n db.session.add(pc)\n db.session.commit()\n\n tgs = TimetableTrainGroup.query.join(RouteTraingroup).join(TimetableTrain).join(TimetableTrainPart).join(\n TimetableCategory).filter(\n RouteTraingroup.master_scenario_id == scenario_id,\n RouteTraingroup.railway_line_id.in_(blocked_lines_id),\n TimetableCategory.transport_mode.in_(reroute_train_categories)\n ).all()\n\n save_additional_project_info(pc=pc, additional_ignore_ocp=additional_ignore_ocp, traingroups_to_reroute=tgs)\n\n\ndef reroute_traingroups():\n infra_version = version.Version(scenario=scenario)\n\n data = read_additional_project_info()\n traingroups = []\n blocked_ocps = []\n for key, value in data.items():\n pc = ProjectContent.query.get(key)\n infra_version.add_projectcontents_to_version_temporary(\n pc_list=[pc],\n update_infra=True,\n use_subprojects=False\n )\n traingroups.extend(value[\"traingroups_to_reroute\"])\n blocked_ocps.extend(value[\"additional_ignore_ocp\"])\n\n route = routing.GraphRoute(graph=graph, infra_version=infra_version)\n\n for tg in traingroups:\n route.line(\n traingroup=tg,\n save_route=True,\n force_recalculation=True,\n ignore_ocps=set([station.db_kuerzel for station in blocked_ocps])\n )\n\n\ndef reroute_traingroups_without_blocked_lines():\n infra_version = version.Version(scenario=scenario)\n data = read_additional_project_info()\n traingroups = []\n for key, value in data.items():\n pc = ProjectContent.query.get(key)\n traingroups.extend(value[\"traingroups_to_reroute\"])\n\n route = routing.GraphRoute(graph=graph, infra_version=infra_version)\n for tg in traingroups:\n route.line(\n traingroup=tg,\n save_route=True,\n force_recalculation=True\n )\n\n\nif __name__ == '__main__':\n reroute_traingroups_without_blocked_lines()\n\n","repo_name":"JonasPrade/pros","sub_path":"scripts/masterarbeit/add_railwayline_blocked.py","file_name":"add_railwayline_blocked.py","file_ext":"py","file_size_in_byte":4775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"40772465535","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : Rock Wayne \n# @Created : 2020-05-06 08:00:00\n# @Last Modified : 2020-05-06 08:00:00\n# @Mail : lostlorder@gmail.com\n# @Version : alpha-1.0\n\n\"\"\"\n# 把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s的所有可能的值出现的概率。 \n# \n# \n# \n# 你需要用一个浮点数数组返回答案,其中第 i 个元素代表这 n 个骰子所能掷出的点数集合中第 i 小的那个的概率。 \n# \n# \n# \n# 示例 1: \n# \n# 输入: 1\n# 输出: [0.16667,0.16667,0.16667,0.16667,0.16667,0.16667]\n# \n# \n# 示例 2: \n# \n# 输入: 2\n# 输出: [0.02778,0.05556,0.08333,0.11111,0.13889,0.16667,0.13889,0.11111,0.08333,0\n# .05556,0.02778] \n# \n# \n# \n# 限制: \n# \n# 1 <= n <= 11 \n# \n\n\"\"\"\nfrom typing import List\n\nimport pytest\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\n\n\nclass Solution:\n \"\"\" 优化DP\"\"\"\n\n def twoSum(self, n: int) -> List[float]:\n MAX_VALUE = 6\n dp = [0.0] * (MAX_VALUE * n + 1)\n for i in range(1, MAX_VALUE+1):\n dp[i] = 1 / MAX_VALUE\n for i in range(2, n + 1):\n for j in range(MAX_VALUE * i, i - 1, -1):\n start = max(i - 1, j - MAX_VALUE)\n # print(\"start\",start,i - 1, j - MAX_VALUE)\n dp[j] = sum(dp[start:j]) * 1 / MAX_VALUE\n return dp[n:]\n\n\n# leetcode submit region end(Prohibit modification and deletion)\nclass Solution1:\n \"\"\" 原始二维DP\n https://leetcode-cn.com/problems/nge-tou-zi-de-dian-shu-lcof/solution/c-dong-tai-gui-hua-jie-fa-by-yizhe-shi-2/\n\n \"\"\"\n\n def twoSum(self, n: int) -> List[float]:\n dp = []\n for i in range(n + 1):\n dp.append([0.0] * (6 * n + 1))\n for i in range(1, 7):\n dp[1][i] = 1 / 6\n for i in range(2, n + 1):\n for j in range(i, 6 * i + 1):\n dp[i][j] = sum(dp[i - 1][max(1, j - 6):j]) * 1 / 6\n res = [round(i, 5) for i in dp[n] if i > 0]\n return res\n\n\nclass Solution2:\n \"\"\" From Book\"\"\"\n\n def twoSum(self, n: int) -> List[float]:\n if not n:\n return []\n MAX_VALUE = 6\n probabilities = [[0] * (MAX_VALUE * n + 1) for _ in range(2)]\n\n flag = 0\n for i in range(1, MAX_VALUE + 1):\n probabilities[flag][i] = 1\n for k in range(2, n + 1):\n for i in range(k):\n probabilities[1 - flag][i] = 0\n for i in range(k, MAX_VALUE * k + 1):\n probabilities[1 - flag][i] = 0\n for j in range(1, min(i, MAX_VALUE) + 1):\n probabilities[1 - flag][i] += probabilities[flag][i - j]\n flag = 1 - flag\n res = []\n total = MAX_VALUE ** n\n for i in range(n, MAX_VALUE * n + 1):\n res.append(probabilities[flag][i] / total)\n return res\n\n\n@pytest.mark.parametrize(\"args,expected\", [\n (1, [0.16667, 0.16667, 0.16667, 0.16667, 0.16667, 0.16667]),\n (2, [0.02778, 0.05556, 0.08333, 0.11111, 0.13889, 0.16667, 0.13889, 0.11111, 0.08333, 0.05556, 0.02778]),\n])\ndef test_solutions(args, expected):\n def check_equal(res, expected):\n assert len(res) == len(expected)\n for v1, v2 in zip(res, expected):\n assert v1 == pytest.approx(v2, abs=1e-5)\n\n res = Solution().twoSum(args)\n res1 = Solution1().twoSum(args)\n res2 = Solution2().twoSum(args)\n check_equal(res, expected)\n check_equal(res1, expected)\n check_equal(res2, expected)\n\n\nif __name__ == '__main__':\n pytest.main([\"-q\", \"--color=yes\", \"--capture=no\", __file__])\n","repo_name":"Wang-Yann/LeetCodeMe","sub_path":"python/CodingInterviews_2/60_nge-tou-zi-de-dian-shu-lcof.py","file_name":"60_nge-tou-zi-de-dian-shu-lcof.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"40499785619","text":"from numpy import newaxis\nimport numpy as np\n\na=np.floor(10*np.random.random((2,2)))\nprint(a)\n\nb=np.floor(10*np.random.random((2,2)))\nprint(b)\n\nprint(np.column_stack((a,b)))\n\na= np.array([4.,2.])\nb= np.array([2.,8.])\nprint(a[:,newaxis])","repo_name":"M-Rafay/Python","sub_path":"numpy/14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"36940111398","text":"a = int(input())\nasd = input().split()\n\nn = {}\nfor i in asd:\n if i in n.keys():\n n[i] += 1\n else:\n n[i] = 1\n\nfor x in n.items():\n if x[1] > 1:\n print (x[0])","repo_name":"Lis1337/homework_algorithms","sub_path":"theme 12/f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"31842674379","text":"import boto3\nimport pytest\nfrom botocore.stub import Stubber\n\neus = boto3.client(\"eus\")\n\n\n@pytest.fixture(autouse=True)\ndef eus_stub():\n with Stubber(eus) as stubber:\n yield stubber\n stubber.assert_no_pending_responses()\n\n\ndef test_get_unicorn(eus_stub):\n expected = {\n \"Unicorn\": {\"UnicornId\": \"u-abcdef0123\", \"UnicornName\": \"Prongs\"},\n }\n\n eus_stub.add_response(\n \"get_unicorn\", expected, {\"UnicornId\": \"u-abcdef0123\"},\n )\n\n actual = eus.get_unicorn(UnicornId=\"u-abcdef0123\")\n\n assert actual == expected\n\n\ndef test_describe_unicorns(eus_stub):\n expected = {\n \"Unicorns\": [{\"UnicornId\": \"u-abcdef0123\", \"UnicornName\": \"Prongs\"}],\n }\n\n eus_stub.add_response(\n \"describe_unicorns\", expected, {},\n )\n\n actual = eus.describe_unicorns()\n\n assert actual == expected\n","repo_name":"seporaitis/elastic-unicorn-service","sub_path":"tests/test_eus.py","file_name":"test_eus.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"6079551770","text":"#!/usr/bin/python2\n\n# define dictionary keywords for gradebook, assignment and category dictionaries\n\n## gradebook keywords\n### list of assignments\nGRADEBOOK_ASSIGNMENTS = 'entries'\n### list of categories\nGRADEBOOK_CATEGORIES = 'weighting'\n\n## assignment keywords\n### how many points were recieved on the assignment ('my points')\nASSIGNMENT_SCORE_POINTS = 'recieved points'\n### the maximum points (without extra-credit) that can be scored on the assignment ('out of' points)\nASSIGNMENT_MAX_POINTS = 'max points'\n### the percent recieved on the assignment (rounded to two decimal places)\nASSIGNMENT_PERCENT = 'percent'\n### the assignment number (not necessarily continuous)\nASSIGNMENT_NUMBER = 'assignment number'\n### the name of the category the assignment is part of\nASSIGNMENT_CATEGORY = 'category'\n### whether or not the assignment grading is complete as a string Yes/No\nASSIGNMENT_GRADING_COMPLETE = 'grading complete'\n### the string values for whether or not the assignment has been graded\nASSIGNMENT_GRADING_COMPLETE_TRUE = 'Yes'\nASSIGNMENT_GRADING_COMPLETE_FALSE = 'No'\n### assignment name/short description\nASSIGNMENT_NAME = 'description'\n\n## gradebook categories keywords\n### the name of the gradebook category\nCATEGORY_NAME = 'name'\n### the weight of the category (when all categories are active)\nCATEGORY_WEIGHT = 'weight percent'\n### how many points were recieved in the category\nCATEGORY_SCORE_POINTS = 'recieved points'\n### the max points of the category as it stands in Aeries\nCATEGORY_MAX_POINTS = 'max points'\n### name of the category for gradebook totals\nTOTAL_CATEGORY = 'Total'\n### the percentage of the category as it stands in Aeries\nCATEGORY_PERCENT = 'grade percent'\n","repo_name":"DavidHarrison/aeries-tools","sub_path":"Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"6464708657","text":"# Author: Abouzar Ghavami\n# Email: ghavamip@gmail.com\n\n\nimport numpy as np\nimport tensorflow.keras as keras\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport pipeline1_good as pipeline\n\nepochs = 5000\nbatch_size = 32\n\nfn = './timeseries.csv'\n\ndf = pd.read_csv(fn, dtype = object)\n\nX = df.CLOSE.astype('float64')\n\ntrain_percentage = 0.8\nvalidate_percentage = 0.19\ntest_percentage = 0.01\n\ntrain_window_length = 100\ntest_window_length = 10\n\n[train, val, test] = pipeline.pipeline(X, train_percentage = train_percentage, \n val_percentage = validate_percentage, test_percentage = test_percentage, \n batch_size = batch_size,\n train_window_length = train_window_length, \n test_window_length = test_window_length)\nx_train = X_train.reshape(-1, 1)\n\ndeep = keras.models.Sequential([\n keras.layers.Flatten(input_shape = [len(X_train[0]), 1]),\n keras.layers.BatchNormalization(),\n keras.layers.Conv1D(filters = 20, kernel_size = 4, strides = 2, padding = 'valid'), #input_shape = [None, 1]), \n keras.layers.LSTM(40, return_sequences = True, input_shape = [None, 1]),\n keras.layers.Dropout(rate = 0.2),\n keras.layers.LayerNormalization(),\n keras.layers.LSTM(40, return_sequences = True), \n keras.layers.Dropout(rate = 0.2),\n keras.layers.LayerNormalization(),\n keras.layers.LSTM(test_window_length, activation = 'linear')])\ndeep.compile(optimizer = 'adam', loss = 'mse')\nmin_val_save = keras.callbacks.ModelCheckpoint(''.join(['Ex11_', str(epochs), '.hdf5']), save_best_only=True, monitor='val_loss', mode='min')\nhistory = deep.fit(train, validation_data = val, epochs = epochs, batch_size = 32, \n callbacks=[min_val_save])\ny_pred = deep.predict(test)\nmse_deep = np.mean(keras.losses.mean_squared_error(y_test, y_pred))\nprint(mse_deep)\nseries = generate_time_series(1, n_steps + 10)\nX_new, Y_new = series[:, :n_steps], series[:, n_steps:]\nY_pred = deep.predict(X_new)\n\nplt.plot([i for i in range(n_steps + 10)], series[0])\nplt.plot([i for i in range(n_steps,n_steps + 10)], Y_pred[0])\nplt.show()\n","repo_name":"AbouzarGhavami/SampleCodes","sub_path":"SampleCodes/timeseriesprediction/RNN_1.py","file_name":"RNN_1.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"20167982739","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Dec 9 10:49:21 2022\r\n\r\n@author: lab\r\n\"\"\"\r\n\r\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\nfrom random import randint\r\n\r\ndef move_button(evento):\r\n evento.widget.place(x = randint(0, 100), y = randint(0,100))\r\n\r\ndef press_button():\r\n messagebox.showinfo(\"titulo\", \"ganaste\")\r\n\r\nroot = Tk()\r\nroot.title(\"Game\")\r\nroot.geometry(\"200x200\")\r\n\r\nbtn = Button(root, text =\"Press me\",command = press_button)\r\nbtn.place(x = 70,y = 20)\r\nbtn.bind(\"\", move_button)\r\n\r\nroot.mainloop()","repo_name":"Medardo90/POO_eventos_tkinter_061222","sub_path":"eventosdeber1_eje5.py","file_name":"eventosdeber1_eje5.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"21797673595","text":"from __future__ import annotations\n\nimport logging\n\nfrom dotenv import load_dotenv\nfrom flask import Flask, request, jsonify\nfrom http.client import HTTPConnection\n\nfrom c8y_api.app import MultiTenantCumulocityApp\n\n\n# A multi-tenant aware Cumulocity application can be created just like this.\n# The bootstrap authentication information is read from the standard\n# Cumulocity environment variables that are injected into the Docker\n# container.\n# The MultiTenantCumulocityApp class is not a CumulocityApi instance (in\n# contrast to SimpleCumulocityApp), it acts as a factory to provide\n# specific CumulocityApi instances for subscribed tenants and users.\n\n# load environment from a .env if present\nload_dotenv()\n\n# enable full logging for requests\nHTTPConnection.debuglevel = 1\nlogging.basicConfig()\nlogging.getLogger().setLevel(logging.DEBUG)\nrequests_log = logging.getLogger(\"requests.packages.urllib3\")\nrequests_log.setLevel(logging.DEBUG)\nrequests_log.propagate = True\n\n# initialize cumulocity\nc8yapp = MultiTenantCumulocityApp()\nlogging.info(\"CumulocityApp initialized.\")\nc8y_bootstrap = c8yapp.bootstrap_instance\nlogging.info(f\"Bootstrap: {c8y_bootstrap.base_url}, Tenant: {c8y_bootstrap.tenant_id}, User:{c8y_bootstrap.username}\")\n\n\n# setup Flask\nwebapp = Flask(__name__)\n\n\n@webapp.route(\"/health\")\ndef health():\n \"\"\"Return dummy health string.\"\"\"\n return jsonify({'status': 'ok'})\n\n\n@webapp.route(\"/tenant\")\ndef tenant_info():\n \"\"\"Return subscribed tenant's ID, username and devices it has access to.\"\"\"\n # The subscribed tenant's credentials (to access Cumulocity and to access\n # the microservice) are part of the inbound request's headers. This is\n # resolved automatically when using the get_tenant_instance function.\n c8y = c8yapp.get_tenant_instance(headers=request.headers)\n logging.info(f\"Obtained tenant instance: tenant: {c8y.tenant_id}, user: {c8y.username}, pass: {c8y.auth.password}\")\n # If the tenant ID is known (e.g. from URL) it can be given directly\n # like this:\n # c8y = c8yapp.get_tenant_instance(tenant_id='t12345')\n tenant_json = {'tenant_id': c8y.tenant_id,\n 'base_url': c8y.base_url,\n 'username': c8y.username}\n devices_json = [{'name': d.name,\n 'id': d.id,\n 'type': d.type} for d in c8y.device_inventory.get_all()]\n info_json = {'tenant': tenant_json,\n 'devices': devices_json}\n return jsonify(info_json)\n\n\n@webapp.route(\"/user\")\ndef user_info():\n \"\"\"Return user's tenant, username and devices they have access to.\"\"\"\n # The user's credentials (to access Cumulocity and to access the\n # microservice) are part of the inbound request's headers. This is\n # resolved automatically when using the get_user_instance function.\n c8y = c8yapp.get_user_instance(request.headers)\n logging.info(f\"Obtained user instance: tenant: {c8y.tenant_id}, user: {c8y.username}\")\n devices_json = [{'name': d.name,\n 'id': d.id,\n 'type': d.type} for d in c8y.device_inventory.get_all()]\n info_json = {'username': c8y.username,\n 'devices': devices_json}\n return jsonify(info_json)\n\n\nwebapp.run(host='0.0.0.0', port=80)\n","repo_name":"SoftwareAG/cumulocity-python-api","sub_path":"samples/multi_tenant_app.py","file_name":"multi_tenant_app.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"44"} +{"seq_id":"40542190864","text":"class Customer:\n def __init__(self, customer_id: int,\n customer_name: str,\n contact_name: str,\n address: str,\n city: str,\n country: str,\n postal_code: str):\n self.customer_id = customer_id\n self.customer_name = customer_name\n self.contact_name = contact_name\n self.address = address\n self.city = city\n self.postal_code = postal_code\n self.country = country\n","repo_name":"godwinaden/RCM-engineering-interview","sub_path":"sql/customer.py","file_name":"customer.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"70141507012","text":"Settings.AutoDetectKeyboardLayout = False\nattackToggleAccOne = Region(Region(218,960,88,72))\nattackToggleAccTwo = Region(Region(1192,956,82,74))\n\nmsgErrorBoxAccOneTest = Region(Region(12,378,384,244))\nmsgErrorBoxAccTwoTest = Region(Region(981,251,352,270))\nradar = Region(Region(758,247,123,69))\ndef attackWarden(nthTime):\n if nthTime == 0 or nthTime == 3:\n ''' heal 21212 '''\n type(Key.TAB)\n type(\"+\")\n sleep(0.5)\n type(\"6\", KeyModifier.CTRL)\n sleep(1)\n type(\"2\")\n sleep(1)\n type(\"5\", KeyModifier.CTRL)\n sleep(1)\n type(\"4\")\n sleep(1)\n ''' aoe bleed 3232 '''\n type(\"3\")\n sleep(1)\n type(\"1\", KeyModifier.CTRL)\n sleep(0.5)\n type(\"e\")\n sleep(0.5)\n type(\"4\") \n elif nthTime == 1 or nthTime == 4:\n ''' aoe bleed 323 '''\n type(\"2\", KeyModifier.CTRL)\n sleep(1)\n type(\"r\")\n sleep(1)\n type(\"4\")\n else:\n ''' spear bleed 3131 '''\n type(\"3\")\n sleep(1)\n type(\"3\", KeyModifier.CTRL)\n sleep(1)\n type(\"q\")\n sleep(1)\n type(\"4\")\n\n \n\ndef attackCappy(nthTime):\n if nthTime == 0 or nthTime == 3:\n type(Key.TAB)\n type(\"1\", KeyModifier.CTRL)\n sleep(1.5)\n type(\"1\")\n sleep(1.5)\n type(\"2\")\n sleep(2)\n type(\"4\")\n sleep(0.6)\n type(\"q\")\n sleep(1.5)\n type(\"6\")\n elif nthTime == 1 or nthTime == 4:\n type(\"2\", KeyModifier.CTRL)\n sleep(1.5)\n type(\"5\", KeyModifier.CTRL)\n sleep(1.5)\n type(\"5\")\n sleep(2)\n type(\"4\")\n sleep(0.6)\n type(\"q\")\n sleep(1.5)\n type(\"6\")\n else:\n type(\"6\", KeyModifier.CTRL)\n sleep(2)\n type(\"3\", KeyModifier.CTRL)\n sleep(2)\n type(\"4\", KeyModifier.CTRL)\n \n\ndef turnAround():\n keyDown(Key.RIGHT)\n sleep(1)\n keyUp(Key.RIGHT)\n type(\"u\")\n\ndef checkRadar(currentLocation):\n if radar.exists(Pattern(\"1586521106235.png\").exact(), 0):\n click(Location(471, 496))\n keyDown(\"s\")\n wait(7)\n keyUp(\"s\")\n click(currentLocation)\n\n \ndef findShards(location, attackToggle, attackTogglePatternActive, attackTogglePatternActiveTwo, attackTogglePatternDeactive, attackClass, msgError):\n click(location)\n\n for i in range(0,1):\n checkRadar(location) \n if attackToggle.exists(attackTogglePatternActive, 0) or attackToggle.exists(attackTogglePatternActiveTwo, 0):\n howManyAttack = 0\n while(True):\n '''\n THE CHARACTERS MUST LOOK UP!! For this to work\n '''\n type(Key.TAB)\n attackClass(howManyAttack)\n checkRadar(location)\n if attackToggle.exists(attackTogglePatternDeactive, 2) or howManyAttack == 5:\n break\n howManyAttack = howManyAttack + 1\n '''\n If its the first acc nd goes out of bonds skip the select\n '''\n\n type(\"v\")\n wait(0.3)\n type(\"u\")\n if msgError.exists(Pattern(\"1586133232245-1.png\").similar(0.69),0.5) or msgError.exists(\"1586135237300-1.png\", 0):\n keyDown(Key.LEFT)\n sleep(0.4)\n keyUp(Key.LEFT)\n \n if msgError.exists(Pattern(\"1586133795162-1.png\").similar(0.74), 0.5):\n turnAround()\n \n\nwhile(True):\n '''\n weaker macro without corpse\n '''\n '''\n Activate account one, Do the script\n '''\n \n findShards(Location(471, 496), attackToggleAccOne, \"1586181739997-1.png\", \"1586211653840.png\", Pattern(\"1586207069969.png\").similar(0.80), attackWarden, msgErrorBoxAccOneTest)\n \n\n '''\n Activate account two, Do the script\n '''\n findShards(Location(1431, 477), attackToggleAccTwo, \"1586181739997-1.png\", \"1586211653840.png\", Pattern(\"1586207069969.png\").similar(0.80), attackCappy, msgErrorBoxAccTwoTest)\n\n\n\n \n\n","repo_name":"Blagoj5/macros","sub_path":"Sikulix/shard farming.sikuli/shard farming.py","file_name":"shard farming.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"27236425888","text":"# Exercise 1. Multiplication\n#\n# Write a Python function to multiply all the positive numbers in a list.\n# The function should return that result.\n\n\ndef multiply_positives(numbers):\n \"\"\"\n Assuming as input a non-empty list of numerical values,\n it returns the multiplication of all the positive ones.\n \"\"\"\n result = 1\n for number in numbers:\n if number > 0:\n result *= number\n return result\n\n\nprint(multiply_positives([-1, 2, -3, 4, -5]))\n","repo_name":"lumc-python/day-2-functions-mihailefter","sub_path":"ex1_multiplication.py","file_name":"ex1_multiplication.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"25873206429","text":"import time\nimport os\nimport sys\nimport random\nimport math\nimport json\nimport subprocess\nimport subprocess\nfrom pathlib import Path\n\n\ndef goto(url):\n script_path = getScriptPath('goto.js')\n cmd = f\"node {script_path} '{url}'\"\n ps = subprocess.check_output(cmd, shell=True)\n return ps\n\n\ndef getScriptPath(name):\n return os.path.join(\n Path(__file__).parent.parent,\n 'cdp/' + name\n )\n\n\ndef getPageSource():\n cmd = 'node ' + getScriptPath('page_source.js')\n ps = subprocess.check_output(cmd, shell=True)\n return ps\n\n\ndef evalJS(command):\n with open('/tmp/evalCommand.txt', 'w') as f:\n f.write(command)\n\n script_path = getScriptPath('eval_js.js')\n cmd = f\"node {script_path}\"\n ps = subprocess.check_output(cmd, shell=True)\n return ps\n\n\ndef getCoords(selector, randomize_within_bcr=True, highlight_bb=True):\n \"\"\"\n - selector: The CSS selector to get the coords for\n - randomize_within_bcr: select a random coordinate within the bounding box\n hight\n - highlight_bb: visually highlight the bounding box for debugging purposes\n \"\"\"\n script_path = getScriptPath('coords.js')\n cmd = f\"node {script_path} '{selector}'\"\n coords = subprocess.check_output(cmd, shell=True)\n coords = coords.decode()\n\n x, y = 0, 0\n\n try:\n parsed = json.loads(coords)\n x, y, width, height = parsed['x'], parsed['y'], parsed['width'], parsed['height']\n\n if randomize_within_bcr:\n # print(x, y, parsed['width'], parsed['height'])\n x += random.randint(0, math.floor(parsed['width'] / 4))\n y += random.randint(0, math.floor(parsed['height'] / 4))\n\n if highlight_bb:\n # Just add a red thick border around the CSS selector\n cmd = \"\"\"var el = document.querySelector('\"\"\" + selector + \\\n \"\"\"'); if (el) { el.style.border = \"2px solid #ff0000\"; }\"\"\"\n evalJS(cmd)\n\n except Exception as e:\n print('getCoords() failed with Error: {}'.format(e))\n return None\n\n return x, y\n\n\ndef startBrowser(args=[], startInTempDir=False, chromeProfile='--profile-directory=\"Default\"'):\n tempDirStr = ''\n if startInTempDir:\n tempDirStr = f'--user-data-dir=/tmp'\n\n arg_str = ' '.join(args)\n if sys.platform == 'darwin':\n chromePath = '/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome'\n # On MacOS Monterey, we need to start Google Chrome\n # in fullscreen mode to get the correct coordinates.\n startCmd = f'{chromePath} --remote-debugging-port=9222 --start-maximized {tempDirStr} {chromeProfile} --disable-notifications --start-fullscreen {arg_str} 1>out.log 2>err.log &'\n else:\n startCmd = f'google-chrome --remote-debugging-port=9222 --start-maximized --disable-notifications {arg_str} 1>out.log 2>err.log &'\n\n if os.getenv('DOCKER') == '1':\n startCmd = 'google-chrome --remote-debugging-port=9222 --no-sandbox --disable-notifications --start-maximized --no-first-run --no-default-browser-check 1>out.log 2>err.log &'\n\n print(startCmd)\n subprocess.Popen([startCmd], shell=True)\n time.sleep(random.uniform(3, 4))\n\n\ndef closeBrowser():\n print('closing browser')\n if sys.platform == 'darwin':\n os.system(\"killall -9 'Google Chrome'\")\n else:\n os.system(\"killall -9 'google-chrome'\")\n","repo_name":"NikolaiT/stealthy-scraping-tools","sub_path":"behavior/sst_utils.py","file_name":"sst_utils.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","stars":132,"dataset":"github-code","pt":"44"} +{"seq_id":"9997224554","text":"from unittest.mock import Mock, patch\n\nimport pytest\n\n\ndef test_scalar_custom_scalar_inst():\n from tartiflette.scalar.scalar import Scalar\n\n s = Scalar(\"A\")\n assert s.name == \"A\"\n assert s._implementation is None\n assert s._schema_name == \"default\"\n\n\n@pytest.fixture\ndef a_scalar():\n from tartiflette.scalar.scalar import Scalar\n\n return Scalar(\"A\")\n\n\ndef test_scalar_custom_scalar_bake_raises(a_scalar):\n from tartiflette.types.exceptions.tartiflette import (\n UnknownScalarDefinition,\n )\n\n with pytest.raises(Exception):\n a_scalar.bake(None)\n\n sch = Mock()\n sch.find_scalar = Mock(return_value=None)\n\n a_scalar._implementation = \"A\"\n\n with pytest.raises(UnknownScalarDefinition):\n a_scalar.bake(sch)\n\n assert sch.find_scalar.call_args_list == [((\"A\",),)]\n\n\ndef test_scalar_custom_scalar_bake(a_scalar):\n a_gql_scalar = Mock()\n\n sch = Mock()\n sch.find_scalar = Mock(return_value=a_gql_scalar)\n\n a_scalar._implementation = Mock()\n a_scalar._implementation.coerce_output = Mock()\n a_scalar._implementation.coerce_input = Mock()\n\n assert a_scalar.bake(sch) is None\n assert a_gql_scalar.coerce_output is a_scalar._implementation.coerce_output\n assert a_gql_scalar.coerce_input is a_scalar._implementation.coerce_input\n assert sch.find_scalar.call_args_list == [((\"A\",),)]\n\n\ndef test_scalar_custom_scalar___call__(a_scalar):\n with patch(\n \"tartiflette.schema.registry.SchemaRegistry.register_scalar\",\n return_value=None,\n ) as mocked_register:\n r = a_scalar(\"R\")\n assert r == \"R\"\n assert mocked_register.call_args_list == [((\"default\", a_scalar),)]\n assert a_scalar._implementation == \"R\"\n","repo_name":"tartiflette/tartiflette","sub_path":"tests/unit/scalar/test_custom_scalar.py","file_name":"test_custom_scalar.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":849,"dataset":"github-code","pt":"44"} +{"seq_id":"16701425642","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Write a Python program to select the odd items of a list\n\nliste = [\"dog\", \"cat\", \"mouse\", \"cow\", \"horse\", \"goat\", \"ship\", \"snail\"]\n\ni = 0\n\nwhile i < len(liste):\n\tif i % 2 != 0:\n\t\tprint(liste[i])\n\ti = i +1\n\n","repo_name":"Moandh81/python-self-training","sub_path":"lists/46.py","file_name":"46.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"16087634808","text":"\"\"\"Repositories for the loan offer domain.\"\"\"\n\nfrom lms.api.v1 import fields\nfrom lms.database import models\nfrom lms.domain.repositories import database, generic\n\n\nclass LoanOfferOdmRepository(\n database.MongoRepository[\n models.LoanOffer,\n fields.LoanOfferCreate,\n fields.LoanOfferUpdate,\n fields.LoanOfferOut,\n ]\n):\n \"\"\"LoanOffer ODM repository.\"\"\"\n\n table = models.LoanOffer\n schema = fields.LoanOfferOut\n","repo_name":"christhoval06/fastapi--lms","sub_path":"lms/domain/loan_offer/repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"39952532020","text":"class Solution:\n def minFlips(self, mat: List[List[int]]) -> int:\n \"\"\"\n #backtrack #bruteforce\n \"\"\"\n m, n = len(mat), len(mat[0])\n def flip(i, j):\n for i, j in (i, j), (i+1, j), (i-1, j), (i, j+1), (i, j-1):\n if 0 <= i < m and 0 <= j < n:\n mat[i][j] ^= 1\n possible = set()\n # row by row, when reached last row, all cell should be 0\n def backtrack(i, j, flips):\n if j == n:\n i, j = i+1, 0\n if i == m:\n if max(mat[-1]) == 0:\n possible.add(flips)\n return\n if i == 0 or mat[i-1][j] == 0:\n backtrack(i, j+1, flips)\n if i == 0 or mat[i-1][j] == 1:\n flip(i, j)\n backtrack(i, j+1, flips+1)\n flip(i, j)\n backtrack(0, 0, 0)\n return min(possible, default=-1)","repo_name":"ruohanliu/leetcode","sub_path":"python/1284 minFlips.py","file_name":"1284 minFlips.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"17427235895","text":"import json\nimport string\nimport pandas as pd\n# import spacy\n# import nltk\n\ncount = 0\nreviews=[]\nstars=[]\nbusiness_id=[]\n# nltk.download('punkt')\n# en = spacy.load('en_core_web_sm')\n# excluded_words_list = en.Defaults.stop_words\n# for p in string.punctuation:\n# excluded_words_list.add(p)\n# excluded_words_list.add('\\'s')\n# excluded_words_list.add('n\\'t')\n# excluded_words_list.add(\"''\")\n# excluded_words_list.add(\"``\")\n\nwith open('/Users/enity/Downloads/text_group_work/yelp_dataset/yelp_academic_dataset_review.json', encoding='utf-8') as f:\n for line in f:\n line_contents = json.loads(line)\n reviews.append(line_contents['text'])\n stars.append(int(line_contents['stars']))\n # business_id.append(line_contents['business_id'])\n count+=1\n if count == 400000:\n break\n# print(\"open file end\")\n# final_reviews=[]\n# for r in reviews:\n# tokens = nltk.word_tokenize(r)\n# after_tokens = [word for word in tokens if word not in excluded_words_list]\n# final_reviews.append(after_tokens)\n\n# df = pd.DataFrame({\"text\":reviews,\"stars\":stars,\"business_id\":business_id})\n\ndf = pd.DataFrame({\"text\":reviews,\"stars\":stars})\ndf = df.loc[300000:400000,:]\ndf = df.loc[df['stars'] != 3]\ndf['sentiment']=df.apply(lambda x: 1 if x.stars>=4 else 0,axis=1)\ndf = df.drop('stars',axis=1)\nprint(df.shape)\ndf.to_csv(\"reviews_train_dataset.csv\",index=False)\nprint('end')\n# df_low_stars=df.loc[df['stars']==1,:]\n\n# business_list=set()\n# for index,row in df_low_stars.iterrows():\n# business_list.add(row['business_id'])\n# if len(business_list) == 50:\n# break\n\n# print(len(business_list))\n\n# df_result = pd.DataFrame(columns=['text','stars','business_id'])\n# for b_id in business_list:\n# result = df.loc[(df[\"business_id\"] == b_id) & (df['stars'] == 1), :]\n# df_result=df_result.append(result.iloc[0])\n# df_result.to_csv(\"random_result.csv\",index=False)\n\n\n","repo_name":"legendzzy/sentiment-analysis-LSTM","sub_path":"split_patial_reviews.py","file_name":"split_patial_reviews.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"32457272129","text":"import SVT\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport math\r\ndef repeatTest(num,rank):\r\n svt_rmse = []\r\n svtp_rmse = []\r\n svt_nomissing_rmse = []\r\n for i in range(num):\r\n svt_m,svtRmse = SVT.testSVT()\r\n svt_rmse.append(svtRmse)\r\n svt_m,svtpRmse = SVT.testCURSVT([],rank)\r\n svtp_rmse.append(svtpRmse)\r\n # svt_m,SVTNoRmse = SVT.testSVT(False)\r\n # svt_nomissing_rmse.append(SVTNoRmse)\r\n svt_nomissing_rmse.append(0.005547751681770088)\r\n os.system('cls')\r\n print(i)\r\n return svt_rmse,svtp_rmse,svt_nomissing_rmse\r\ndef plotRepeatGraph():\r\n svt_rmse,svtp_rmse,svt_nomissing_rmse = repeatTest(10,5)\r\n # svt_rmse = [1.6,1.5,1.6,1.5,1.6,1.5,1.6,1.5,1.6,1.5]\r\n # svtp_rmse = [0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2]\r\n # svt_nomissing_rmse = [0.002,0.002,0.002,0.002,0.002,0.002,0.002,0.002,0.002,0.002]\r\n x_coordinate = range(len(svt_rmse))\r\n plt.xlabel('experiment times')\r\n plt.ylabel('RMSE')\r\n plt.plot(x_coordinate,svt_rmse,color='black',linewidth=1.0, linestyle='-')\r\n plt.plot(x_coordinate, svtp_rmse, color='red', linewidth=1.0, linestyle='-')\r\n plt.plot(x_coordinate, svt_nomissing_rmse, color='blue', linewidth=1.0, linestyle='--')\r\n plt.show()\r\n\r\nMAX_RANK = 30\r\ndef plotRanksGraph():\r\n svtp_rmse = []\r\n svt_nomissing_rmse = []\r\n for rank in range(1,MAX_RANK):\r\n svt_m,svtpRmse = SVT.testCURSVT([],rank)\r\n svtp_rmse.append(svtpRmse)\r\n # svt_m,SVTNoRmse = SVT.testSVT(False)\r\n # svt_nomissing_rmse.append(SVTNoRmse)\r\n svt_nomissing_rmse.append(0.005547751681770088)\r\n os.system('cls')\r\n print(rank)\r\n x_coordinate = range(1,MAX_RANK)\r\n plt.xlabel('RANK')\r\n plt.ylabel('RMSE')\r\n plt.plot(x_coordinate, svtp_rmse, color='red', linewidth=1.0, linestyle='-')\r\n plt.plot(x_coordinate, svt_nomissing_rmse, color='blue', linewidth=1.0, linestyle='--')\r\n plt.show()\r\n\r\n\r\ndef plotMissingProportionGraph():\r\n total = 90*522\r\n prop = 0.1\r\n svt_rmse_avg_list = []\r\n svtp_rmse_avg_list = []\r\n svt_nomissing_rmse_avg_list=[]\r\n x_coordinate = []\r\n while prop < 0.95:\r\n print(\"Proportion\")\r\n print(prop)\r\n x_coordinate.append(prop)\r\n missing = total*prop\r\n missing_col_num = int(math.sqrt((missing/6)))\r\n missing_row_num = int(6*math.sqrt((missing/6)))\r\n SVT.df.MISSING_COL_NUM = missing_col_num\r\n SVT.df.MISSING_ROW_NUM = missing_row_num\r\n svt_rmse,svtp_rmse,svt_nomissing_rmse = repeatTest(3,5)\r\n svt_rmse_avg = sum(svt_rmse)/len(svt_rmse)\r\n svt_rmse_avg_list.append(svt_rmse_avg)\r\n svtp_rmse_avg = sum(svtp_rmse)/len(svtp_rmse)\r\n svtp_rmse_avg_list.append(svtp_rmse_avg)\r\n svt_nomissing_rmse_avg = 0.005547751681770088\r\n svt_nomissing_rmse_avg_list.append(svt_nomissing_rmse_avg)\r\n prop = prop + 0.1\r\n \r\n \r\n\r\n plt.xlabel('Missing Proportion')\r\n plt.ylabel('rmse')\r\n plt.plot(x_coordinate,svt_rmse_avg_list,color='black',linewidth=1.0, linestyle='-')\r\n plt.plot(x_coordinate, svtp_rmse_avg_list, color='red', linewidth=1.0, linestyle='-')\r\n plt.plot(x_coordinate, svt_nomissing_rmse_avg_list, color='blue', linewidth=1.0, linestyle='--')\r\n plt.show()\r\n\r\nif __name__ == '__main__':\r\n # plotRepeatGraph()\r\n # plotRanksGraph()\r\n plotMissingProportionGraph()\r\n\r\n\r\n","repo_name":"yangshuoc/pku_SVT_plus","sub_path":"ResultGraph.py","file_name":"ResultGraph.py","file_ext":"py","file_size_in_byte":3411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"31533520743","text":"import sys, pygame, time\n\npygame.init()\nsize = 320, 320\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption(\"Connect Four\")\n\nWHITE = 255, 255, 255\nBLACK = 0, 0, 0\nYELLOW = 255, 255, 0\nRED = 255, 0, 0\nBLUE = 0, 0, 255\n\nclass TwoPlayer:\n\n ##Gameplay##\n board = []\n turn = 'Y'\n score = [0, 0]\n last_added = [0,0] #handles undo\n undone = True\n ##Display##\n marker = pygame.image.load(\"arrow.png\")\n markerrect = marker.get_rect()\n turn_indicator = pygame.image.load(\"turn.png\")\n font = pygame.font.Font(None, 28)\n ###########\n \n def __init__(self):\n screen.fill(BLUE)\n for i in range(7):\n self.board.append([])\n for j in range(6):\n self.board[i].append('E')\n pygame.draw.ellipse(screen, WHITE, [40*(i+0.5), 40*(j+0.5)+40, 40, 40]) \n self.markerrect.left = 30\n self.markerrect.top = 300\n screen.blit(self.marker, self.markerrect)\n screen.blit(self.turn_indicator, [0, 0])\n pygame.draw.ellipse(screen, YELLOW, [110, 10, 20, 20])\n text = self.font.render(\"Y: 0 R: 0\", 1, WHITE)\n screen.blit(text, [160, 10])\n pygame.display.flip()\n \n def print_board(self):\n screen.fill(BLUE)\n for i in range(7):\n for j in range(6):\n if self.board[i][j] == 'E':\n pygame.draw.ellipse(screen, WHITE, [40*(i+0.5), 40*(j+0.5)+ 40, 40, 40])\n elif self.board[i][j] == 'Y':\n pygame.draw.ellipse(screen, YELLOW, [40*(i+0.5), 40*(j+0.5)+ 40, 40, 40])\n elif self.board[i][j] == 'R':\n pygame.draw.ellipse(screen, RED, [40*(i+0.5), 40*(j+0.5)+ 40, 40, 40])\n screen.blit(self.turn_indicator, [0, 0])\n if self.turn == 'Y':\n pygame.draw.ellipse(screen, YELLOW, [110, 10, 20, 20])\n else:\n pygame.draw.ellipse(screen, RED, [110, 10, 20, 20])\n text = self.font.render(\"Y: \" + str(self.score[0]) + \" R: \" + str(self.score[1]), 1, WHITE)\n screen.blit(text, [160, 10])\n pygame.display.flip()\n \n def print_marker(self):\n screen.blit(self.marker, self.markerrect)\n pygame.display.flip()\n \n def moveleft(self):\n self.markerrect.left = self.markerrect.left - 40\n screen.blit(self.marker, self.markerrect) \n pygame.display.flip()\n\n def moveright(self):\n self.markerrect.right = self.markerrect.right + 40\n screen.blit(self.marker, self.markerrect) \n pygame.display.flip()\n\n def place_chip(self):\n i = (self.markerrect.left - 30) / 40\n for j in range(6):\n if self.board[i][5 - j] == 'E':\n if self.turn == 'Y':\n pygame.draw.ellipse(screen, YELLOW, [40*(i+0.5), 40*((5-j)+0.5)+40, 40, 40])\n self.board[i][5-j] = 'Y'\n self.last_added[0] = i\n self.last_added[1] = 5 - j\n elif self.turn == 'R':\n pygame.draw.ellipse(screen, RED, [40*(i+0.5), 40*((5-j)+0.5)+40, 40, 40])\n self.board[i][5-j] = 'R'\n self.last_added[0] = i\n self.last_added[1] = 5 - j\n self.undone = False\n screen.blit(self.marker, self.markerrect) \n pygame.display.flip()\n return True\n return False \n \n def connect(self, i, j, x_dir, y_dir):\n if(x_dir == 0 and y_dir == 1):\n pygame.draw.line(screen, BLACK, [40*(i+1), 40*(7-j)], [40*(i+1), 40*(4-j)], 5)\n pygame.display.flip()\n elif(x_dir == 1 and y_dir == 0):\n pygame.draw.line(screen, BLACK, [40*(i+1), 40*(7-j)], [40*(i+4), 40*(7-j)], 5)\n pygame.display.flip()\n elif(x_dir == -1 and y_dir == 1):\n pygame.draw.line(screen, BLACK, [40*(i+1), 40*(7-j)], [40*(i-2), 40*(4-j)], 5)\n pygame.display.flip()\n elif(x_dir == 1 and y_dir == 1):\n pygame.draw.line(screen, BLACK, [40*(i+1), 40*(7-j)], [40*(i+4), 40*(4-j)], 5)\n pygame.display.flip()\n \n def check(self, depth, i, j, x_dir, y_dir):\n if(depth == 3):\n return True\n elif(j - y_dir < 0 or j - y_dir > 5 or i + x_dir < 0 or i + x_dir > 6):\n return False\n elif(self.board[i + x_dir][j - y_dir] == self.turn):\n if(self.check(depth + 1, i + x_dir, j - y_dir, x_dir, y_dir)):\n return True\n return False\n \n def check_board(self):\n for i in range(7):\n for j in range(6):\n if(self.board[i][5-j] == self.turn):\n for k in range(-1, 2):\n for l in range(0, 2):\n if(not(k == 0 and l == 0)):\n if(self.check(0, i, 5 - j, k, l)):\n self.connect(i, j, k, l)\n if(self.turn == 'Y'):\n self.turn = 'R'\n pygame.draw.ellipse(screen, RED, [110, 10, 20, 20])\n else:\n self.turn = 'Y'\n pygame.draw.ellipse(screen, YELLOW, [110, 10, 20, 20])\n return True\n if(self.turn == 'Y'):\n self.turn = 'R'\n pygame.draw.ellipse(screen, RED, [110, 10, 20, 20])\n else:\n self.turn = 'Y'\n pygame.draw.ellipse(screen, YELLOW, [110, 10, 20, 20])\n pygame.display.update() \n return False\n\n def undo(self):\n self.undone = True\n self.board[self.last_added[0]][self.last_added[1]] = 'E'\n if self.turn == 'Y':\n self.turn = 'R'\n else:\n self.turn = 'Y'\n self.print_board()\n screen.blit(self.marker, self.markerrect)\n pygame.display.flip()\n\n def reset_game(self):\n for i in range(7):\n for j in range(6):\n self.board[i][j] = 'E'\n\n def display_winner(self):\n if self.turn == 'R':\n winner = pygame.image.load(\"ywins.png\")\n screen.fill(WHITE)\n screen.blit(winner, [0,0])\n pygame.display.flip()\n self.score[0] = self.score[0] + 1\n else:\n winner = pygame.image.load(\"rwins.png\")\n screen.fill(WHITE)\n screen.blit(winner, [0,0])\n pygame.display.flip()\n self.score[1] = self.score[1] + 1\n\n done = 1\n while done:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n done = 0\n self.reset_game()\n self.print_board()\n else:\n done = 1\n \n","repo_name":"kcrowe01/My_Projects","sub_path":"connect_four/TwoP.py","file_name":"TwoP.py","file_ext":"py","file_size_in_byte":7069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"10164502201","text":"import os\nimport typing as t\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\n\nfrom unstructured.ingest.error import SourceConnectionError, SourceConnectionNetworkError\nfrom unstructured.ingest.interfaces import (\n BaseConnectorConfig,\n BaseSingleIngestDoc,\n BaseSourceConnector,\n IngestDocCleanupMixin,\n SourceConnectorCleanupMixin,\n SourceMetadata,\n)\nfrom unstructured.ingest.logger import logger\nfrom unstructured.utils import requires_dependencies\n\nif t.TYPE_CHECKING:\n from wikipedia import WikipediaPage\n\n\n@dataclass\nclass SimpleWikipediaConfig(BaseConnectorConfig):\n title: str\n auto_suggest: bool = False\n\n\n@dataclass\nclass WikipediaIngestDoc(IngestDocCleanupMixin, BaseSingleIngestDoc):\n connector_config: SimpleWikipediaConfig = field(repr=False)\n\n @property\n @requires_dependencies([\"wikipedia\"], extras=\"wikipedia\")\n def page(self) -> \"WikipediaPage\":\n import wikipedia\n\n return wikipedia.page(\n self.connector_config.title,\n auto_suggest=self.connector_config.auto_suggest,\n )\n\n def get_filename_prefix(self) -> str:\n title: str = str(self.connector_config.title)\n title = \" \".join(title.split()).replace(\" \", \"-\")\n return title\n\n @property\n def filename(self) -> Path:\n raise NotImplementedError()\n\n @property\n def text(self) -> str:\n raise NotImplementedError()\n\n @property\n def _output_filename(self):\n raise NotImplementedError()\n\n @property\n def date_created(self) -> t.Optional[str]:\n return None\n\n @property\n def date_modified(self) -> t.Optional[str]:\n return None\n\n @property\n def record_locator(self) -> t.Optional[t.Dict[str, t.Any]]:\n return {\n \"page_title\": self.connector_config.title,\n \"page_url\": self.source_metadata.source_url, # type: ignore\n }\n\n def _create_full_tmp_dir_path(self):\n self.filename.parent.mkdir(parents=True, exist_ok=True)\n\n @requires_dependencies([\"wikipedia\"], extras=\"wikipedia\")\n def update_source_metadata(self):\n from wikipedia.exceptions import PageError\n\n try:\n page = self.page\n except PageError:\n self.source_metadata = SourceMetadata(\n exists=False,\n )\n return\n\n self.source_metadata = SourceMetadata(\n version=page.revision_id,\n source_url=page.url,\n exists=True,\n )\n\n @SourceConnectionError.wrap\n @BaseSingleIngestDoc.skip_if_file_exists\n def get_file(self):\n \"\"\"Fetches the \"remote\" doc and stores it locally on the filesystem.\"\"\"\n self._create_full_tmp_dir_path()\n logger.debug(f\"Fetching {self} - PID: {os.getpid()}\")\n self.update_source_metadata()\n with open(self.filename, \"w\", encoding=\"utf8\") as f:\n f.write(self.text)\n\n\n@dataclass\nclass WikipediaIngestHTMLDoc(WikipediaIngestDoc):\n registry_name: str = \"wikipedia_html\"\n\n @property\n def filename(self) -> Path:\n return (\n Path(self.read_config.download_dir) / f\"{self.get_filename_prefix()}.html\"\n ).resolve()\n\n @property\n def text(self):\n return self._get_html()\n\n @SourceConnectionNetworkError.wrap\n def _get_html(self):\n return self.page.html()\n\n @property\n def _output_filename(self):\n return Path(self.processor_config.output_dir) / f\"{self.get_filename_prefix()}-html.json\"\n\n\n@dataclass\nclass WikipediaIngestTextDoc(WikipediaIngestDoc):\n registry_name: str = \"wikipedia_text\"\n\n @property\n def filename(self) -> Path:\n return (Path(self.read_config.download_dir) / f\"{self.get_filename_prefix()}.txt\").resolve()\n\n @property\n def text(self):\n return self._get_content()\n\n @SourceConnectionNetworkError.wrap\n def _get_content(self):\n return self.page.content\n\n @property\n def _output_filename(self):\n return Path(self.processor_config.output_dir) / f\"{self.get_filename_prefix()}-txt.json\"\n\n\n@dataclass\nclass WikipediaIngestSummaryDoc(WikipediaIngestDoc):\n registry_name: str = \"wikipedia_summary\"\n\n @property\n def filename(self) -> Path:\n return (\n Path(self.read_config.download_dir) / f\"{self.get_filename_prefix()}-summary.txt\"\n ).resolve()\n\n @property\n def text(self):\n return self._get_summary()\n\n @SourceConnectionNetworkError.wrap\n def _get_summary(self):\n return self.page.summary\n\n @property\n def _output_filename(self):\n return Path(self.processor_config.output_dir) / f\"{self.get_filename_prefix()}-summary.json\"\n\n\n@dataclass\nclass WikipediaSourceConnector(SourceConnectorCleanupMixin, BaseSourceConnector):\n connector_config: SimpleWikipediaConfig\n\n def initialize(self):\n pass\n\n @requires_dependencies([\"wikipedia\"], extras=\"wikipedia\")\n def check_connection(self):\n import wikipedia\n\n try:\n wikipedia.page(\n self.connector_config.title,\n auto_suggest=self.connector_config.auto_suggest,\n )\n except Exception as e:\n logger.error(f\"failed to validate connection: {e}\", exc_info=True)\n raise SourceConnectionError(f\"failed to validate connection: {e}\")\n\n def get_ingest_docs(self):\n return [\n WikipediaIngestTextDoc(\n processor_config=self.processor_config,\n connector_config=self.connector_config,\n read_config=self.read_config,\n ),\n WikipediaIngestHTMLDoc(\n processor_config=self.processor_config,\n connector_config=self.connector_config,\n read_config=self.read_config,\n ),\n WikipediaIngestSummaryDoc(\n processor_config=self.processor_config,\n connector_config=self.connector_config,\n read_config=self.read_config,\n ),\n ]\n","repo_name":"Unstructured-IO/unstructured","sub_path":"unstructured/ingest/connector/wikipedia.py","file_name":"wikipedia.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","stars":3375,"dataset":"github-code","pt":"44"} +{"seq_id":"20358225011","text":"from typing import Optional\nfrom random import randint\nimport random\nfrom games.connect4.action import Connect4Action\nfrom games.connect4.result import Connect4Result\nfrom games.state import State\nimport random\n\n\nclass Connect4State(State):\n def my_shuffle(array):\n random.shuffle(array)\n return array\n EC = 0\n IC = -1\n PLAYED_CELL= -2\n BLUE = 1\n BLACK = 2\n GREEN = 3\n RED = 4\n WHITE = 5\n SPECIAL = 6\n NORMAL_PIECES = [1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,6,6,6] \n my_shuffle(NORMAL_PIECES)\n\n grid = [ \n [IC, IC, (EC,0), IC, (EC,0), IC, (EC,0), IC, IC],\n [IC, IC, IC, (EC,0), IC, (EC,0), IC, IC, IC],\n [IC, IC, (EC,0), IC, (EC,0), IC, (EC,0), IC, IC],\n [IC, (EC,0), IC, (EC,0), IC, (EC,0), IC, (EC,0), IC],\n [IC, IC, (EC,0), IC, (EC,0), IC, (EC,0), IC, IC],\n [IC, (EC,0), IC, (EC,0), IC, (EC,0), IC, (EC,0), IC],\n [(EC, 0), IC, (EC,0), IC, (EC,0), IC, (EC,0), IC, (EC,0)],\n [IC, (EC,0), IC, (EC,0), IC, (EC,0), IC, (EC,0), IC],\n [IC, IC, (EC,0), IC, (EC,0), IC, (EC,0), IC, IC],\n [IC, (EC,0), IC, (EC,0), IC, (EC,0), IC, (EC,0), IC],\n [IC, IC, (EC,0), IC, (EC,0), IC, (EC,0), IC, IC],\n [IC, IC, IC, (EC,0), IC, (EC,0), IC, IC, IC],\n [IC, IC, (EC,0), IC, (EC,0), IC, (EC,0), IC, IC]\n ]\n num_rows = 13 \n num_cols = 9\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == (EC,0):\n grid[i][j] = (NORMAL_PIECES.pop(0),0)\n\n available_colors = [1,2,3,4,5]\n chosen_colors_player_0 = []\n chosen_colors_player_1 = []\n score_player_0 = 0\n score_player_1 = 0\n possibleTuples = []\n for i in range(1,7):\n for j in range(5):\n possibleTuples.append((i,j))\n\n def __init__(self):\n super().__init__()\n \"\"\"\n the dimensions of the board\n \"\"\"\n self.__num_rows = 13\n self.__num_cols = 9\n\n \"\"\"\n the grid\n \"\"\"\n\n\n self.__grid = Connect4State.grid\n\n\n\n \"\"\"\n counts the number of turns in the current game\n \"\"\"\n self.__turns_count = 1\n\n \"\"\"\n the index of the current acting player\n \"\"\"\n self.__acting_player = 0\n self.__notActing_player = 1\n\n \"\"\"\n determine if a winner was found already \n \"\"\"\n self.__has_winner = False\n\n\n\n def __check_winner(self):\n if self.is_game_over():\n return True\n\n return False\n\n def get_grid(self):\n return self.__grid\n\n\n\n def get_num_players(self):\n return 2\n\n def find_move_to_make_5_stack(self):\n flag = False\n for i, row in enumerate(self.__grid):\n for j, element in enumerate(row):\n if isinstance(element, tuple) and element[1] == 4 and element[0] in Connect4State.chosen_colors_player_1:\n while flag == False:\n colFrom = randint(0, self.__num_cols)\n rowFrom = randint(0, self.__num_rows)\n colTo = j\n rowTo = i\n if self.validate_action(Connect4Action(colFrom,rowFrom,colTo,rowTo)):\n flag = True\n return(colFrom,rowFrom,colTo,rowTo)\n return None\n\n\n #FUNÇÃO PARA VER SE A PILHA TEM 5 PEÇAS e update no score\n def check_stack(self):\n for i, row in enumerate(self.__grid):\n for j, element in enumerate(row):\n if isinstance(element, tuple) and element[1] >= 5:\n if self.__acting_player == 0:\n if isinstance(element, tuple) and element[0] in Connect4State.chosen_colors_player_0:\n Connect4State.score_player_0 += 1\n print(f\"Score inside player 0: {Connect4State.score_player_0}\")\n elif self.__acting_player == 1:\n if isinstance(element, tuple) and element[0] in Connect4State.chosen_colors_player_1:\n Connect4State.score_player_1 += 1\n print(f\"Score inside player 1: {Connect4State.score_player_1}\")\n self.__grid[i][j] = -2\n\n ## VALIDAÇÕES ##\n def validate_action(self, action: Connect4Action) -> bool:\n colFrom = action.get_colFrom()\n rowFrom = action.get_rowFrom()\n colTo = action.get_colTo()\n rowTo = action.get_rowTo()\n \n\n # valid column\n if colFrom < 0 or colTo < 0 or colFrom >= self.__num_cols or colTo >=self.__num_cols:\n if self.__acting_player == 2:\n print(\"Less than 0 or Bigger than col\")\n return False\n \n # valid row\n if rowFrom < 0 or rowTo < 0 or rowFrom >= self.__num_rows or rowTo >= self.__num_rows:\n if self.__acting_player == 2:\n print(\"Less than 0 or Bigger than rows\")\n return False\n\n # same piece moving\n if self.__grid[rowFrom][colFrom] == self.__grid[rowTo][colTo]:\n if self.__acting_player == 2:\n print(\"Can't have a piece of the same color on top of each other\")\n return False\n \n # moving an opponents color piece\n if self.__acting_player == 0:\n if isinstance(self.__grid[rowFrom][colFrom], tuple):\n if (self.__grid[rowFrom][colFrom][0]) in Connect4State.chosen_colors_player_1:\n return False\n\n # moving an opponents color piece\n if self.__acting_player == 1:\n if isinstance(self.__grid[rowFrom][colFrom], tuple):\n if (self.__grid[rowFrom][colFrom][0]) in Connect4State.chosen_colors_player_0:\n if self.__acting_player == 2:\n print(\"Cant move a piece of the opponents color\")\n return False \n\n #select invalid cell\n if self.__grid[rowFrom][colFrom] == -1 or self.grid[rowTo][colTo] == -1:\n if self.__acting_player == 2:\n print(\"Move the piece to a place where there are pieces\")\n return False\n\n # row above or below only\n if abs(rowFrom - rowTo) > 1:\n if self.__acting_player == 2:\n print(\"You can only move on top of adjacent pieces 1 !\")\n return False\n\n # if same row, only adjacent col\n if abs(rowFrom - rowTo) == 0:\n if abs(colFrom - colTo) > 2:\n if self.__acting_player == 2:\n print(\"You can only move on top of adjacent pieces 2 !\")\n return False\n\n # cant move a stack \n if isinstance(self.__grid[rowFrom][colFrom], tuple):\n if (self.__grid[rowFrom][colFrom][1]) > 0:\n return False\n\n return True\n\n \n #GAME OVER#\n def is_game_over(self) -> bool:\n num_remaining_pieces = 0\n number_of_stacks = 0\n for row in range(self.__num_rows):\n for col in range(self.__num_cols):\n if self.__grid[row][col] != -1 and self.__grid[row][col] != -2:\n num_remaining_pieces += 1\n\n \n for i, row in enumerate(self.__grid):\n for j, element in enumerate(row):\n if isinstance(element, tuple) and element[1] > 0:\n number_of_stacks +=1\n if (num_remaining_pieces == number_of_stacks):\n return True\n\n def update(self, action: Connect4Action):\n colFrom = action.get_colFrom()\n rowFrom = action.get_rowFrom()\n colTo = action.get_colTo()\n rowTo = action.get_rowTo()\n\n if self.__grid[rowTo][colTo] != -2:\n if isinstance(self.__grid[rowFrom][colFrom], tuple) and isinstance(self.__grid[rowTo][colTo], tuple):\n ecFrom, heightFrom = self.__grid[rowFrom][colFrom]\n ecTo, heightTo = self.__grid[rowTo][colTo]\n \n self.__grid[rowTo][colTo] = (ecFrom, heightTo + 1)\n self.__grid[rowFrom][colFrom] = -2\n \n if self.__grid[rowTo][colTo] == -2:\n if rowFrom < rowTo:\n for i in range(rowTo + 1, self.__num_rows):\n for x in range(0,self.__num_cols):\n if (self.__grid[i][x]) != -1:\n if (self.__grid[i][x]) != -2:\n \n \n if (self.__grid[i][x]) in Connect4State.possibleTuples:\n \n ecFrom, heightFrom = self.__grid[rowFrom][colFrom]\n ecTo, heightTo = self.__grid[i][x]\n self.__grid[i][x] = (ecFrom, heightTo + 1)\n self.__grid[rowFrom][colFrom] = -2\n break\n else:\n continue\n break \n if rowFrom > rowTo:\n for i in range(rowTo - 1, self.__num_rows):\n for x in range(0,self.__num_cols):\n if (self.__grid[i][x]) != -1:\n if (self.__grid[i][x]) != -2:\n \n if (self.__grid[i][x]) in Connect4State.possibleTuples:\n \n ecFrom, heightFrom = self.__grid[rowFrom][colFrom]\n ecTo, heightTo = self.__grid[i][x]\n self.__grid[i][x] = (ecFrom, heightTo + 1)\n self.__grid[rowFrom][colFrom] = -2\n break\n else:\n continue\n break \n \n\n # determine if there is a winner\n self.__has_winner = self.__check_winner()\n\n #Check if there are 5 piece stack\n self.check_stack()\n #check if there are move valid moves \n self.is_game_over()\n # switch to next player\n self.__acting_player = 1 if self.__acting_player == 0 else 0\n self.display()\n self.__turns_count += 1\n \n \n \n def __display_cell(self, row, col):\n piece = self.__grid[row][col]\n stack = [0,1,2,3,4]\n this_pieces = [1,2,3,4,5,6]\n for x in stack:\n if piece == (1,x):\n print(f'BL{x}', end=\"\") \n if piece == (2,x):\n print(f'BK{x}', end=\"\")\n if piece == (3,x):\n print(f'GR{x}', end=\"\")\n if piece == (4,x):\n print(f'RE{x}', end=\"\")\n if piece == (5,x):\n print(f'WH{x}', end=\"\")\n if piece == (6,x):\n print(f'SP{x}', end=\"\") \n for y in this_pieces:\n if piece == (y,5):\n print('X',end=\"\")\n if piece == -1:\n print(' ', end=\"\") \n if piece == -2:\n print('X', end=\"\")\n\n\n\n def display(self):\n for row in range(0, self.__num_rows):\n for col in range(0, self.__num_cols):\n self.__display_cell(row,col)\n print('', end=\"\")\n print(\" \",row) \n \n print(\" \")\n print(\"\") \n\n def __is_full(self):\n #return self.__turns_count > (self.__num_cols * self.__num_rows)\n pass\n\n def is_finished(self) -> bool:\n return self.is_game_over()\n \n\n def get_acting_player(self) -> int:\n return self.__acting_player\n \n\n def clone(self):\n cloned_state = Connect4State()\n cloned_state.__turns_count = self.__turns_count\n cloned_state.__acting_player = self.__acting_player\n cloned_state.__has_winner = self.__has_winner\n for row in range(0, self.__num_rows):\n for col in range(0, self.__num_cols):\n cloned_state.__grid[row][col] = self.__grid[row][col] \n return cloned_state\n\n def get_result(self, pos) -> Optional[Connect4Result]:\n if self.__has_winner:\n print(self.display())\n score_0, score_1 = self.score_player_0, self.score_player_1\n if score_0 > score_1:\n print(\"Player 2 wins\")\n return Connect4Result.WIN if pos == 0 else Connect4Result.LOOSE\n elif score_1 > score_0:\n print(\"Player 1 wins\")\n return Connect4Result.WIN if pos == 1 else Connect4Result.LOOSE\n elif score_1 == score_0:\n print(\"Draw\")\n return Connect4Result.DRAW\n return None\n\n def get_num_rows(self):\n return self.__num_rows\n\n def get_num_cols(self):\n return self.__num_cols\n\n def before_results(self):\n pass\n\n def get_possible_actions(self):\n actions = []\n for colFrom in range(0, self.get_num_cols()):\n for rowFrom in range(0, self.get_num_rows()):\n for colTo in range(0, self.get_num_cols()):\n for rowTo in range(0, self.get_num_rows()):\n action = Connect4Action(colFrom, rowFrom, colTo, rowTo)\n if self.validate_action(action):\n actions.append(action)\n return actions # Exit the function if a valid action is found\n return actions\n\n def sim_play(self, action):\n new_state = self.clone()\n new_state.play(action)\n return new_state\n","repo_name":"locolow/TP1","sub_path":"luisteofilo-ai-solve-games-b96806e60704/src/games/connect4/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":13900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"72283608453","text":"import sys\ninput = sys.stdin.readline\nfrom collections import deque\n\nm, n = map(int, input().split())\n\ngraph = [[] for _ in range(n)]\n\n\nslist = []\nfor i in range(n):\n slist = input().split()\n for j in slist:\n graph[i].append(int(j))\n\ndx = [1, -1, 0, 0]\ndy = [0, 0, 1, -1]\nque = deque()\nfor i in range(n):\n for j in range(m):\n if graph[i][j] == 1:\n que.append([i, j, 0])\n \n\ndef bfs():\n day = 0\n while que:\n st = que.popleft()\n day = st[2]\n for d in range(4):\n nx = st[0] + dx[d]\n ny = st[1] + dy[d]\n \n if 0 <= nx < n and 0 <= ny < m:\n if graph[nx][ny] == 0:\n graph[nx][ny] = 1\n que.append([nx, ny, st[2] + 1])\n \n return day\n\nans = bfs()\nfor lo in graph:\n for tu in lo:\n if tu == 0:\n print(-1)\n exit()\n \nprint(ans)\n","repo_name":"cokkum113/AlgorithmPython","sub_path":"7576.py","file_name":"7576.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"40369947386","text":"from django.urls import path, include\nfrom django.views.i18n import JavaScriptCatalog\n\nfrom main import views, debug_api, chat\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('response', views.auto_response, name='auto_response'),\n path('response_api', views.response_api, name='response_api'),\n\n # web pages\n path('login/staff/', views.login_page, name='login_staff'),\n path('page/chatconsole/', views.chat_console, name='chat_console'),\n path('page/counsellor/', views.counsellor, name='counsellor'),\n path('page/supervisor/', views.supervisor, name='supervisor'),\n path('page/administrator/', views.administrator, name='administrator'),\n path('page/staffstatus/', views.staffstatus, name='staffstatus'),\n path('page/statistics/', views.statistics_page, name='statispage'),\n path('page/calendar/', views.calendar_page, name='calendarpage'),\n\n # APIs\n path('api/logout/', views.logout_staff, name='logout_staff'),\n path('api/findstaff/', views.findstaff, name='findstaff'),\n path('api/updatestaff/', views.updatestaff, name='updatestaff'),\n path('api/addstud/', views.addstud, name='addstud'),\n path('api/appointstaff/', views.appointstaff, name='appointstaff'),\n path('api/supervisorjoin/', views.supervisor_join, name='supervisorjoin'),\n path('api/submitsurvey/', views.submit_survey, name='submitsurvey'),\n path('api/endchatbot/', views.end_chatbot, name='endchatbot'),\n path('api/student/count', views.count_student_in_queue, name='student_count'),\n path('api/get_statistics/', views.get_statistics, name='get_statistics'),\n path('api/export_statistics/', views.export_statistics, name='export_statistics'),\n path('api/get_red_route/', views.get_red_route, name='get_red_route'),\n path('api/export_red_route/', views.export_red_route, name='export_red_route'),\n path('api/update_calendar/', views.update_calendar, name='update_calendar'),\n path('api/working_day//', views.is_working_day, name='working_day'),\n path('api/working_hour/', views.is_working_hour, name='working_hour'),\n path('api/chatting_working_hour/', views.is_chatting_working_hour, name='chatting_working_hour'),\n path('user/login/', views.login_all, name='login'),\n path('user/login-sso/', views.login_sso, name='login_sso'),\n path('user/login-sso/callback/', views.login_sso_callback, name='login_sso_callback'),\n path('user/logout/student/', views.student_logout, name='student_logout'),\n path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),\n path('i18n/', include('django.conf.urls.i18n'))\n]\n\ndebug_urls = [\n path('debug/getseq/', debug_api.getseq, name='debug_getseq'),\n # path('debug/addstud/', debug_api.addstud, name='debug_addstud'),\n path('debug/getstud/', debug_api.getstud, name='debug_getstud'),\n path('debug/deletestud/', debug_api.deletestud, name='debug_deletestud'),\n # path('debug/updatestud/', debug_api.updatestud, name='debug_updatestud'),\n # path('debug/getstafflist/', debug_api.getstafflist, name='debug_getstafflist'),\n # path('debug/getstaff/', debug_api.getstaff, name='debug_getstaff'),\n # path('debug/addstaff/', debug_api.addstaff, name='debug_addstaff'),\n # path('debug/updatestaff/', debug_api.updatestaff, name='debug_updatestaff'),\n # path('debug/deletestaff/', debug_api.deletestaff, name='debug_deletestaff'),\n # path('debug/assignstaff/', debug_api.assignstaff, name='debug_assignstaff'),\n path('debug/startchat/', debug_api.startchat, name='debug_stratchat'),\n path('debug/endchat/', debug_api.endchat, name='debug_endchat'),\n # path('debug/reassign_counsellor/', debug_api.reassign_task, name='reassign_counsellor'),\n # path('debug/dequeue_student/', debug_api.dequeue_task, name='dequeue_student'),\n]\n\nchat_urls = [\n path('chat/student/', chat.student, name='chat_student'),\n path('chat/counsellor/', chat.counsellor, name='chat_counsellor'),\n path('chat/counsellor_from_email/', chat.counsellor_from_email, name='chat_counsellor_from_email'),\n path('chat/subscribe_stream/', chat.subscribe_stream, name='chat_subscribe_stream'),\n path('chat/unsubscribe_stream/', chat.unsubscribe_stream, name='chat_unsubscribe_stream'),\n path('chat/delete_stream/', chat.delete_stream, name='chat_delete_stream'),\n path('chat/delete_stream_in_topic/', chat.delete_stream_in_topic, name='chat_delete_stream_in_topic'),\n path('chat/stream_room/', chat.stream_room, name='chat_stream_room'),\n]\n\nurlpatterns += debug_urls\nurlpatterns += chat_urls\n","repo_name":"chenbingxiayu/chatbot-demo","sub_path":"chatbot_demo/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4560,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"44"} +{"seq_id":"29674951240","text":"# 2) write a program to print 1 to 5 multiplication table using single loop \n\nnum=1\ncount=1\nmultiplication=1\n\nfor count in range(1,12):\n if count<=11:\n multiplication=count*num\n print(f\"{num} x {count} = {multiplication}\")\n elif count>11:\n count=1\n num=num+1\n \n\n","repo_name":"SirZexx/Python_Ex","sub_path":"loop1/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"14601514719","text":"from importlib import import_module\n\nfrom django.shortcuts import get_object_or_404\nfrom django_filters.rest_framework import CharFilter, DjangoFilterBackend, FilterSet\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.filters import OrderingFilter\nfrom rest_framework.generics import ListAPIView, RetrieveAPIView\nfrom rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly\nfrom rest_framework.response import Response\n\n\nfrom .serializers import BookmarkedResourceSerializer, SeriesSerializer, SermonsSerializer\nfrom .services import (\n bookmark_resource,\n decrement_like_on_model,\n get_bookmarks_for_resource,\n has_user_bookmarked,\n increment_like_on_model\n)\nfrom bookmarking.exceptions import AlreadyExist, DoesNotExist\nfrom bookmarking.handlers import library\nfrom sermons.models import Series, Sermon\n\n\n# Create your views here.\n\nlibrary.register([Sermon])\n\n\ndef resolve_model(func):\n def decorator(requests, **kwargs):\n if 'model' in kwargs:\n module = import_module('sermons.models')\n klass = getattr(module, kwargs['model'].capitalize())\n kwargs['model'] = klass\n\n return func(requests, **kwargs)\n return decorator\n\n\nclass SeriesLists(ListAPIView):\n class SeriesFilter(FilterSet):\n tags = CharFilter(field_name='tags', lookup_expr='icontains')\n title = CharFilter(field_name='title', lookup_expr='icontains')\n\n class Meta:\n model = Series\n fields = {\n 'starts_at': ['lte', 'gte', ],\n 'ends_at': ['lte', 'gte', ],\n }\n\n queryset = Series.objects.all()\n serializer_class = SeriesSerializer\n filterset_class = SeriesFilter\n filter_backends = (DjangoFilterBackend,\n OrderingFilter,)\n ordering_fields = ('starts_at', 'ends_at', 'title')\n\n\nclass SeriesDetail(RetrieveAPIView):\n queryset = Series.objects.all()\n serializer_class = SeriesSerializer\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n\nclass SermonList(ListAPIView):\n class SermonsFilter(FilterSet):\n title = CharFilter(field_name='title', lookup_expr='icontains')\n tags = CharFilter(field_name='tags', lookup_expr='icontains')\n preacher = CharFilter(field_name='preacher', lookup_expr='icontains')\n series_name = CharFilter(field_name='series__name', lookup_expr='icontains')\n mime_type = CharFilter(field_name='mime_type', lookup_expr='exact')\n\n class Meta:\n model = Sermon\n fields = {\n 'published': ['lte', 'gte'],\n 'series': ['exact'],\n }\n\n queryset = Sermon.objects.all()\n serializer_class = SermonsSerializer\n filterset_class = SermonsFilter\n filter_backends = (DjangoFilterBackend, OrderingFilter,)\n ordering_fields = ('published', 'created_at', 'updated_at', 'preacher', 'title', 'series')\n\n\nclass SermonDetail(RetrieveAPIView):\n queryset = Sermon.objects.all()\n serializer_class = SermonsSerializer\n\n\n@resolve_model\n@api_view(['PATCH'])\n@permission_classes([IsAuthenticated])\ndef update_likes_on_resource(request, pk, action, model: str):\n \"\"\"\n Update likes on models.\n\n :param request:\n :param pk:\n :param action:\n :param model:\n :return:\n \"\"\"\n try:\n instance = get_object_or_404(model, pk=pk)\n\n if action == 'add_like':\n increment_like_on_model(instance=instance, user=request.user)\n elif action == 'remove_like':\n decrement_like_on_model(instance=instance, user=request.user)\n response = Response(status=status.HTTP_204_NO_CONTENT)\n except AlreadyExist:\n message = f'{model} #{instance.pk} is already bookmarked'\n response = Response(status=status.HTTP_400_BAD_REQUEST, data={\"message\": message})\n except (ValueError, DoesNotExist):\n message = f'{model.capitalize()} #{instance.pk} does not exists'\n response = Response(status=status.HTTP_400_BAD_REQUEST, data={\"message\": message})\n\n return response\n\n\n@api_view(['PATCH'])\n@permission_classes([IsAuthenticated])\n@resolve_model\ndef add_to_bookmark(request, pk, model):\n try:\n instance = get_object_or_404(model, pk=pk)\n bookmark_resource(instance=instance, user=request.user)\n return Response(status=status.HTTP_204_NO_CONTENT, data='resource bookmarked')\n except AlreadyExist:\n return Response(status=status.HTTP_400_BAD_REQUEST, data={\"message\": \"already bookmarked\"})\n\n\n@resolve_model\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef my_bookmarks(request, model):\n bookmarks = get_bookmarks_for_resource(user=request.user, model=model)\n serializer = BookmarkedResourceSerializer(many=True, data=bookmarks, context={'request': request})\n serializer.is_valid()\n return Response(status=status.HTTP_200_OK, data=serializer.data)\n\n\n@resolve_model\n@api_view(['GET'])\ndef already_bookmarked(request, model, pk):\n if has_user_bookmarked(user=request.user, model=model, pk=pk):\n return Response(status=status.HTTP_200_OK, data={'message': 'Already bookmarked'})\n\n return Response(status=status.HTTP_404_NOT_FOUND, data={'message': 'Not bookmarked'})\n","repo_name":"ndy40/HCN-CMS","sub_path":"hcn_cms/sermons/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"72017214533","text":"#USE from rabbit_content_addendum import *\r\nglobal feeds\r\n\r\nfeeds += \"\"\"\\n\r\nhttps://schneier.com/blog/atom.xml\r\nhttp://xkcd.com/atom.xml\r\nhttp://feeds.arstechnica.com/arstechnica/index/\r\nhttp://feeds.gawker.com/lifehacker/full\r\nhttps://www.reddit.com/r/technology/.rss\r\n\"\"\"\r\n\r\n#OVERRIDES addCategory to update criteria without adding new targetable sections\r\ndef addCategory(name, criteria):\r\n global categories, txt_categories, dict_categories\r\n if name in txt_categories:\r\n for ndx in range(len(txt_categories)):\r\n if name == txt_categories[ndx]:\r\n categories[ndx] = criteria\r\n else:\r\n categories.append(criteria);\r\n txt_categories.append(name)\r\n dict_categories[name] = criteria\r\n\r\ntech += \"\"\"\\n20: feds \r\n25: trade\r\n\"\"\"\r\naddCategory('Technology', tech)\r\n\r\nbusiness += \"\"\"\\n\r\n25: money\r\n20: economy\r\n\"\"\"\r\naddCategory('Business', business)\r\n\r\nusa_politics += \"\"\"\\n\r\n30: politics\r\n\"\"\"\r\naddCategory('USA politics', usa_politics)\r\n\r\nasia += \"\"\"\\n\r\n50: china\r\n20: china, trade\r\n20: china, economy\r\n40: asian economy\r\n40: military, south china sea\r\n\"\"\"\r\naddCategory('Asia', asia)\r\n\r\neurope = \"\"\"\\n\r\n35: europe\r\n20: EU,eu\r\n\"\"\"\r\naddCategory('Europe', europe)\r\n\r\ncollege += \"\"\"\\n\r\n10: college, school\r\n30: university|college,rankings\r\n30: college,tuition\r\n\"\"\"\r\naddCategory('University', college)\r\n\r\nhealth += \"\"\"\\n\r\n30: healthy, life\r\n10: healthy, lifetyle\r\n30: dieting\r\n25: exercise\r\n30: exercising\r\n30: fitness\r\n10: health, body\r\n\"\"\"\r\naddCategory('Health', health)\r\n\r\nlaw = \"\"\"\\n\r\n25: congress\r\n25: bills,-dolla dolla\r\n35: new law\r\n10: judge\r\n30: federal judges\r\n35: judge appointments\r\n\"\"\"\r\naddCategory('Law', law)\r\n\r\nfood += \"\"\"\\n\r\n30: food\r\n20: meal recipe\r\n20: budget recipe\r\n20: recipes\r\n\"\"\"\r\naddCategory('Food', food)\r\n\r\ntravel += \"\"\"\\n\r\n40: travel\r\n40: cheap flights\r\n50: travel adventures\r\n50: budget traveling\r\n30: recreation\r\n20: summer activities\r\n20: winter activities\r\n20: fall activities\r\n20: spring activities\r\n45: travel ideas\r\n45: how to travel\r\n45: travel guides\r\n\"\"\"\r\naddCategory('Travel', travel)\r\n\r\nmusic += \"\"\"\\n\r\n20: top songs\r\n15: best albums\r\n20: concerts, music concerts\r\n\"\"\"\r\naddCategory('Music', music)\r\n\r\nentertainment += \"\"\"\\n\r\n20: movie\r\n30: new movie\r\n35: (best|good|great show|movie)\r\n\"\"\"\r\naddCategory('Entertainment', entertainment)\r\n\r\ncrypto += \"\"\"\\n\r\n20: cryptocurrenc(y|ies)\r\n10: bitcoin(|s)\r\n15: alt( |-)coins\"\"\"\r\naddCategory('Crypto', crypto)\r\n\r\nspace_stuff += \"\"\"\\n\r\n\"\"\"\r\naddCategory('Space', space_stuff)\r\n\r\nclimate += \"\"\"\\n\r\n40: air pollution, toxic\r\n\"\"\"\r\naddCategory('Climate', climate)\r\n\r\nworld_affairs += \"\"\"\\n\r\n35: sanctions\r\n\"\"\"\r\naddCategory('World Affairs', world_affairs)\r\n\r\nentries, named_categories = [], list(dict_categories.keys())\r\n","repo_name":"DZeroCool/NewsHare","sub_path":"rabbit_content_addendum.py","file_name":"rabbit_content_addendum.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"3021266465","text":"from bs4 import BeautifulSoup\nimport os\nimport random\nimport re \nimport requests\nimport json\nimport time\nfrom datetime import datetime\n\nfrom bookupdate import *\nfrom bookclean import *\n\n\ndef writeBookinfo(url,headers,n):\n try:\n print('Try to get html from the book which will be recorded...')\n bookhtml = requests.get(url, headers = randomHeaders(headers), timeout = 8)\n print(\"Request Successful for the \"+str(n)+'-th book!')\n bookinfo = BeautifulSoup(bookhtml.content, features=\"html5lib\")\n except:\n print('Wrong!!') \n return(False) \n\n try:\n result = bookinfo.find('script', {'type':'application/ld+json'})\n result = json.loads(result.text.strip())\n except:\n return(False)\n try:\n bookName = result['name']\n except:\n bookName = ''\n try:\t \n bookAuthor = result['author'][0]['name']\n except:\n bookAuthor = ''\n try:\n bookIsbn = result['isbn']\n except:\n bookIsbn = ''\n try:\n bookUrl = result['url']\n if bookUrl != url:\n print(bookUrl + '<--->' + url)\n except:\n bookUrl = url \n try:\n voteNum = bookinfo.find('span',{'property':'v:votes'})\n voteNum = voteNum.text.strip()\n except:\n voteNum = '' \n try:\n voteAvg = bookinfo.find('strong',{'property':'v:average'})\n voteAvg = voteAvg.text.strip()\n except:\n voteAvg = ''\n \n booklistpath = os.path.join(os.path.dirname(os.getcwd()),'data/BookInfoSet.csv') \n \n with open(booklistpath, mode = 'a') as f:\n f.write(bookIsbn+',')\n f.write('\"'+bookName+'\"'+',')\n f.write('\"'+bookAuthor+'\"'+',')\n f.write(voteAvg+',')\n f.write(voteNum+',')\n f.write(bookUrl+',')\n f.write(str(datetime.date(datetime.today()))+'\\n')\n f.close()\n print(\"This is the \" + str(n)+ \"-th book recorded this time! Book Info is written into file! Take a short break!\")\n return(True) \n\n\ndef main():\n\n headers = readHeaderslist()\n booklinkset = updateLinkSet(set())\n\n if len(booklinkset) == 0:\n url = 'https://book.douban.com/'\n else:\n url = random.sample(booklinkset,1)[0]\n\n loop = 0\n n = 1\n error = 0\n totalRequest = 0\n\n print(\"Start Time: \"+ str(datetime.today()))\n\n while True:\n try:\n print('Try to get html from the link of book link set...')\n html = requests.get(url, headers = randomHeaders(headers), timeout = 8)\n if html.ok: print(\"Request Success for the \" + str(loop) + \"-th time!\")\n loop += 1\n totalRequest += 1\n\n page = BeautifulSoup(html.content, features=\"html5lib\")\n urllist = page.findAll('a',{'href':re.compile(\"https://book.douban.com/subject/[0-9]*\")})\n print('Find '+ str(len(urllist))+' books.')\n for link in urllist:\n booklink = cleanlink(link['href'])\n if booklink not in booklinkset:\n result = writeBookinfo(booklink, headers,n)\n if result: \n n += 1\n totalRequest += 1\n booklinkset.add(booklink)\n linksetpath = os.path.join(os.path.dirname(os.getcwd()),'data/BookLinkSet.txt')\n with open(linksetpath,'a') as a:\n a.write(booklink+'?\\n')\n a.close()\n time.sleep(random.randint(5,10))\n url = random.sample(booklinkset,1)[0]\n time.sleep(random.randint(3,5))\n except:\n error += 1\n print(\"Stop Time: \" + str(datetime.today()))\n print('The total requests are '+str(totalRequest))\n if error > 1: break\n url = random.sample(booklinkset,1)[0]\n time.sleep(random.randint(1,3))\n\nif __name__ == '__main__':\n main()\n","repo_name":"Jiashuo-Sun/DoubanBookList","sub_path":"code/WebCrawler.py","file_name":"WebCrawler.py","file_ext":"py","file_size_in_byte":3961,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"44"} +{"seq_id":"31261612771","text":"from PIL import Image\n\n#opens the images\nimg1 = Image.open(\"1.png\")\nimg2 = Image.open(\"2.png\")\nimg3 = Image.open(\"3.png\")\nimg4 = Image.open(\"4.png\")\nimg5 = Image.open(\"5.png\")\nimg6 = Image.open(\"6.png\")\nimg7 = Image.open(\"7.png\")\nimg8 = Image.open(\"8.png\")\nimg9 = Image.open(\"9.png\")\n\nwidth, height = img1.size #assigns the height and width to use for the new image\n\nfinal = Image.new(\"RGB\", (width, height)) #creates new image for the final product\n\npixel1 = img1.load()\npixel2 = img2.load()\npixel3 = img3.load()\npixel4 = img4.load()\npixel5 = img5.load()\npixel6 = img6.load()\npixel7 = img7.load()\npixel8 = img8.load()\npixel9 = img9.load()\n\n#lists for the RGB values and the final values\nred = []\nblue = []\ngreen = []\nfinallist = []\n\n \nfor y in range (height):\n for x in range (width):\n #Goes through each individual pixel in each image and adds their rgb values to their respective lists\n red1, green1, blue1 = pixel1[x,y]\n red.append(red1)\n blue.append(blue1)\n green.append(green1)\n red2, green2, blue2 = pixel2[x,y]\n red.append(red2)\n blue.append(blue2)\n green.append(green2)\n red3, green3, blue3 = pixel3[x,y]\n red.append(red3)\n blue.append(blue3)\n green.append(green3)\n red4, green4, blue4 = pixel4[x,y]\n red.append(red4)\n blue.append(blue4)\n green.append(green4)\n red5, green5, blue5 = pixel5[x,y]\n red.append(red5)\n blue.append(blue5)\n green.append(green5)\n red6, green6, blue6 = pixel6[x,y]\n red.append(red6)\n blue.append(blue6)\n green.append(green6)\n red7, green7, blue7 = pixel7[x,y]\n red.append(red7)\n blue.append(blue7)\n green.append(green7)\n red8, green8, blue8 = pixel8[x,y]\n red.append(red8)\n blue.append(blue8)\n green.append(green8)\n red9, green9, blue9 = pixel9[x,y]\n red.append(red9)\n blue.append(blue9)\n green.append(green9)\n \n #sorts each list\n red.sort()\n blue.sort()\n green.sort()\n \n #gets the median values from the lists\n medianPixel = (red[4], green[4], blue[4])\n \n #adds this median value to final list\n finallist.append(medianPixel)\n \n #clears lists\n del red[:]\n del blue[:]\n del green[:]\n\n#puts data into the image\nfinal.putdata(finallist)\nfinal.save(\"final.png\")\n \n \n \n \n","repo_name":"jisaias/jisaiasrepo","sub_path":"proj1.py","file_name":"proj1.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"31656399857","text":"class Solution(object):\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n if not matrix or target is None:\n return False\n m,n = len(matrix),len(matrix[0])\n l,r = 0,m*n - 1\n while l <= r:\n mid = (l+r)/2\n num = matrix[mid/n][mid%n]\n if num == target:\n return True\n elif num < target:\n l = mid + 1\n else:\n r = mid - 1\n return False\n '''\n if len(matrix) == 0:\n return False\n elif len(matrix[0]) == 0:\n return False\n m,n = len(matrix),len(matrix[0])\n l,r = 0,m*n - 1\n while l < r:\n mid = (l + r -1)/2\n if matrix[mid/n][mid%n] < target:\n l = mid + 1\n else:\n r = mid\n return matrix[r/n][r%n] == target\n '''\n '''\n if matrix == []:\n return False\n up,down = 0,len(matrix)-1\n left,right = 0,len(matrix[0])-1\n while up < down:\n mid = (up+down)/2 + 1\n if target < matrix[mid][0]:\n down = mid - 1\n elif target > matrix[mid][0]:\n up = mid\n else:\n return True\n while left <= right:\n mid = (right+left)/2\n if target == matrix[up][mid]:\n return True\n elif target < matrix[up][mid]:\n right = mid - 1\n else:\n left = mid + 1\n return False\n '''\n \n","repo_name":"King26535/leetcode","sub_path":"74.Searcha2DMatrix.py","file_name":"74.Searcha2DMatrix.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"4033954545","text":"## Script (Python) \"getLocalProperties\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=attr\n##title=getLocalProperties (DEPRECATED use get_properties or get_property instead)\n##\n\nfrom Products.CMFCore.utils import getToolByName\n\npp = getToolByName(context, 'portal_properties')\nsc = getattr(pp, 'services_configuration')\n\nreturn getattr(sc, attr)\n","repo_name":"gisweb/gisweb.iol","sub_path":"src/gisweb/iol/skins/iol_scripts/getLocalProperties.py","file_name":"getLocalProperties.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"44"} +{"seq_id":"70127679813","text":"from functools import wraps\nfrom flask import url_for, request, redirect, render_template, session, flash\nfrom ..authentication import sessao_ativa, make_session_permanent, sessao_expirada, retorna_usuario\nfrom .zelda_modelo import ZeldaModelo\n\ndef verifica_permissao(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n funcionalidade_caminho = '/' + request.path.split('/')[1]\n \n funcionalidade = ZeldaModelo.pesquisa_funcionalidade(funcionalidade_caminho)\n usuario = retorna_usuario()\n\n if funcionalidade is not None:\n if usuario.pode_acessar(funcionalidade):\n return f(*args, **kwargs)\n\n flash('Você não tem acesso à funcionalidade \"' + funcionalidade.nome + '\"')\n else:\n flash('A funcionalidade de caminho \"' + funcionalidade_caminho + '\" não está cadastrada no sistema')\n\n return redirect(url_for('home'))\n return decorated_function\n\ndef login_required(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if sessao_expirada():\n flash(\"Sessão expirada\")\n\n if not sessao_ativa():\n return redirect(url_for('login'))\n\n make_session_permanent()\n\n return f(*args, **kwargs)\n return decorated_function","repo_name":"jucimarjr/zelda","sub_path":"app/utils/front_helper.py","file_name":"front_helper.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"44"} +{"seq_id":"16903374533","text":"import subprocess, time\nfrom datetime import date\nfrom collections import deque\nfrom threading import Thread, Condition\nimport myfitnesspal\nfrom gpiozero import Servo\n\nfood_nutrition = {}\nFOOD_ITEM_NAME = \"Milano Mint Cookies\"\nstarting_weight = 0\nfood_nutrition_serving_index = 1\ncalorie_deficit = 0\n\ndef weight_reader(proc, q_hx711_weight, cv_hx711_thread):\n print(\"HX711 Thread: Entered thread\", flush=True)\n print(\"HX711 Thread: waiting for output from HX711\", flush=True)\n for line in iter(proc.stdout.readline, b'START\\n'):\n # print(\"Thread: waiting for START, status = {status}\".format(status = line))\n continue\n\n print(\"HX711 Thread: reading lines\", flush=True)\n for line in iter(proc.stdout.readline, b''):\n q_hx711_weight.append(line.decode('utf-8')[:-1])\n cv_hx711_thread.acquire()\n cv_hx711_thread.notify()\n cv_hx711_thread.release()\n # print(\"Thread: line = {l}\".format(l = line), flush=True)\n print(\"HX711 Thread: Done reading, ending thread\", flush=True)\n\ndef myfitnesspal_reader(q_day_data, q_goals, client, cv_mfp_thread):\n print(\"Fitness Thread: Entered thread\", flush=True)\n try:\n while True:\n today = date.today()\n day = client.get_date(today.year, today.month, today.day)\n q_day_data.append(day.totals)\n q_goals.append(day.goals)\n\n cv_mfp_thread.acquire()\n cv_mfp_thread.notify()\n cv_mfp_thread.release()\n # time.sleep(4)\n\n except (KeyboardInterrupt, SystemExit):\n return\n\nif __name__ == \"__main__\":\n proc = subprocess.Popen([\"python\", \"./read_weight.py\"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n print(\"Opened process\")\n # time.sleep(20)\n q_hx711_weight = deque(maxlen=5)\n cv_hx711_thread = Condition()\n t_hx711 = Thread(target=weight_reader, args=(proc, q_hx711_weight, cv_hx711_thread))\n t_hx711.daemon = True\n t_hx711.start()\n print(\"Started hx711 thread\")\n\n print(\"Creating MyFitnessPal client\")\n client = myfitnesspal.Client('pranavburugula', password='qxPtaA8z')\n print(\"Done creating MyFitnessPal client\")\n\n food_nutrition = client.get_food_search_results(FOOD_ITEM_NAME)[2]\n print(\"{food_name}: calories = {cal}, servings = {s}, sugar = {sugar}\".format(food_name = FOOD_ITEM_NAME, cal = food_nutrition.calories, s = food_nutrition.servings, sugar = food_nutrition.sugar))\n # print(\"Serving: \", food_nutrition.servings[0].nutrition_multiplier)\n q_day_data = deque(maxlen=1)\n q_goals = deque(maxlen=1)\n cv_mfp_thread = Condition()\n t_mfp = Thread(target=myfitnesspal_reader, args=(q_day_data, q_goals, client, cv_mfp_thread))\n t_mfp.daemon = True\n t_mfp.start()\n print(\"Started myfitnesspal thread\")\n\n servo = Servo(25)\n servo.min()\n\n first_iter = True\n try:\n while True:\n # print(\"Iteration {iter}: reading queue\".format(iter = i))\n # weight = starting_weight\n # if first_iter:\n # print(\"Place snacks in box\")\n # for i in range(20):\n # print(\"Starting in {count}\".format(count = 20 - i))\n # time.sleep(1)\n # cv_hx711_thread.acquire()\n # cv_hx711_thread.wait()\n # cv_hx711_thread.release()\n # weight = float(q_hx711_weight.pop())\n # starting_weight = weight\n # first_iter = False\n # print(\"starting weight = \", starting_weight)\n # else:\n cv_hx711_thread.acquire()\n cv_hx711_thread.wait()\n cv_hx711_thread.release()\n weight = float(q_hx711_weight.pop())\n if weight > starting_weight:\n starting_weight = weight\n print(\"weight = \", weight)\n print(\"starting weight = \", starting_weight)\n\n cv_mfp_thread.acquire()\n cv_mfp_thread.wait()\n cv_mfp_thread.release()\n day_data = q_day_data.pop()\n goals = q_goals.pop()\n print(\"day_data = \", day_data)\n print(\"goals = \", goals)\n\n calorie_deficit = (starting_weight - weight) * food_nutrition.calories / food_nutrition.servings[food_nutrition_serving_index].value\n\n print(\"calorie deficit = \", calorie_deficit)\n\n if bool(day_data) and day_data['calories'] + calorie_deficit > goals['calories']:\n print(\"Exceeded goals, locking box\")\n servo.max()\n elif calorie_deficit > goals['calories']:\n print(\"Exceeded goals, locking box\")\n servo.max()\n else:\n servo.min()\n\n time.sleep(10)\n except (KeyboardInterrupt, SystemExit):\n proc.terminate()\n try:\n proc.wait(timeout=0.2)\n print('== subprocess exited with rc =', proc.returncode)\n except subprocess.TimeoutExpired:\n print('subprocess did not terminate in time')","repo_name":"pranavburugula/CS437FinalProjectDeviceCode","sub_path":"device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"11804205236","text":"from contextlib import contextmanager\nfrom copy import copy\nfrom dataclasses import dataclass\nfrom sys import stderr\nfrom typing import Any, Callable, Optional\n\nfrom util import Token, ToppleException, trace\n\n\ndef name_type(value_or_type):\n if value_or_type == Pointer:\n return \"pointer\"\n elif isinstance(value_or_type, str):\n return f\"'{value_or_type}'\"\n\n elif isinstance(value_or_type, Pointer):\n if value_or_type.type is None:\n return \"pointer\"\n else:\n return f\"'{value_or_type.type}'\"\n\n elif value_or_type == int or isinstance(value_or_type, int):\n return \"integer\"\n\n elif value_or_type == bytearray or isinstance(value_or_type, bytearray):\n return \"bytes\"\n\n\ndef ensure_type(value, type):\n if type is Any:\n return\n\n elif isinstance(type, str):\n if isinstance(value, Pointer) and value.type == type:\n return\n else:\n pass\n\n elif type == Pointer:\n if isinstance(value, Pointer) and value.type is None:\n return\n else:\n pass\n\n elif isinstance(value, type):\n return\n\n raise ToppleException(\n \"type mismatch\", hint=f\"expected {name_type(type)}, found {name_type(value)}\"\n )\n\n\nclass EarlyExit(Exception):\n pass\n\n\nclass Stack(list):\n def append(self, vs):\n if len(self) + len(vs) > 10_000:\n raise ToppleException(\"stack overflow\")\n\n for v in vs:\n if isinstance(v, bool):\n v = 0xFFFF_FFFF_FFFF_FFFF if v else 0\n super().append(v)\n\n @contextmanager\n def pop(self, types):\n try:\n if len(types) == 0:\n return []\n\n popped = self[-len(types) :]\n for _ in popped:\n super().pop()\n\n if len(popped) < len(types):\n word = \"value\" if len(types) == 1 else \"values\"\n raise ToppleException(\n \"stack underflow\", hint=f\"expected {len(types)} {word}\"\n )\n\n for v, ty in zip(popped, types):\n ensure_type(v, ty)\n\n yield popped\n\n except ToppleException as e:\n e.captured_stack = popped\n raise e\n\n def pick(self, n):\n if len(self) < n + 1:\n raise ToppleException(\"stack underflow\")\n return self[-(n + 1)]\n\n def top_truthy(self):\n with self.pop([Any]) as [v]:\n return v != 0\n\n\nclass Pointer:\n block: list\n idx: int\n type: Optional[str]\n\n def __init__(self):\n self.block = [None] * 400\n self.idx = 0\n self.type = None\n\n def __str__(self):\n return f\"{name_type(self)} (offset {self.idx})\"\n\n def with_offset(self, offset):\n idx = (self.idx + offset) & 0xFFFF_FFFF_FFFF_FFFF\n\n if idx >= 400:\n raise ToppleException(\"pointer out of bounds\")\n\n p = copy(self)\n p.idx = idx\n return p\n\n def get(self):\n v = self.block[self.idx]\n if v is None:\n raise ToppleException(\"uninitialized data\")\n return v\n\n def set(self, v):\n self.block[self.idx] = v\n\n def close(self, type):\n p = copy(self)\n p.type = type\n return p\n\n def open(self):\n p = copy(self)\n p.type = None\n return p\n\n\n@dataclass\nclass Cell:\n value: Any = None\n\n\n@dataclass\nclass Node:\n token: Optional[Token]\n\n\n@dataclass\nclass Literal(Node):\n value: int\n\n def run(self, stack):\n with trace(self.token):\n stack.append([self.value])\n\n\n@dataclass\nclass Get(Node):\n cell: Cell\n\n def run(self, stack):\n with trace(self.token):\n if self.cell.value is None:\n raise ToppleException(\"uninitialized data\")\n stack.append([self.cell.value])\n\n\n@dataclass\nclass Set(Node):\n cell: Cell\n\n def run(self, stack):\n with trace(self.token):\n with stack.pop([Any]) as [v]:\n self.cell.value = v\n\n\n@dataclass\nclass Open(Node):\n type: str\n\n def run(self, stack):\n with trace(self.token): # TODO\n with stack.pop([self.type]) as [p]:\n stack.append([p.open()])\n\n\n@dataclass\nclass Close(Node):\n type: str\n\n def run(self, stack):\n with trace(self.token): # TODO\n with stack.pop([Pointer]) as [p]:\n stack.append([p.close(self.type)])\n\n\n@dataclass\nclass Primitive(Node):\n action: Callable[[Stack], None]\n\n def run(self, stack):\n with trace(self.token):\n self.action(stack)\n\n\n@dataclass\nclass String(Node):\n value: str\n\n def run(self, _stack):\n print(self.value, end=\"\", file=stderr)\n\n\n@dataclass\nclass Definition(Node):\n contents: list\n\n def run(self, stack):\n for node in self.contents:\n node.run(stack)\n\n\n@dataclass\nclass Call(Node):\n word: Definition\n\n def run(self, stack):\n with trace(self.token):\n try:\n self.word.run(stack)\n except EarlyExit:\n pass\n\n\n@dataclass\nclass Exit(Node):\n def run(self, stack):\n raise EarlyExit\n\n\n@dataclass\nclass Condition(Node):\n if_true: list\n if_false: list\n\n def run(self, stack):\n with trace(self.token):\n if stack.top_truthy():\n to_run = self.if_true\n else:\n to_run = self.if_false\n\n for node in to_run:\n node.run(stack)\n\n\n@dataclass\nclass Loop(Node):\n test: list\n body: list\n\n def run(self, stack):\n while True:\n for node in self.test:\n node.run(stack)\n\n with trace(self.token):\n if not stack.top_truthy():\n break\n\n for node in self.body:\n node.run(stack)\n\n\n@dataclass\nclass ArithPrim(Node):\n action: Callable[[int, int], int]\n\n def run(self, stack):\n with trace(self.token):\n with stack.pop([int, int]) as [l, r]:\n try:\n stack.append([self.action(l, r) & 0xFFFF_FFFF_FFFF_FFFF])\n except ZeroDivisionError:\n raise ToppleException(\"division by zero\")\n\n\n@dataclass\nclass BoolPrim(Node):\n action: Callable[[int, int], int]\n\n def run(self, stack):\n with trace(self.token):\n with stack.pop([int, int]) as [l, r]:\n n = 0xFFFF_FFFF_FFFF_FFFF if self.action(l, r) else 0\n stack.append([n])\n","repo_name":"wirelyre/topple","sub_path":"src/python/runtime.py","file_name":"runtime.py","file_ext":"py","file_size_in_byte":6495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"3484500695","text":"import boto3\r\nimport json\r\nimport csv\r\nfrom datetime import date\r\nfrom datetime import datetime\r\n\r\n#Variables de ambiente\r\nENDPOINT_NAME = 'DEMO-linear-endpoint-202305251028'\r\n#os.environt['ENDPOINT_NAME']\r\nruntime = boto3.client('runtime.sagemaker')\r\n\r\ndef lambda_handler(event, context):\r\n try:\r\n print(\"Parámetros Recibidos Evento: \" + json.dumps(event, indent=2))\r\n payload = format(event['queryStringParameters']['data'])\r\n print(\"Payload: \" + payload)\r\n ENDPOINT_NAME = format(event['queryStringParameters']['endpoint'])\r\n \r\n print(\"End-Point: \" + ENDPOINT_NAME)\r\n \r\n response = runtime.invoke_endpoint(EndpointName= ENDPOINT_NAME, ContentType='text/csv',Body=payload)\r\n print(\"Response: \")\r\n print(response)\r\n \r\n result = json.loads(response['Body'].read().decode())\r\n print(\"Result: \")\r\n print(result)\r\n \r\n pred = (result['predictions'][0]['score'])\r\n predicted_label = 'Good' if pred >= 0.85 else 'Bad'\r\n \r\n fecha = datetime.now().strftime(\"%b-%d-%Y %H:%M:%S\")\r\n \r\n # Crear un objeto JSON de respuesta\r\n respuesta = {\r\n 'prediccion': predicted_label,\r\n 'fecha': fecha\r\n }\r\n \r\n print(predicted_label)\r\n return {\r\n 'statusCode': 200,\r\n 'body': json.dumps(respuesta),\r\n 'headers': {\r\n 'Content-Type': 'application/json',\r\n 'Access-Control-Allow-Origin': '*' # Esto es para CORS, si es necesario\r\n }\r\n }\r\n \r\n except Exception as e:\r\n # Captura y maneja cualquier excepción que ocurra\r\n error_message = str(e)\r\n print(\"Error: \" + error_message)\r\n\r\n # Devuelve una respuesta de error\r\n return {\r\n 'statusCode': 500,\r\n 'body': json.dumps({'error': error_message}),\r\n 'headers': {\r\n 'Content-Type': 'application/json',\r\n 'Access-Control-Allow-Origin': '*' # Esto es para CORS, si es necesario\r\n }\r\n }","repo_name":"elealtns/TFMUnir","sub_path":"Funcion Lambda.py","file_name":"Funcion Lambda.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"12645626481","text":"# 给定一个整数 n,生成所有由 1 ... n 为节点所组成的 二叉搜索树 。\n# Definition for a binary tree node.\nfrom typing import List\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0):\n self.val = val\n self.left = None\n self.right = None\n def return_res(self):\n res = self.left + self.right\n return res\n\n\nclass Solution:\n def generateTrees(self, n: int) -> List[TreeNode]:\n def generateTrees(start, end):\n if start > end:\n return [None]\n allTrees = []\n for i in range(start, end + 1): # 枚举可行根节点\n # 获得所有可行的左子树集合\n leftTrees = generateTrees(start, i - 1)\n # 获得所有可行的右子树集合\n rightTrees = generateTrees(i + 1, end)\n # 从左子树集合中选出一棵左子树,从右子树集合中选出一棵右子树,拼接到根节点上\n for l in leftTrees:\n for r in rightTrees:\n currTree = TreeNode(i)\n currTree.left = l\n currTree.right = r\n allTrees.append(currTree)\n\n return allTrees\n\n return generateTrees(1, n) if n else []\n\n def generateTrees_1(self, n: int) -> List[TreeNode]:\n if (n == 0):\n return []\n\n def build_Trees(left, right):\n all_trees = []\n if (left > right):\n return [None]\n for i in range(left, right + 1):\n left_trees = build_Trees(left, i - 1)\n right_trees = build_Trees(i + 1, right)\n for l in left_trees:\n for r in right_trees:\n cur_tree = TreeNode(i)\n cur_tree.left = l\n cur_tree.right = r\n all_trees.append(cur_tree)\n return all_trees\n\n res = build_Trees(1, n)\n return res\n\n def generateTrees_2(self, n):\n \"\"\"\n :type n: int\n :rtype: List[TreeNode]\n \"\"\"\n # 如果 为空树\n if not n:\n return []\n\n def new_trees(start, end):\n if start > end:\n return [None]\n\n all_trees = []\n # 针对(start,end)中的每一个i进行切分,也就是求G(i),判断左右是否有节点,通过start和end比较\n for i in range(start, end + 1):\n # 左子树\n left_trees = new_trees(start, i - 1)\n # 右子树\n right_trees = new_trees(i + 1, end)\n\n for left in left_trees:\n for right in right_trees:\n tree = TreeNode(i)\n tree.left = left\n tree.right = right\n all_trees.append(tree)\n # print(all_trees)\n # 注:每次递归进入的子树的all_trees都是不一样的。可以通过打印print()查看控制台的输出,这样更容易理解具体的思路。\n return all_trees\n\n return new_trees(1, n)\n\n\nxyb = Solution().generateTrees_2(3)\nprint(xyb)\n","repo_name":"Jacob-xyb/leetcode_Jacob","sub_path":"python/Jx2020/(未解决)95. 不同的二叉搜索树 II.py","file_name":"(未解决)95. 不同的二叉搜索树 II.py","file_ext":"py","file_size_in_byte":3285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"2874919617","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse, JsonResponse\nfrom datetime import datetime, timezone\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.decorators import login_required\n\nfrom . import models\nfrom . import forms\n\ndef logout_view(request):\n logout(request)\n return redirect(\"/login/\")\n\ndef register_view(request):\n if request.method == \"POST\":\n form_instance = forms.RegistrationForm(request.POST)\n if form_instance.is_valid():\n form_instance.save()\n return redirect(\"/login/\")\n else:\n form_instance = forms.RegistrationForm()\n\n context = {\n \"title\":\"Registration\",\n \"form\":form_instance\n }\n return render(request, \"registration/register.html\", context=context)\n\n@login_required\ndef character_view(request):\n if request.method== \"POST\":\n character_form = forms.CharacterForm(request.POST, request.FILES)\n if character_form.is_valid():\n character_form.save(request)\n return redirect(\"/\")\n else:\n character_form = forms.CharacterForm()\n context = {\n \"title\":\"Add Your Character!\",\n \"form\":character_form,\n }\n return render(request, \"character.html\", context=context)\n\nrolls = ((\"Acrobatics\", \"DEX\"),(\"Animal Handling\", \"WIS\"),(\"Arcana\", \"INT\"),(\"Athletics\", \"STR\"),(\"Deception\", \"CHA\"),\n(\"History\", \"INT\"),(\"Insight\", \"WIS\"),(\"Intimidation\", \"CHA\"),(\"Investigation\", \"INT\"),(\"Medicine\", \"WIS\"),(\"Nature\", \"INT\"),\n(\"Perception\", \"WIS\"),(\"Performance\", \"CHA\"),(\"Persuasion\", \"CHA\"),(\"Religion\", \"INT\"),(\"Sleight of Hand\", \"DEX\"),(\"Stealth\", \"DEX\"),(\"Survival\", \"WIS\"))\n@login_required\ndef functions_view(request):\n context = {\n \"title\":\"Interact with your Character!\",\n \"rolls\": rolls,\n }\n return render(request, \"functions.html\", context=context)\n\n# Create your views here.\ndef index(request):\n context = {\n \"title\": \"CINS 465 Title\",\n \"variable\": \"CINS465 Hello World\"\n }\n return render(request, \"index.html\", context=context)\n #return HttpResponse(\"CINS465 Hello World\")\n\ndef home(request):\n if request.user.is_authenticated:\n exists = models.CharacterModel.objects.filter(player_id=request.user).exists()\n else:\n exists = False\n context = {\n \"title\": \"Homepage\",\n \"exists\": exists,\n }\n return render(request, \"home.html\", context=context)\n\ndef about(request):\n context = {\n \"title\": \"about\",\n }\n return render(request, \"about.html\", context=context)\n\ndef characters_view(request):\n character_objects = models.CharacterModel.objects.all().order_by('-name')\n characters = {}\n characters[\"characters\"] = []\n for charz in character_objects:\n temp_char = {}\n temp_char[\"description\"] = charz.description\n temp_char[\"name\"] = charz.name\n temp_char[\"race\"] = charz.race\n temp_char[\"weapon\"] = charz.weapon\n characters[\"characters\"] += [temp_char]\n return JsonResponse(characters)\n\ndef functionz_view(request):\n character_object = models.CharacterModel.objects.all().get(player_id = request.user)\n the_character = {}\n the_character[\"description\"] = character_object.description\n the_character[\"name\"] = character_object.name\n the_character[\"race\"] = character_object.race\n the_character[\"weapon\"] = character_object.weapon\n the_character[\"strength\"] = character_object.strength\n the_character[\"wisdom\"] = character_object.wisdom\n the_character[\"charisma\"] = character_object.charisma\n the_character[\"dexterity\"] = character_object.dexterity\n the_character[\"intelligence\"] = character_object.intelligence\n return JsonResponse(the_character)\n\n@login_required\ndef tavern(request):\n return render(request, 'tavern.html')\n\n@login_required\ndef room(request, room_name):\n return render(request, 'room.html', {\n 'room_name': room_name\n })\n","repo_name":"braedinmgregoire/DndWebsite","sub_path":"baedin/myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"33959058685","text":"binaryx = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nprint(binaryx)\ndef twobinary(binary):\n binary[len(binary)-1]=1\n print(binary)\n binary[len(binary)-1]=0\n binary[len(binary)-2]=1\n print(binary)\n binary[len(binary)-1]=1\n print(binary)\n return \ndef threebinary(binarythree):\n print('.',binarythree)\n i = twobinary(binarythree)\n print('.',binarythree)\n binarythree[len(binarythree)-3]=1\n i = twobinary(binarythree)\n return\nprint(threebinary(binaryx))\n\n \n \n","repo_name":"AayushAnimalFriends/codingclass2-Journal","sub_path":"papas challenge.py","file_name":"papas challenge.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"36675019450","text":"import random\r\nimport time\r\n\r\ntooHot = Exception(\"Over Temperature Limit\",\"Check the water level\")\r\nmaxtemp = 150\r\ndef get_temp():\r\n return random.randint(30,155)\r\n\r\nwhile True:\r\n current_temp = get_temp()\r\n print(current_temp, end=\"\")\r\n if current_temp< maxtemp:\r\n print(\"Keep Driving\")\r\n time.sleep(0.2)\r\n else:\r\n raise tooHot\r\n","repo_name":"DeepakAddepalli/python","sub_path":"exception_hand.py","file_name":"exception_hand.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"35964087417","text":"import numpy as np\nfrom complete_unitary import complete_unitary\nfrom qiskit import QuantumCircuit, QuantumRegister\n\n\nclass Oracle(QuantumCircuit):\n def __init__(\n self,\n p: float,\n w_len: int,\n name: str = \"$O_x$\",\n ):\n self.p_ = p\n self.w_len = w_len\n self.w_reg = QuantumRegister(w_len, name=\"w\")\n self.y_reg = QuantumRegister(1, name=\"y\")\n super().__init__(self.y_reg, self.w_reg, name=name)\n self._build()\n\n def _matrix(self) -> np.ndarray:\n p_w = np.zeros(2**self.w_len)\n\n def y_x(w: int) -> int:\n return 1 if w == 0 else 0\n\n p_w[0] = self.p_\n p_w[1:] = (1 - self.p_) / (2**self.w_len - 1)\n\n row = np.zeros(2 ** (self.w_len + 1))\n\n for w in range(2**self.w_len):\n\n for y in range(2):\n col = 2 * w + y\n row[col] = np.sqrt(p_w[w]) if y == y_x(w) else 0\n\n return complete_unitary({0: row}).T\n\n def _build(self) -> None:\n mat = self._matrix()\n\n self.unitary(\n mat,\n self.qubits,\n label=self.name,\n )\n\n def inverse(self) -> QuantumCircuit:\n inv = super().inverse()\n inv.name = self.name + \"$^\\\\dagger$\"\n return inv\n\n\ndef main():\n from qiskit import Aer, assemble\n from qiskit.quantum_info import Statevector\n\n qc = Oracle(0.7, 1)\n backend = Aer.get_backend(\"statevector_simulator\")\n job = backend.run(assemble(qc))\n result = job.result()\n statevector = Statevector(result.get_statevector())\n probs = statevector.probabilities_dict()\n for k, v in probs.items():\n print(f\"{k}: {v:.3f}\")\n print()\n\n print(statevector)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"boyesjo/tma4900","sub_path":"code/wan/oracle.py","file_name":"oracle.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"36356781690","text":"from datetime import datetime\n\nimport numpy as np\nimport pandas as pd\n\nfrom course_lib.Base.Evaluation.Evaluator import EvaluatorHoldout\nfrom src.data_management.New_DataSplitter_leave_k_out import New_DataSplitter_leave_k_out\nfrom src.data_management.RecSys2019Reader import RecSys2019Reader\nfrom src.data_management.data_reader import get_ignore_users\nfrom src.model.Ensemble.Boosting.boosting_preprocessing import get_label_array, preprocess_dataframe_after_reading\nfrom src.tuning.holdout_validation.run_parameter_search_lightgbm import run_parameter_search_lightgbm\nfrom src.utils.general_utility_functions import get_split_seed\n\nif __name__ == '__main__':\n # Data loading\n root_data_path = \"../../data/\"\n data_reader = RecSys2019Reader(root_data_path)\n data_reader = New_DataSplitter_leave_k_out(data_reader, k_out_value=3, use_validation_set=False,\n force_new_split=True, seed=get_split_seed())\n data_reader.load_data()\n URM_train, URM_test = data_reader.get_holdout_split()\n\n # Reading the dataframe\n dataframe_path = \"../../resources/boosting_dataframe/\"\n train_df = pd.read_csv(dataframe_path + \"train_df_100_advanced_lt_20.csv\")\n valid_df = pd.read_csv(dataframe_path + \"valid_df_30_advanced_lt_20.csv\")\n\n train_df = preprocess_dataframe_after_reading(train_df)\n y_train = train_df['label'].values + 1\n\n train_df = train_df.drop(columns=[\"label\"],\n inplace=False)\n valid_df = preprocess_dataframe_after_reading(valid_df)\n valid_df = valid_df.drop(columns=[],\n inplace=False)\n\n _, non_zero_count, total = get_label_array(data_frame=train_df, URM_train=URM_train)\n y_valid, _, _ = get_label_array(data_frame=valid_df, URM_train=URM_test)\n\n # Setting evaluator\n mapper = data_reader.get_original_user_id_to_index_mapper()\n ignore_users = get_ignore_users(URM_train, mapper, lower_threshold=20, upper_threshold=2 ** 16 - 1,\n ignore_non_target_users=True)\n evaluator = EvaluatorHoldout(URM_test, cutoff_list=[10], ignore_users=ignore_users)\n total_users = np.arange(URM_train.shape[0])\n mask = np.in1d(total_users, ignore_users, invert=True)\n users_to_validate = total_users[mask]\n\n # HP tuning\n print(\"Start tuning...\")\n version_path = \"../../report/hp_tuning/light_gbm/\"\n now = datetime.now().strftime('%b%d_%H-%M-%S')\n now = now + \"_k_out_value_3_eval/\"\n version_path = version_path + now\n\n run_parameter_search_lightgbm(URM_train, train_df, y_train, valid_df, y_valid, cutoff_test=30,\n categorical_features=[],\n num_iteration=10000, early_stopping_iteration=150,\n objective=\"lambdarank\", verbose=True,\n output_folder_path=version_path, evaluator_validation=evaluator,\n n_cases=100, n_random_starts=40, metric_to_optimize=\"MAP\")\n\n print(\"...tuning ended\")\n","repo_name":"riccardopoiani/recsys-competition","sub_path":"scripts/hp_tuning/lgb_tuning.py","file_name":"lgb_tuning.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"31454644045","text":"class Solution:\n def countEven(self, num: int) -> int:\n ans = 0\n for i in range(2, num+1):\n temp = 0\n\n while i != 0:\n digit = i % 10\n temp += digit\n i //= 10\n\n if temp % 2 == 0:\n ans += 1\n\n return ans\n\n\n# JS solution\n\"\"\"\n/**\n * @param {number} num\n * @return {number}\n */\nvar countEven = function(num) {\n let nums = [];\n for (let i = 2; i <= num; i++) {\n nums.push(i);\n }\n\n let ans = 0;\n for (let n of nums) {\n let temp = 0;\n while (n != 0) {\n let digit = n % 10;\n temp += digit;\n n = Math.floor(n / 10);\n }\n\n if (temp % 2 === 0) {\n ans += 1;\n }\n }\n return ans;\n};\n\"\"\"\n","repo_name":"Shamsiddinov70/Algorithms_LeetCode","sub_path":"february_challenge_2023/11_countEven.py","file_name":"11_countEven.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"26910599211","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 7 17:42:16 2022\n\n@author: Sbhatia3\n\"\"\"\nimport json\nimport requests\nimport sys\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nfrom pyVim import connect\nimport ssl\nfrom pyVmomi import vim\nimport re\nimport collections\n\n#Defining class for structural collection of Config file parameters.\nclass OrderedConfig(collections.OrderedDict):\n pass\n\napp_settings = {\n 'api_pass': \"XXXX\",\n 'api_user': \"administrator@vsphere.local\",\n 'api_url': \"https:///rest/\",\n 'vcenter_ip': \"xx.xx.xx.xx\",\n 'VM_name': \"UbantuTest\", ### Desired VM for which we need to find details\n 'vsphere_datacenter': \"ECM\"\n}\n\n## Authenticate with Vcenter to find the VM ID\ndef auth_vcenter(username, password):\n #print('Authenticating to vCenter, user: {}'.format(username))\n resp = requests.post(\n '{}/com/vmware/cis/session'.format(app_settings['api_url']),\n auth=(app_settings['api_user'], app_settings['api_pass']),\n verify=False\n )\n if resp.status_code != 200:\n print('Error! API responded with: {}'.format(resp.status_code))\n return\n return resp.json()['value']\n\ndef get_api_data(req_url):\n sid = auth_vcenter(app_settings['api_user'], app_settings['api_pass'])\n #print('Requesting Page: {}'.format(req_url))\n resp = requests.get(req_url, verify=False, headers={'vmware-api-session-id': sid})\n if resp.status_code != 200:\n print('Error! API responded with: {}'.format(resp.status_code))\n return\n return resp\n\n## Getting VM details including VM ID needed to browser through MOB\ndef get_vm(vm_name):\n resp = get_api_data('{}/vcenter/vm?filter.names={}'.format(app_settings['api_url'], vm_name))\n j = resp.json()\n return (j)\n\n#Fetching VM ID from REST API for the VM we want to import\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\nvmdetails = get_vm(app_settings['VM_name'])\nvmid = vmdetails['value'][0]['vm']\n\ns = ssl._create_unverified_context()\nservice_instance = connect.SmartConnect(\n host=app_settings['vcenter_ip'], user=app_settings['api_user'], pwd=app_settings['api_pass'], sslContext=s\n)\ncontent = service_instance.RetrieveContent()\ncontainer = content.rootFolder # starting point to look into\nviewType = [vim.VirtualMachine] # object types to look for\nrecursive = True # whether we should look into it recursively\ncontainerView = content.viewManager.CreateContainerView(container, viewType, recursive) # create container view\nchildren = containerView.view\nfor child in children: # for each statement to iterate all names of VMs in the environment\n if (str(vmid) in str(child)):\n vm_summary = child.summary #Summary of the desired VM to import\n vm_config = child.config #Complete config data hiararchy and child item values loaded in the variable\n vm_resourcepool = child.resourcePool #Resource pool details\n vm_network = child.network #Network details of the VM\n vm_datastore = child.datastore\n vm_parent = child.parent\n\n# Config file structure and populating with corresponding values fetched with MOB\ndata = OrderedConfig()\ndata[\"provider\"] = OrderedConfig()\ndata[\"provider\"][\"vsphere\"] = OrderedConfig()\ndata[\"provider\"][\"vsphere\"][\"user\"] = \"sampleuser\"\ndata[\"provider\"][\"vsphere\"][\"password\"] = \"samplepassword\"\ndata[\"provider\"][\"vsphere\"][\"allow_unverified_ssl\"] = \"true\"\n\n#Posting resource pool details\nresourcepool_string = str(vm_resourcepool.owner.name) + '/' + str(vm_resourcepool.name)\ndata[\"data\"] = OrderedConfig()\n\ndata[\"data\"][\"vsphere_datacenter\"] = OrderedConfig()\ndata[\"data\"][\"vsphere_datacenter\"][\"dc\"] = OrderedConfig()\ndata[\"data\"][\"vsphere_datacenter\"][\"dc\"][\"name\"] = app_settings['vsphere_datacenter']\n\ndata[\"data\"][\"vsphere_resource_pool\"] = OrderedConfig()\ndata[\"data\"][\"vsphere_resource_pool\"][\"pool\"] = OrderedConfig()\ndata[\"data\"][\"vsphere_resource_pool\"][\"pool\"][\"name\"] = resourcepool_string\ndata[\"data\"][\"vsphere_resource_pool\"][\"pool\"][\"datacenter_id\"] = \"${data.vsphere_datacenter.dc.id}\"\n\n#Posting datastore details\ndatastore_string = str(vm_datastore[0].name)\ndata[\"data\"][\"vsphere_datastore\"] = OrderedConfig()\ndata[\"data\"][\"vsphere_datastore\"][\"datastore\"] = OrderedConfig()\ndata[\"data\"][\"vsphere_datastore\"][\"datastore\"][\"name\"] = datastore_string\ndata[\"data\"][\"vsphere_datastore\"][\"datastore\"][\"datacenter_id\"] = \"${data.vsphere_datacenter.dc.id}\"\n\n#Posting virtual machine details\ndatastore_string = str(vm_datastore[0].name)\ndata[\"data\"][\"vsphere_virtual_machine\"] = OrderedConfig()\ndata[\"data\"][\"vsphere_virtual_machine\"][\"template\"] = OrderedConfig()\ndata[\"data\"][\"vsphere_virtual_machine\"][\"template\"][\"name\"] = str(vm_config.name)\ndata[\"data\"][\"vsphere_virtual_machine\"][\"template\"][\"datacenter_id\"] = \"${data.vsphere_datacenter.dc.id}\"\n\n#for all network adapter, creating a stack, adapter details in order\nnetwork_adapter = []\nfor item_netadapter in vm_config.hardware.device:\n if (str(\"Network adapter\") in str(item_netadapter.deviceInfo.label)):\n vm_networkadapter = item_netadapter\n #Posting adapter type for Network interface details\n if (str(\"E1000e\") in str(type(vm_networkadapter))):\n network_adapter.append(\"e1000e\")\n if (str(\"Vmxnet3\") in str(type(vm_networkadapter))):\n network_adapter.append(\"vmxnet3\")\n\ndata[\"resource\"] = OrderedConfig()\ndata[\"resource\"][\"vsphere_virtual_machine\"] = OrderedConfig()\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"] = OrderedConfig()\n\n#Posting network details and adding network interface details at same order\nfor index, nic in enumerate(vm_network): \n network_string = str(nic.name)\n data[\"data\"][\"vsphere_network\"+str(index)] = OrderedConfig()\n data[\"data\"][\"vsphere_network\"+str(index)][\"network\"+str(index)] = OrderedConfig()\n data[\"data\"][\"vsphere_network\"+str(index)][\"network\"+str(index)][\"name\"] = network_string\n data[\"data\"][\"vsphere_network\"+str(index)][\"network\"+str(index)][\"datacenter_id\"] = \"${data.vsphere_datacenter.dc.id}\"\n\nfor index, nic in reversed(list(enumerate(vm_network))): \n #adding network interface details\n #network_string = str(nic.name)\n #print(nic.name)\n data[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"network_interface\"+str(index)] = { \"adapter_type\" : network_adapter.pop() }\n data[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"network_interface\"+str(index)][\"network_id\"] = str(\"${data.vsphere_network.\"+\"network\"+str(index)+\".id}\")\n\n#########################################################################\n#########################################################################\n###################Posting other VM generic details######################\n#########################################################################\n#########################################################################\n\n#Posting Name of the Virtual machine\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"name\"] = str(vm_config.name)\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"folder\"] = vm_parent.name\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"resource_pool_id\"\n ] = \"${data.vsphere_resource_pool.pool.id}\"\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"datastore_id\"] = \"${data.vsphere_datastore.datastore.id}\"\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"boot_retry_enabled\"\n ] = vm_config.bootOptions.bootRetryEnabled\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"enable_disk_uuid\"] = vm_config.flags.diskUuidEnabled\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"enable_logging\"] = vm_config.flags.enableLogging\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"num_cores_per_socket\"\n ] = vm_config.hardware.numCoresPerSocket\n\n#Posting Number of CPU's\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"num_cpus\"] = vm_config.hardware.numCPU\n\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"guest_id\"] = str(vm_config.guestId)\n#Posting Memory\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"memory\"] = vm_config.hardware.memoryMB\n\n#Posting guestid\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"guest_id\"] = str(vm_config.guestId)\n\n#Posting CPU Hot add enabled flag info\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"cpu_hot_add_enabled\"] = str(vm_config.cpuHotAddEnabled\n ).lower()\n\n#Posting Memory hot add enabled flag info\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"memory_hot_add_enabled\"] = str(\n vm_config.memoryHotAddEnabled\n).lower()\n\n#Posting firmware information\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"firmware\"] = str(vm_config.firmware).lower()\n\n#Posting scsi type information\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"scsi_type\"] = \"${data.vsphere_virtual_machine.template.scsi_type}\"\n\n#Posting ignore tags and custom attribute changes\ndata[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][\"lifecycle\"] = { \"ignore_changes\": [\"custom_attributes\", \"tags\"]}\ndisk_starting_name = \"disk\"\nno_of_disk = 0\n\n#Posting disk information\nfor item_virtualdisk in vm_config.hardware.device:\n if (str(\"VirtualDisk\") in str(type(item_virtualdisk))):\n diskname = disk_starting_name + str(no_of_disk)\n data[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][diskname] = OrderedConfig()\n data[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][diskname][\"label\"] = \"disk\" + str(\n item_virtualdisk.unitNumber\n )\n data[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][diskname][\"size\"] = int(\n item_virtualdisk.capacityInKB / 1048576\n )\n data[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][diskname][\"unit_number\"] = item_virtualdisk.unitNumber\n data[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][diskname][\"thin_provisioned\"] = str(\n item_virtualdisk.backing.thinProvisioned\n ).lower()\n data[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][diskname][\"path\"] = str(\n item_virtualdisk.backing.fileName\n )\n data[\"resource\"][\"vsphere_virtual_machine\"][\"jsontemplate\"][diskname][\"keep_on_remove\"] = \"true\"\n no_of_disk += 1\n\nfor key in data:\n if (key == 'resource'):\n for t in data[key]:\n if (t == 'vsphere_virtual_machine'):\n data[key][t][str(vm_config.name)] = data[key][t].pop('jsontemplate')\n\n#getting json string (Order changing issue)\njson_string = json.dumps(data, indent = 4)\n\n#replacing all different diskname(eg: disk0) to \"disk\" itself\nfor i in range(no_of_disk):\n replace_string = '\"disk'+ str(i) +'\": {'\n json_string = re.sub(replace_string, '\"disk\": {', json_string) \n\n#replacing all different diskname(eg: \"vsphere_network0\") to \"vsphere_network\" itself\nfor i in range(len(vm_network)):\n replace_string = '\"vsphere_network'+ str(i) +'\": {'\n json_string = re.sub(replace_string, '\"vsphere_network\": {', json_string) \n\n#replacing all different diskname(eg: \"network_interface0\") to \"network_interface\" itself\nfor i in range(len(vm_network)):\n replace_string = '\"network_interface'+ str(i) +'\": {'\n json_string = re.sub(replace_string, '\"network_interface\": {', json_string) \n\nsys.stdout.write(json_string)\n\n#outputting config JSON file\nwith open(\"main.tf.json\", \"w\") as outfile:\n outfile.write(json_string)\n","repo_name":"sumitbhatia1986/Terraform-VMware-ReverseEngineering","sub_path":"import_script.py","file_name":"import_script.py","file_ext":"py","file_size_in_byte":11729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"22203166631","text":"from maestro.core.store import BaseDataStore\nfrom maestro.core.query.metadata import Query\nfrom maestro.core.metadata import (\n ItemChange,\n ConflictLog,\n ItemVersion,\n Operation,\n SyncSession,\n)\nfrom maestro.backends.base_nosql.collections import CollectionType\nfrom maestro.backends.base_nosql.utils import type_to_collection\nfrom typing import List, Dict, Any, cast, Optional\nfrom abc import abstractmethod\nimport copy\n\n\nclass NoSQLDataStore(BaseDataStore):\n def update_vector_clocks(self, item_change: \"ItemChange\"):\n \"\"\"\n Updates the cached VectorClocks with the new change.\n\n Args:\n item_change (ItemChange): ItemChange that was saved to the data store\n\n \"\"\"\n item_change_record = self.item_change_metadata_converter.to_record(\n metadata_object=item_change\n )\n change_vector_clock_item = copy.deepcopy(\n item_change_record[\"change_vector_clock_item\"]\n )\n change_vector_clock_item[\"id\"] = change_vector_clock_item[\"provider_id\"]\n self._save(\n instance=change_vector_clock_item,\n collection=type_to_collection(key=CollectionType.PROVIDER_IDS),\n )\n\n @abstractmethod\n def find_item_changes(self, ids: \"List[str]\") -> \"List[ItemChange]\":\n \"\"\"\n Finds multiple ItemChanges by their IDs. The elements must be returned in\n the same order as the list of IDs.\n\n Args:\n ids (List[str]): List of ItemChange IDs\n \"\"\"\n\n @abstractmethod\n def _save(self, instance: \"Dict\", collection: \"str\"):\n \"\"\"\n Saves an item to the data store.\n\n Args:\n instance (Dict): data being saved\n collection (str): collection name\n \"\"\"\n\n @abstractmethod\n def _delete(self, instance: \"Dict\", collection: \"str\"):\n \"\"\"\n Deletes an item from the data store.\n\n Args:\n instance (Dict): item being deleted\n collection (str): collection name\n \"\"\"\n\n def save_item(self, item: \"Any\"):\n copied = copy.deepcopy(item)\n self._save(instance=copied, collection=copied.pop(\"collection_name\"))\n\n def delete_item(self, item: \"Any\"):\n copied = copy.deepcopy(item)\n self._delete(instance=copied, collection=copied.pop(\"collection_name\"))\n\n def save_item_change(\n self,\n item_change: \"ItemChange\",\n is_creating: \"bool\" = False,\n query: \"Optional[Query]\" = None,\n ) -> \"ItemChange\":\n item_change_record = self.item_change_metadata_converter.to_record(\n metadata_object=item_change\n )\n self._save(\n instance=item_change_record,\n collection=type_to_collection(key=CollectionType.ITEM_CHANGES),\n )\n if is_creating:\n self.update_vector_clocks(item_change=item_change)\n\n return item_change\n\n def save_conflict_log(self, conflict_log: \"ConflictLog\"):\n conflict_log_record = self.conflict_log_metadata_converter.to_record(\n metadata_object=conflict_log\n )\n self._save(\n instance=conflict_log_record,\n collection=type_to_collection(key=CollectionType.CONFLICT_LOGS),\n )\n\n def execute_item_change(self, item_change: \"ItemChange\"):\n item = self.deserialize_item(\n serialization_result=item_change.serialization_result\n )\n\n if item_change.operation == Operation.DELETE:\n self.delete_item(item=item)\n else:\n self.save_item(item=item)\n\n def save_item_version(self, item_version: \"ItemVersion\"):\n item_version_record = self.item_version_metadata_converter.to_record(\n metadata_object=item_version\n )\n self._save(\n instance=item_version_record,\n collection=type_to_collection(key=CollectionType.ITEM_VERSIONS),\n )\n\n def save_sync_session(self, sync_session: \"SyncSession\"):\n sync_session_record = self.sync_session_metadata_converter.to_record(\n metadata_object=sync_session\n )\n self._save(\n instance=sync_session_record,\n collection=type_to_collection(key=CollectionType.SYNC_SESSIONS),\n )\n\n def item_to_dict(self, item: \"Any\") -> \"Dict\":\n data = copy.deepcopy(cast(\"Dict\", item))\n data.pop(\"collection_name\")\n return data\n","repo_name":"estudio89/maestro-python","sub_path":"maestro/backends/base_nosql/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"74823443293","text":"from typing import Iterable\nimport pandas as pd\nimport re\nfrom pprint import pprint\nfrom pymorphy2 import MorphAnalyzer\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.decomposition import TruncatedSVD\nimport numpy as np\nimport optuna\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import RidgeClassifier\nfrom sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score\nfrom sklearn.metrics import balanced_accuracy_score, make_scorer\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import LinearSVC \nfrom sklearn.linear_model import LogisticRegression\nfrom statistics import median\n\n\nALLOWED_CHARS = \"абвгдеёжзийклмонпрстуфхцчшщъыьэюя \"\n\n# Функция чистит строку от всех посторонних символов. Разрешенные символы передаются через allowed_chars\ndef filter_forbidden_chars(text : str, allowed_chars : Iterable):\n filter_fn = lambda char: char if char in allowed_chars else \" \"\n return re.sub(\" +\", \" \", \"\".join([filter_fn(char) for char in text])).strip()\n\n# Функция ставит все слова в строке в начальную форму\ndef all_words_to_infinitive(text : str, analyzer : MorphAnalyzer):\n words = text.split(\" \")\n return \" \".join([analyzer.parse(word)[0].normal_form for word in words]).strip()\n\n# Функция полностью обрабатывает текст\ndef preprocess(data):\n data['text'] = data['text'].apply(str.lower)\n\n data['text'] = data['text'].apply(lambda text: filter_forbidden_chars(text, ALLOWED_CHARS))\n\n morpher = MorphAnalyzer()\n\n data['text'] = data['text'].apply(lambda text: all_words_to_infinitive(text, morpher))\n \n return data\n\n# Функция для кросс-валидации\n# Из-за очень значительного дисабаланса классов повторять приходится много раз\n# Иначе результаты ненадежны и выводы о хорошем обобщении моделью данных\n# сделать нельзя.\ndef eval_model(model, data, y):\n return median(cross_val_score(model, data, y, scoring=make_scorer(balanced_accuracy_score),\n cv=RepeatedStratifiedKFold(n_splits=3, n_repeats=25)))\n\n# функция для оптимизации параметров svc модели\ndef svc_objective(trial : optuna.Trial, data):\n\n model = make_pipeline(TfidfVectorizer(min_df=trial.suggest_int(\"min_df1\", 1, 12), max_df=trial.suggest_float(\"max_df1\", 0.5, 1.0),\n ngram_range=(1, trial.suggest_int(\"max_ngram1\", 1, 8)), analyzer='word'), \n LinearSVC(C=trial.suggest_float(\"C1\", 0.001, 100.0), max_iter=1000,\n multi_class=trial.suggest_categorical(\"multiclass1\", ['crammer_singer', 'ovr']),\n class_weight='balanced', dual=trial.suggest_categorical(\"dual1\", [True, False])))\n \n return eval_model(model, data['text'], data['y'])\n\n# функция для оптимизации параметров LogisticRegression\ndef logistic_objective(trial : optuna.Trial, data):\n\n model = make_pipeline(TfidfVectorizer(min_df=trial.suggest_int(\"min_df1\", 1, 12), max_df=trial.suggest_float(\"max_df1\", 0.5, 1.0),\n ngram_range=(1, trial.suggest_int(\"max_ngram1\", 1, 8)), analyzer='word'), \n LogisticRegression(C=trial.suggest_float(\"C\", 0.0001, 100.0), \n solver=trial.suggest_categorical(\"solver\", ['newton-cg', 'sag', 'saga', 'lbfgs']),\n max_iter=10000,\n n_jobs=-1, class_weight='balanced'))\n \n return eval_model(model, data['text'], data['y'])\n\n# функция для оптимизации пары TruncatedSVD + Ridge\ndef lin_trunc_obj(trial : optuna.Trial, data):\n solver = trial.suggest_categorical(\"solver\", ['svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag', 'saga', 'lbfgs'])\n positive = solver == 'lbfgs'\n model = make_pipeline(TfidfVectorizer(min_df=trial.suggest_int(\"min_df1\", 1, 12), max_df=trial.suggest_float(\"max_df1\", 0.5, 1.0),\n ngram_range=(1, trial.suggest_int(\"max_ngram1\", 1, 8)), analyzer='word'),\n TruncatedSVD(n_components=trial.suggest_int(\"n_components\", 2, 256), \n algorithm=trial.suggest_categorical(\"algorithm\", ['arpack', 'randomized']),\n n_iter=trial.suggest_int(\"n_iter\", 2, 12)), \n StandardScaler(),\n RidgeClassifier(alpha=trial.suggest_float(\"alpha\", 0.001, 100.0), class_weight='balanced',\n solver=solver, positive=positive))\n try:\n return eval_model(model, data['text'], data['y'])\n except ValueError:\n return 0.0\n\n# Функция для подбора параметров классификатора на оснвое голосования\n# участвуют все три выбранных типа моделей\ndef best_voting_objective(trial : optuna.Trial, data):\n make_idf = lambda index, trial: TfidfVectorizer(min_df=trial.suggest_int(f\"min_df_{index}\", 1, 12), max_df=trial.suggest_float(f\"max_df_{index}\", 0.5, 1.0),\n ngram_range=(1, trial.suggest_int(f\"max_ngram_{index}\", 1, 8)), analyzer='word')\n\n m1 = make_pipeline(make_idf(1, trial), LinearSVC(C=trial.suggest_float(\"C1\", 0.001, 100.0), max_iter=1000,\n multi_class=trial.suggest_categorical(\"multiclass1\", ['crammer_singer', 'ovr']),\n class_weight='balanced', dual=trial.suggest_categorical(\"dual1\", [True, False])))\n\n m2 = make_pipeline(make_idf(2, trial), LogisticRegression(C=trial.suggest_float(\"C2\", 0.0001, 100.0), \n solver=trial.suggest_categorical(\"solver\", ['newton-cg', 'sag', 'saga', 'lbfgs']),\n max_iter=10000,\n n_jobs=-1, class_weight='balanced'))\n\n m3 = make_pipeline(make_idf(3, trial),\n TruncatedSVD(n_components=trial.suggest_int(\"n_components\", 2, 256), \n algorithm=trial.suggest_categorical(\"algorithm\", ['arpack', 'randomized']),\n n_iter=trial.suggest_int(\"n_iter\", 2, 12)), \n RidgeClassifier(alpha=trial.suggest_float(\"alpha\", 0.001, 100.0), class_weight='balanced',\n solver=trial.suggest_categorical(\"ridge_solver\", ['svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag', 'saga', 'lbfgs']), \n positive=trial.params['ridge_solver'] == 'lbfgs'))\n\n \n model = VotingClassifier([(\"M1\", m1), (\"M2\", m2), (\"M3\", m3)], n_jobs=3)\n \n try:\n return eval_model(model, data['text'], data['y'])\n except ValueError:\n return 0.0\n\n\nif __name__ == \"__main__\":\n # СРАЗУ ЖЕ СБРОСИТЬ ЗАПРЕЩЕННЫЕ ДАННЫЕ И ИЗ ТРЕНИРОВКИ, И ИЗ ТЕСТА\n data = pd.read_csv(\"train_dataset_train.csv\")[['Текст Сообщения', 'Категория']]\n data.rename(columns={\"Текст Сообщения\": \"text\", \"Категория\": \"y\"}, inplace=True)\n\n # Удалить категорию 12 - из-за нее не получается\n # тестировать модель через кросс-валидацию\n data = data.drop(data[data['y']==12].index)\n data.reset_index(inplace=True, drop=True)\n data = preprocess(data)\n\n test = pd.read_csv(\"test_dataset_test.csv\")[['Текст Сообщения', 'id']]\n test.rename(columns={\"Текст Сообщения\": \"text\"}, inplace=True)\n\n test = preprocess(test)\n\n m1 = make_pipeline(TfidfVectorizer(min_df=6, max_df=0.6695288186828025,\n ngram_range=(1, 4), analyzer='word'), \n LinearSVC(C=64.85593893692645, max_iter=1000,\n multi_class='crammer_singer',\n class_weight='balanced', dual=True))\n\n m2 = make_pipeline(TfidfVectorizer(min_df=3, max_df=0.6142292977031804,\n ngram_range=(1, 6), analyzer='word'), \n LogisticRegression(C=0.1467795053973877, \n solver='sag',\n max_iter=10000,\n n_jobs=-1, class_weight='balanced'))\n\n m3 = make_pipeline(TfidfVectorizer(min_df=10, max_df=0.6522187041564516,\n ngram_range=(1, 4), analyzer='word'),\n TruncatedSVD(n_components=159, \n algorithm='arpack',\n n_iter=4), \n RidgeClassifier(alpha=87.83655027139227, class_weight='balanced',\n solver='saga', max_iter=10000))\n\n model = VotingClassifier([(\"M1\", m1), (\"M2\", m2), (\"M3\", m3)], n_jobs=3)\n #print(eval_model(model, data['text'], data['y']))\n \n model.fit(data['text'], data['y'])\n preds = model.predict(test['text'])\n test['Категория'] = preds\n test[['id', 'Категория']].to_csv(\"ens_sub.csv\", index=False)\n \n","repo_name":"goodsuga/rdb_k_model","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":9317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"36566461808","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: waywaywayw\n@date: 2018-09-07\n\"\"\"\n\nimport os, re\nfrom bs4 import BeautifulSoup\nimport requests\nimport json\n\nfrom crawler_myTools.selenium_tools.webdriver import MyWebDriver\n\nfrom my_tools.my_files import MyFiles\nfrom jsonDB_myTools.common import MyJsonDB\n\n\ndef filter_exist(driver, resource_list, db):\n # 过滤掉已经下载好的文件的dfpan地址列表\n for idx, resource in enumerate(resource_list):\n # 处理没有url的resource\n if not resource.get('url') or not resource.get('name') :\n print('遇到异常resource:', resource)\n resource_list.pop(idx)\n continue\n\n driver.get(resource['url'])\n # print(driver.title)\n res_name = driver.title\n res_url = driver.current_url\n if db.is_duplicate('name', res_name) or db.is_duplicate('url', res_url):\n resource_list.pop(idx)\n else:\n resource_list[idx]['name'] = res_name\n resource_list[idx]['url'] = driver.current_url\n\n # 之前request的版本.. 结果遇到了乱码..\n # response = requests.get(dfpan, proxies=proxies, headers=headers)\n # # lf0905-.rar\n # content = response.content.decode(\"utf8\")\n # # debug, 保存内容\n # with open('temp.html', 'wb') as f:\n # f.write(response.content)\n # # 找到该dfpan对应的文件名\n # searchObj = re.match(r'.*(.*?).*', content, re.DOTALL)\n # res_name = searchObj.group(1)\n # print(res_name)\n # print(res_name.encode('utf8').decode('gb18030'))\n\n\ndef get_resouce_from_page(soup):\n # 找到response中所有的资源\n # dfpan_list = ['http://page2.dfpan.com/fs/3k2i3n1g7c6v339/', 'http://page2.dfpan.com/fs/bkeidncgcc4vdf9/']\n resource_list = []\n elem_dfpan = soup.findAll(\"div\", {'class': \"entry_body\"})\n for elem in elem_dfpan:\n resource = {}\n # 获取标题和网址\n a_list = elem.findAll('a')\n for a in a_list:\n e_text = a.get_text()\n a_href = a['href']\n # 有特定符号putpan\n if (a_href.find('putpan') >= 0 or a_href.find('tadown') >= 0):\n # 获取网址\n resource['url'] = a['href']\n break\n # 获取可能的密码\n e_text = elem.get_text()\n if e_text.find('解压码') >= 0 and e_text.find('下载教程') >= 0:\n e_text_1 = re.split(r\"解压码\", e_text)[1]\n e_text_2 = re.split(r\"下载教程\", e_text_1)[0]\n resource['密码'] = e_text_2.strip()\n # add resource\n if resource:\n resource_list.append(resource)\n\n return resource_list\n\n\ndef write_to_db(db_path, save_path, resource_list):\n with open(save_path, 'a', encoding='utf8') as save_file, open(db_path, 'a', encoding='utf8') as db_file:\n for res in resource_list:\n save_file.write(res['url'] + '\\n')\n db_file.write(json.dumps(res, ensure_ascii=False) + '\\n')\n print(json.dumps(res, ensure_ascii=False))\n\n\nif __name__ == '__main__':\n # 数据文件的地址\n db_path = os.path.join('output', 'db_xiaocao.txt')\n db = MyJsonDB(db_path)\n\n beg_page = 1\n end_page = 5\n # 遍历整个blog所有的页面\n for page in range(beg_page, end_page):\n # 填好url\n real_url = 'http://xcbz.blog.fc2blog.us/page-{}.html'.format(page)\n # 请求url\n response = requests.get(real_url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n # 得到资源列表\n resource_list = get_resouce_from_page(soup)\n # 初步过滤:名字已存在的res ,丢弃\n print('page %d, resource_list len : %d' % (page, len(resource_list)))\n\n # 过滤掉已存在的文件\n driver = MyWebDriver(driver_type=2).driver()\n if not driver: print('创建浏览器异常!')\n filter_exist(driver, resource_list, db)\n driver.close()\n\n # 保存需要的dfpan\n print('page %d, filterd resource_list len : %d' % (page, len(resource_list)))\n db.write_to_db(db_path, resource_list, write_mode='a', verbose=True)\n","repo_name":"waywaywayw/_yunfile_crawler","sub_path":"crawler/xiaocao_download.py","file_name":"xiaocao_download.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"70178172256","text":"from turtle import title\nimport incollege\nimport os\n\n\n# Epic 10 API, Due: 11/21/2022 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\ndef test_profileAPIinputHandling(): # test that AccountCreation APIinputHangling is working \n global accounts\n accounts = incollege.AccountCreation(\"testAPI\")\n assert os.path.exists(\"MyCollege_users.txt\") # check that MyCollege_users.txt has the same contents as test_studentAccounts.txt\n assert os.path.exists(\"test_studentAccounts.txt\")\n with open(\"MyCollege_users.txt\", \"r\") as f:\n with open(\"test_studentAccounts.txt\", \"r\") as g:\n assert f.read() == g.read()\n # close txt files\n f.close()\n g.close()\n\n\n# test that JobPosting APIinputHangling is working\ndef test_jobsAPIinputHandling(): # test that JobPosting APIinputHangling is working\n global jobs\n jobs = incollege.JobPosting(\"testAPI\")\n assert os.path.exists(\"MyCollege_jobs.txt\") # check that MyCollege_jobs.txt has the same contents as test_newJobs.txt\n assert os.path.exists(\"test_newJobs.txt\")\n with open(\"MyCollege_jobs.txt\", \"r\") as f:\n with open(\"test_newJobs.txt\", \"r\") as g:\n assert f.read() == g.read() \n f.close()\n g.close()\n \n","repo_name":"Shaunakcp/InCollege","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"36431520741","text":"import os\nimport tempfile\nimport pandas as pd\nimport requests\nfrom dataBaseConn2 import DatabaseConnection\nfrom datetime import datetime\nimport sqlalchemy\n\ncurrentTime = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\ndef downloadA3500():\n url = \"https://www.bcra.gob.ar/Pdfs/PublicacionesEstadisticas/com3500.xls\"\n # Create a temporary directory to store the downloaded file\n temp_dir = tempfile.mkdtemp()\n\n # File path for the downloaded XLS file\n file_path = os.path.join(temp_dir, \"data.xls\")\n\n # Download the XLS file from the URL\n try:\n response = requests.get(url)\n response.raise_for_status() # Check if the request was successful\n with open(file_path, \"wb\") as file:\n file.write(response.content)\n except requests.exceptions.RequestException as e: \n print(f\"An error occurred while downloading the file: {e} a las {currentTime}\")\n return False\n \n print(\"------------------------------------\")\n print(\"A3500 downloaded successfully at \" + currentTime)\n \n # Read the specified range \"A:B\" from the first sheet\n data_df = pd.read_excel(file_path, sheet_name=0, usecols=\"C:D\", skiprows=3)\n\n # Set column names\n data_df.columns = [\"date\", \"A3500\"]\n\n # Convert the \"date\" column to datetime\n date_format = \"%d/%m/%Y\"\n data_df['date'] = pd.to_datetime(data_df['date'], format=date_format)\n\n # connect to the database\n db = DatabaseConnection(db_type=\"postgresql\", db_name= os.environ.get('POSTGRES_DB'))\n db.connect()\n\n # Check if the table exists\n table_exists_query = f\"\"\"\n SELECT table_name \n FROM information_schema.tables \n WHERE table_schema = 'public' AND table_name = 'A3500'\n \"\"\"\n result = pd.read_sql(table_exists_query, db.conn)\n\n if result.empty:\n data_to_insert = data_df\n else:\n query = f'SELECT MAX(date) FROM \"A3500\"'\n last_date = pd.read_sql(query, db.conn).iloc[0,0]\n # convert to datetime in order to compare to the date column in data_df\n last_date = pd.to_datetime(last_date)\n \n data_to_insert = data_df[data_df['date'] > last_date]\n \n if len(data_to_insert) == 0:\n print(\"No rows to be inserted. Exiting...\")\n else:\n print(f\"Inserting {len(data_to_insert)} rows into A3500 Table\")\n # use Date type for the 'date' column in the database to get rid of the time part\n dtypeMap = {'date': sqlalchemy.types.Date}\n result = data_to_insert.to_sql(name = 'A3500', con = db.engine, if_exists = 'append', index = False, dtype=dtypeMap, schema = 'public')\n db.conn.commit()\n print(f\"Number of records inserted as reported by the postgres server: {result}\") \n \n\n db.disconnect()\n\n # Delete the temporary file\n os.remove(file_path)\n\n return True\n\nif __name__ == \"__main__\":\n if downloadA3500() == False:\n print(\"An error occurred while downloading A3500\")\n \n","repo_name":"jmtruffa/downloader","sub_path":"A3500DownloaderPostgres.py","file_name":"A3500DownloaderPostgres.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"30378980394","text":"from django.conf.urls import include, url,patterns\nfrom django.contrib import admin\nfrom client.views import IndexView,LoginView,RegisterView,LogoutView,PlayView,GameView\n\n\nurlpatterns = patterns('',\n\n url(r'^index',IndexView.as_view()),\n\n url(r'^register$', RegisterView.as_view()),\n\n url(r'^login$', LoginView.as_view()),\n\n url(r'^logout$',LogoutView.as_view()),\n\n url(r'^play$',PlayView.as_view()),\n\n url(r'^play/game',GameView.as_view()),\n)\n","repo_name":"dvass01/amazon_giphy","sub_path":"project/client/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"412189486","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom sklearn.metrics import auc, roc_curve\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\n\r\n\r\n# instream\r\n\r\n\r\ntrain = pd.read_csv('./data/what2.csv')\r\ntest = pd.read_csv('./test_what2.csv')\r\n\r\ntrain = train.drop('Unnamed: 0', axis=1)\r\ntest = test.drop(['Unnamed: 0', 'SeriousDlqin2yrs'], axis=1)\r\n\r\n\r\n#\r\n\r\n\r\ndef fillMedian(data, data2):\r\n cols = {}\r\n for i in data.columns:\r\n if (data[i].isnull().sum() > 0):\r\n cols[i] = np.nanmedian(pd.concat([data[i], data2[i]], axis=0))\r\n for i in cols.keys():\r\n data[i].fillna(cols[i], inplace=True)\r\n data2[i].fillna(cols[i], inplace=True)\r\n\r\n\r\nfillMedian(train, test)\r\n\r\n\r\n# train models\r\n\r\n\r\nX = train.drop('SeriousDlqin2yrs', axis=1)\r\ny = train['SeriousDlqin2yrs']\r\n\r\n\r\n# score\r\n\r\n\r\ndef scoring(clf, X, y):\r\n fpr, tpr, thresholds = roc_curve(y, clf.predict_proba(X)[:, 1])\r\n # plt.plot(fpr, tpr, marker = 'o')\r\n # plt.show()\r\n roc_auc = auc(fpr, tpr)\r\n return roc_auc\r\n\r\n\r\n# RF\r\n\r\n\r\nclfRand = RandomForestClassifier(max_depth=7, max_features=0.5, criterion='entropy',\r\n n_estimators=160, n_jobs=-1)\r\nclfRand2 = RandomForestClassifier(max_depth=7, max_features=0.5, criterion='entropy',\r\n n_estimators=200, n_jobs=-1)\r\n\r\n# b = cross_val_score(cv=5, estimator=clfRand, n_jobs=-1, scoring=scoring, X=X, y=y)\r\n\r\nclfRand.fit(X, y)\r\nclfRand2.fit(X, y)\r\n\r\nprint(scoring(clfRand, X, y))\r\nprint(scoring(clfRand2, X, y))\r\n\r\npredClfRand = clfRand.predict_proba(test)[:, 1]\r\npredClfRand2 = clfRand2.predict_proba(test)[:, 1]\r\n\r\n\r\npred = (predClfRand + predClfRand2) / 2\r\n\r\ns = pd.read_csv('./data/ratio_pred.csv')\r\n\r\ns['Probability'] = pred\r\ns['Probability'] = [int(x+0.5) for x in s['Probability']]\r\n# s['Score'] = 900 - 600 * s['Probability']\r\ns.to_csv('test_ans.csv', index=False)\r\n","repo_name":"wang-weishuai/GiveMeSomeCredit","sub_path":"RF_final.py","file_name":"RF_final.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"43182963441","text":"# @Author : lijishi\n# @Contact : lijishi@emails.bjut.edu.cn\n# @Software: Pycharm & Python 3.7\n# @EditTime: Jan 23, 2020\n# @Version : 1.0\n# @describe: Use TencentCloud API Realize OCR\n# @LICENSE : GNU GENERAL PUBLIC LICENSE Version 3\n\n# References\n# https://cloud.tencent.com/document/product/866/33515\n\n'''\n11:通用印刷体识别 12:通用印刷体识别(高速版)13:通用印刷体识别(高精度版) 14:通用手写体识别 15:英文识别\n21:身份证识别 22:营业执照识别 23:银行卡识别 24:名片识别\n31:增值税发票识别 32:运单识别\n41:驾驶证识别 42:车牌识别 43:车辆VIN码识别 44:行驶证识别\n51:算式��别 52:表格识别\n'''\n\nfrom tencentcloud.common import credential\nfrom tencentcloud.common.profile.client_profile import ClientProfile\nfrom tencentcloud.common.profile.http_profile import HttpProfile\nfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException\nfrom tencentcloud.ocr.v20181119 import ocr_client, models\n\ndef Tencent_OCR_Summary(pic_str, mode):\n try:\n cred = credential.Credential(\"Your ID\", \"Your Secret\")\n httpProfile = HttpProfile()\n httpProfile.endpoint = \"ocr.tencentcloudapi.com\"\n clientProfile = ClientProfile()\n clientProfile.httpProfile = httpProfile\n client = ocr_client.OcrClient(cred, \"ap-beijing\", clientProfile)\n\n if mode == '11': #11:通用印刷体识别\n return Tencent_OCR_Basic_Print(pic_str, client)\n elif mode == '12': #12:通用印刷体识别(高速版)\n return Tencent_OCR_Basic_Print_Fast(pic_str, client)\n elif mode == '13': #13:通用印刷体识别(高精度版)\n return Tencent_OCR_Basic_Print_HighAccurate(pic_str, client)\n elif mode == '14': #14:通用手写体识别\n return Tencent_OCR_Handwriting(pic_str, client)\n elif mode == '15': #15:英文识别\n return Tencent_OCR_English(pic_str, client)\n elif mode == '21': #21:身份证识别\n return # 废弃\n elif mode == '22': #22:营业执照识别\n return Tencent_OCR_BizLicense(pic_str, client)\n elif mode == '23': #23:银行卡识别\n return Tencent_OCR_BankCard(pic_str, client)\n elif mode == '24': #24:名片识别\n return # 废弃\n elif mode == '31': #31:增值税发票识别\n return Tencent_OCR_VatInvoice(pic_str, client)\n elif mode == '32': #32:运单识别\n return Tencent_OCR_Waybill(pic_str, client)\n elif mode == '41': #41:驾驶证识别\n return Tencent_OCR_DriverLicense(pic_str, client)\n elif mode == '42': #42:车牌识别\n return Tencent_OCR_LicensePlate(pic_str, client)\n elif mode == '43': #43:车辆VIN码识别\n return Tencent_OCR_Vin(pic_str, client)\n elif mode == '44': #44:行驶证识别\n return # 废弃\n elif mode == '51': #51:算式识别\n return Tencent_OCR_Arithmetic(pic_str, client)\n elif mode == '52': #52:表格识别\n return Tencent_OCR_Table(pic_str, client)\n else:\n return Tencent_OCR_Basic_Print(pic_str, client)\n\n except TencentCloudSDKException as err:\n print(err)\n\n#11:通用印刷体识别\ndef Tencent_OCR_Basic_Print(pic_str, client):\n req = models.GeneralBasicOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\",\"LanguageType\":\"auto\"}'\n params = params_1 + pic_str + params_2\n # params = '{\"ImageBase64\":\"pic_str\",\"LanguageType\":\"auto\"}'\n req.from_json_string(params)\n resp = client.GeneralBasicOCR(req)\n text = resp.to_json_string()\n return text\n\n#12:通用印刷体识别(高速版)\ndef Tencent_OCR_Basic_Print_Fast(pic_str, client):\n req = models.GeneralFastOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n # params = '{\"ImageBase64\":\"pic_str\"}'\n req.from_json_string(params)\n resp = client.GeneralFastOCR(req)\n text = resp.to_json_string()\n return text\n\n#13:通用印刷体识别(高精度版)\ndef Tencent_OCR_Basic_Print_HighAccurate(pic_str, client):\n req = models.GeneralAccurateOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n #params = '{\"ImageBase64\":\"pic_str\"}'\n req.from_json_string(params)\n resp = client.GeneralAccurateOCR(req)\n text = resp.to_json_string()\n return text\n\n#14:通用手写体识别\ndef Tencent_OCR_Handwriting(pic_str, client):\n req = models.GeneralHandwritingOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n #params = '{\"ImageBase64\":\"pic_str\"}'\n req.from_json_string(params)\n resp = client.GeneralHandwritingOCR(req)\n text = resp.to_json_string()\n return text\n\n#15:英文识别\ndef Tencent_OCR_English(pic_str, client):\n req = models.EnglishOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n #params = '{\"ImageBase64\":\"pic_str\"}'\n req.from_json_string(params)\n resp = client.EnglishOCR(req)\n text = resp.to_json_string()\n return text\n\n#22:营业执照识别\ndef Tencent_OCR_BizLicense(pic_str, client):\n req = models.BizLicenseOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n #params = '{\"ImageBase64\":\"pic_str\"}'\n req.from_json_string(params)\n resp = client.BizLicenseOCR(req)\n text = resp.to_json_string()\n return text\n\n#23:银行卡识别\ndef Tencent_OCR_BankCard(pic_str, client):\n req = models.BankCardOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n #params = '{\"ImageBase64\":\"pic_str\"}'\n req.from_json_string(params)\n resp = client.BankCardOCR(req)\n text = resp.to_json_string()\n return text\n\n#31:增值税发票识别\ndef Tencent_OCR_VatInvoice(pic_str, client):\n req = models.VatInvoiceOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n #params = '{\"ImageBase64\":\"pic_str\"}'\n req.from_json_string(params)\n resp = client.VatInvoiceOCR(req)\n text = resp.to_json_string()\n return text\n\n#32:运单识别\ndef Tencent_OCR_Waybill(pic_str, client):\n req = models.WaybillOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n #params = '{\"ImageBase64\":\"pic_str\"}'\n req.from_json_string(params)\n resp = client.WaybillOCR(req)\n text = resp.to_json_string()\n return text\n\n#41:驾驶证识别\ndef Tencent_OCR_DriverLicense(pic_str, client):\n req = models.DriverLicenseOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n #params = '{\"ImageBase64\":\"pic_str\"}'\n req.from_json_string(params)\n resp = client.DriverLicenseOCR(req)\n text = resp.to_json_string()\n return text\n\n#42:车牌识别\ndef Tencent_OCR_LicensePlate(pic_str, client):\n req = models.LicensePlateOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n #params = '{\"ImageBase64\":\"pic_str\"}'\n req.from_json_string(params)\n resp = client.LicensePlateOCR(req)\n text = resp.to_json_string()\n return text\n\n#43:车辆VIN码识别\ndef Tencent_OCR_Vin(pic_str, client):\n req = models.VinOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n #params = '{\"ImageBase64\":\"pic_str\"}'\n req.from_json_string(params)\n resp = client.VinOCR(req)\n text = resp.to_json_string()\n return text\n\n#51:算式识别\ndef Tencent_OCR_Arithmetic(pic_str, client):\n req = models.ArithmeticOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n #params = '{\"ImageBase64\":\"pic_str\"}'\n req.from_json_string(params)\n resp = client.ArithmeticOCR(req)\n text = resp.to_json_string()\n return text\n\n#52:表格识别\ndef Tencent_OCR_Table(pic_str, client):\n req = models.TableOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n #params = '{\"ImageBase64\":\"pic_str\"}'\n req.from_json_string(params)\n resp = client.TableOCR(req)\n text = resp.to_json_string()\n return text\n\n\n\n#21:身份证识别\ndef Tencent_OCR_IDCard(pic_str, flag_side, flag_piccut, flag_porcut):\n cred = credential.Credential(\"Your ID\", \"Your Secret\")\n httpProfile = HttpProfile()\n httpProfile.endpoint = \"ocr.tencentcloudapi.com\"\n clientProfile = ClientProfile()\n clientProfile.httpProfile = httpProfile\n client = ocr_client.OcrClient(cred, \"ap-beijing\", clientProfile)\n\n req = models.IDCardOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n if flag_side:\n params_2 = r'\",\"CardSide\":\"BACK\",\"Config\":\"{\\\"CropIdCard\\\":'\n else:\n params_2 = r'\",\"CardSide\":\"FRONT\",\"Config\":\"{\\\"CropIdCard\\\":'\n if flag_piccut:\n params_3 = r'false,\\\"CropPortrait\\\":'\n else:\n params_3 = r'true,\\\"CropPortrait\\\":'\n if flag_porcut:\n params_4 = r'false}\"}'\n else:\n params_4 = r'true}\"}'\n params = params_1 + pic_str + params_2 + params_3 + params_4\n #params = '{\"ImageBase64\":\"pic_str\",\"CardSide\":\"FRONT\",\"Config\":\"{\\\\\"CropIdCard\\\\\":true,\\\\\"CropPortrait\\\\\":true}\"}'\n req.from_json_string(params)\n resp = client.IDCardOCR(req)\n text = resp.to_json_string()\n return text\n\n#24:名片识别\ndef Tencent_OCR_BusinessCard(pic_str, flag):\n cred = credential.Credential(\"Your ID\", \"Your Secret\")\n httpProfile = HttpProfile()\n httpProfile.endpoint = \"ocr.tencentcloudapi.com\"\n clientProfile = ClientProfile()\n clientProfile.httpProfile = httpProfile\n client = ocr_client.OcrClient(cred, \"ap-beijing\", clientProfile)\n\n req = models.BusinessCardOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n if flag:\n params_2 = r'\",\"Config\":\"{\\\"RetImageType\\\":\\\"PROPROCESS\\\"}\"}'\n else:\n params_2 = r'\"}'\n params = params_1 + pic_str + params_2\n #params = '{\"ImageBase64\":\"pic_str\",\"Config\":\"{\\\\\"RetImageType\\\\\":\\\\\"PROPROCESS\\\\\"}\"}'\n req.from_json_string(params)\n resp = client.BusinessCardOCR(req)\n text = resp.to_json_string()\n return text\n\n# 44:行驶证识别\ndef Tencent_OCR_VehicleLicense(pic_str, flag):\n cred = credential.Credential(\"Your ID\", \"Your Secret\")\n httpProfile = HttpProfile()\n httpProfile.endpoint = \"ocr.tencentcloudapi.com\"\n clientProfile = ClientProfile()\n clientProfile.httpProfile = httpProfile\n client = ocr_client.OcrClient(cred, \"ap-beijing\", clientProfile)\n\n req = models.VehicleLicenseOCRRequest()\n params_1 = r'{\"ImageBase64\":\"'\n if flag:\n params_2 = r'\",\"CardSide\":\"BACK\"}'\n else:\n params_2 = r'\",\"CardSide\":\"FRONT\"}'\n params = params_1 + pic_str + params_2\n # params = '{\"ImageBase64\":\"pic_str\",\"CardSide\":\"FRONT\"}'\n req.from_json_string(params)\n resp = client.VehicleLicenseOCR(req)\n text = resp.to_json_string()\n return text\n\n\n","repo_name":"GaryNotGay/OCR_TencentCloudAPI","sub_path":"Tencent_OCR.py","file_name":"Tencent_OCR.py","file_ext":"py","file_size_in_byte":11447,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"70864616096","text":"import getopt , sys\nimport importlib\nimport random\n\nmiscommunication_rate = 1\nnum_games = 300\nsteal_points = 5\ncooperate_points = 3\nfight_points = 1\n\ndef runSimulation(p1, p2):\n p1_choices = []\n p2_choices = []\n\n for i in range(0, num_games):\n p1_choice = p1.nextOutput();\n p2_choice = p2.nextOutput();\n\n if(random.randint(0,99) < miscommunication_rate):\n p1_choice = not p1_choice\n if(random.randint(0,99) < miscommunication_rate):\n p2_choice = not p2_choice\n\n p1_choices.append(p1_choice)\n p2_choices.append(p2_choice)\n\n if p1_choice and p2_choice:\n p1.addPoints(cooperate_points)\n p2.addPoints(cooperate_points)\n\n elif p1_choice and not p2_choice:\n p2.addPoints(steal_points)\n p1.addPoints(0)\n\n elif p2_choice and not p1_choice:\n p1.addPoints(steal_points)\n p2.addPoints(0)\n\n else:\n p1.addPoints(fight_points)\n p2.addPoints(fight_points)\n\n print(p1_choices)\n print(p2_choices)\n print(\"Simulation finished! P1: \" + str(p1.points)+ \" P2: \"+str(p2.points))\n\ndef main():\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"h\", [\"help\"])\n except getopt.GetoptError as err:\n print(err)\n sys.exit(2)\n print(\"Starting simulation!\")\n p1 = importlib.import_module(args[0].split('.')[0])\n p2 = importlib.import_module(args[1].split('.')[0])\n\n runSimulation(p1, p2);\n\n\n\nif __name__ =='__main__':\n main();\n \n","repo_name":"jcaip/game-theory","sub_path":"simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"70128228576","text":"import pygame\nimport DEFAULT\nfrom ground import Ground\nfrom math import sin, cos, sqrt\n\n\nclass Weapon(pygame.sprite.Sprite):\n def __init__(self, player_launcher, direction,damage,velocity,image1,image2):\n super().__init__()\n self.dmg = damage\n self.velocity = velocity\n # shuriken\n self.player_launcher = player_launcher\n self.direction = direction\n self.image = image1\n self.image = image2\n # position\n self.rect = self.image.get_rect()\n self.rect.x, self.rect.y = player_launcher.rect.x + self.player_launcher.direction * player_launcher.rect.width, player_launcher.rect.y + 3\n self.angle = self.player_launcher.aim_angle\n self.angle_rota = 1\n # velocité de départ\n self.y_v = (self.player_launcher.viseur_rect.y - self.player_launcher.rect.y)/9.8 * self.player_launcher.puissance/10\n self.x_v = (self.player_launcher.viseur_rect.x - self.player_launcher.rect.x)/9.8 * self.player_launcher.puissance/10\n # image pour la rotation\n self.origin_img = self.image\n # explosions\n self.image_explo = pygame.transform.scale(pygame.image.load(DEFAULT.image_explo), (60, 60))\n self.image_explo1 = pygame.transform.scale(pygame.image.load(DEFAULT.image_explo1), (60, 60))\n self.image_explo2 = pygame.transform.scale(pygame.image.load(DEFAULT.image_explo2), (60, 60))\n self.image_explo3 = pygame.transform.scale(pygame.image.load(DEFAULT.image_explo3), (60, 60))\n # trajectoire\n self.t_trajectory = 0\n # importation du background\n self.object_ground = Ground()\n\n def choose_weapon(self,id):\n if id == 1:\n self.damage=20\n self.velocity = 10\n self.image = pygame.image.load(DEFAULT.path_shuriken)\n self.image = pygame.transform.scale(self.image, (15, 15))\n\n def rotate(self):\n self.angle_rota += 7 * (self.x_v + self.y_v)\n self.image = pygame.transform.rotozoom(self.origin_img, self.angle_rota, 1)\n self.rect = self.image.get_rect(center=self.rect.center)\n\n def move(self, screen):\n collision = pygame.sprite.collide_mask(self.object_ground, self)\n # passé dans l'explosion\n collision_player = pygame.sprite.spritecollide(self, self.player_launcher.game.all_players, False,\n pygame.sprite.collide_mask)\n # si le projectile touche un objet\n if collision is not None:\n self.explosion(screen)\n self.kill()\n # si il touche le joueur\n elif len(collision_player) != 0:\n self.explosion(screen)\n self.kill()\n # verif limites de map\n elif self.rect.x > DEFAULT.window_width + 100 or self.rect.x < 0:\n self.kill()\n # sinon on fait la trajectoire\n else:\n self.rect.x += self.x_v\n # self.x_v /= 1.1\n self.rect.y += 9.8 * self.t_trajectory + self.y_v\n self.t_trajectory += 0.01\n self.rotate()\n\n def explosion(self, screen):\n \"\"\"permet de créer un rayon de dégâts autour de l'impact de projectile\"\"\"\n # faire l'animation\n screen.blit(self.image_explo, (self.rect.x, self.rect.y))\n screen.blit(self.image_explo1, (self.rect.x, self.rect.y))\n screen.blit(self.image_explo2, (self.rect.x, self.rect.y))\n screen.blit(self.image_explo3, (self.rect.x, self.rect.y))\n # aps opti car on le fait juste avant\n collision_player = pygame.sprite.spritecollide(self, self.player_launcher.game.all_players, False,\n pygame.sprite.collide_mask)\n for player in collision_player:\n player.take_damage(10)\n\n","repo_name":"maelaubert56/projet_transverse_L1_S2_GrpA2","sub_path":"weapon.py","file_name":"weapon.py","file_ext":"py","file_size_in_byte":3812,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"34689396038","text":"'''\nhttps://leetcode.com/problems/jewels-and-stones/\n\nJ는 보석, S는 소유한 돌, S에는 보석이 몇 개 있는지 찾아라, 대소문자 구분\n\n:param jewels: \"aA\"\n:param stones: \"aAAbbbb\"\n'''\nimport collections\n\ndef solution(jewels, stones):\n table = collections.defaultdict(int)\n for s in stones:\n table[s] += 1\n\n count = [num for stone, num in table.items()\n if stone in jewels]\n return sum(count)\n\n\ndef answer(jewels, stones):\n '''\n Counter를 사용해서 계산 생략\n 비교없이 jewels를 key로 사용해서 값 더하기\n '''\n table = collections.Counter(stones)\n count = 0\n\n for char in jewels:\n count += table[char]\n\ndef answer_line_1(J, S):\n '''\n sum()에 bool리스트를 넣으면 True 값의 개수를 구한다\n '''\n return sum(s in J for s in S)\n\n\nprint(solution(\"aA\", \"aAAbbbb\"))","repo_name":"devkjy00/TIL","sub_path":"Book/파이썬알고리즘인터뷰/11.해시테이블/보석과돌.py","file_name":"보석과돌.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"29317538751","text":"import boto3 \nfrom boto3 import client\nfrom os import environ\nimport asyncio\nimport json\n\n# Pardot Task prefix\ntasks_prefix = environ['PardotTaskPrefix']\n\n# Mapping of TaskGroups to Tasks to DataTypes\n# As of right now there is only one task group, but if some kind of postprocesing was required, this could handle it\n# with a new group \ntask_mapping = {\"TaskGroup1\":{\"tasks\":[\n {\"task\":\"PardotPull\", \n \"data_types\":[ \"visitoractivities\",\"campaigns\",\n \"lists\",\"prospects\",\"tagobjects\",\"tags\",\n \"opportunities\",\"prospectaccounts\",\"forms\",\n \"listmemberships\",\"visitors\"]}, \n {\"task\":\"PardotPullEmailStats\",\n \"data_types\":[\"emailstats\"]}]\n }\n }\n\n\nlambda_client = client('lambda')\n\ndef execute_tasks(task_dict, lambda_client):\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n loop.run_until_complete(execute_task_group_async(task_dict, lambda_client))\n return \n\nasync def execute_task_group_async(task_dict, client):\n '''\n Asynchronously executes task / data_type collection as a group\n Have to reformat the dictionary into a list to allow asyncio gather to work \n '''\n tasks = [[[task,data_type] for data_type in task_dict[task]] for task in task_dict.keys()][0]\n return await asyncio.gather(*[invoke_function(task[0], task[1],client) for task in tasks])\n\n\nasync def invoke_function(task, data_type, lambda_client):\n '''\n Invokes lambda function for all for a specific task, for a specific type of data\n '''\n payload = {'Metadata': {'DataType': data_type}}\n\n response = lambda_client.invoke(\n FunctionName=task,\n InvocationType='RequestResponse',\n Payload=json.dumps(payload))\n \n return response\n\n\ndef lambda_handler(event, context):\n \n print(f'Starting Pardot Batch pull')\n\n execute()\n\ndef execute():\n def PardotBatch():\n for taskgroup in task_mapping.keys():\n updated_dict = {}\n for tasks in task_mapping[taskgroup][\"tasks\"]:\n for task in tasks.keys():\n # Update the task name to match the lambda name (ie. pardot-us-east-2-prod.. might get added)\n updated_dict[f'{tasks_prefix}-{tasks[\"task\"]}'] = tasks['data_types']\n execute_tasks(updated_dict, lambda_client)\n\n PardotBatch()","repo_name":"skpadgett/PardotETL","sub_path":"functions/PardotBatch/PardotBatch.py","file_name":"PardotBatch.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"38256672374","text":"import keras.backend as K\nimport tensorflow as tf\nfrom emma.utils.registry import lossfunctions, lossfunction\nfrom emma.attacks.leakagemodels import LeakageModel\n\n\ndef get_loss(conf):\n if conf.loss_type in lossfunctions:\n f = lossfunctions[conf.loss_type]\n return f(conf)\n else:\n return conf.loss_type\n\n\n@lossfunction('correlation')\ndef _get_correlation_loss(conf):\n num_outputs = LeakageModel.get_num_outputs(conf)\n num_keys = conf.key_high - conf.key_low\n\n def correlation_loss(y_true_raw, y_pred_raw):\n \"\"\"\n Custom loss function that calculates the Pearson correlation of the prediction with\n the true values over a number of batches.\n \"\"\"\n if num_outputs > num_keys:\n y_true_raw = K.reshape(y_true_raw, (-1, num_keys))\n y_pred_raw = K.reshape(y_pred_raw, (-1, num_keys))\n\n # y_true_raw = K.print_tensor(y_true_raw, message='y_true_raw = ') # Note: print truncating is incorrect in the print_tensor function\n # y_pred_raw = K.print_tensor(y_pred_raw, message='y_pred_raw = ')\n y_true = (y_true_raw - K.mean(y_true_raw, axis=0, keepdims=True)) # We are taking correlation over columns, so normalize columns\n y_pred = (y_pred_raw - K.mean(y_pred_raw, axis=0, keepdims=True))\n\n loss = K.variable(0.0)\n for key_col in range(0, conf.key_high - conf.key_low): # 0 - 16\n y_key = K.expand_dims(y_true[:, key_col], axis=1) # [?, 16] -> [?, 1]\n y_keypred = K.expand_dims(y_pred[:, key_col], axis=1) # [?, 16] -> [?, 1]\n denom = K.sqrt(K.dot(K.transpose(y_keypred), y_keypred)) * K.sqrt(K.dot(K.transpose(y_key), y_key))\n denom = K.maximum(denom, K.epsilon())\n correlation = K.dot(K.transpose(y_key), y_keypred) / denom\n loss += 1.0 - correlation\n\n return loss\n\n return correlation_loss\n\n\n@lossfunction('correlation_special')\ndef _get_special_correlation_loss(conf):\n def correlation_loss(y_true_raw, y_pred_raw):\n \"\"\"\n Custom loss function that calculates the Pearson correlation of the prediction with\n the true values over a number of batches, with the addition of a weight parameter that\n is used to approximate the true key byte value.\n \"\"\"\n y_true = (y_true_raw - K.mean(y_true_raw, axis=0, keepdims=True)) # We are taking correlation over columns, so normalize columns\n y_pred = (y_pred_raw - K.mean(y_pred_raw, axis=0, keepdims=True))\n weight_index = conf.key_high - conf.key_low\n\n loss = K.variable(0.0)\n weight = K.mean(y_pred_raw[:, weight_index], axis=0)\n for key_col in range(0, conf.key_high - conf.key_low): # 0 - 16\n y_key = K.expand_dims(y_true[:, key_col], axis=1) # [?, 16] -> [?, 1]\n y_keypred = K.expand_dims(y_pred[:, key_col], axis=1) # [?, 16] -> [?, 1]\n denom = K.sqrt(K.dot(K.transpose(y_keypred), y_keypred)) * K.sqrt(K.dot(K.transpose(y_key), y_key))\n denom = K.maximum(denom, K.epsilon())\n correlation = K.dot(K.transpose(y_key), y_keypred) / denom\n loss += 1.0 - correlation\n\n alpha = 0.001\n exact_pwr = tf.multiply(weight, y_pred_raw[:, key_col])\n loss += alpha * K.sum(K.square(y_true_raw[:, key_col] - exact_pwr))\n\n return loss\n\n return correlation_loss\n\n\n@lossfunction('abs_distance')\ndef _get_abs_distance_loss(conf):\n return __get_distance_loss(conf, False)\n\n\n@lossfunction('squared_distance')\ndef _get_squared_distance_loss(conf):\n return __get_distance_loss(conf, True)\n\n\ndef __get_distance_loss(conf, squared):\n def distance_loss(y_true_raw, y_pred_raw):\n y_true = y_true_raw\n y_pred = y_pred_raw\n\n loss = K.variable(0.0)\n for key_col in range(0, conf.key_high - conf.key_low): # 0 - 16\n y_key = y_true[:, key_col] # [?, 16] -> [?,]\n y_keypred = y_pred[:, key_col] # [?, 16] -> [?,]\n if squared:\n loss += K.sum(K.square(y_key - y_keypred))\n else:\n loss += K.sum(K.abs(y_key - y_keypred))\n\n return loss\n\n return distance_loss\n\n\n@lossfunction('softmax_crossentropy')\ndef _get_crossentropy_loss(*_):\n def crossentropy_loss(y_true, y_pred):\n y_true = tf.stop_gradient(y_true)\n return tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_true, logits=y_pred)\n return crossentropy_loss\n","repo_name":"rpp0/emma","sub_path":"emma/ai/lossfunctions.py","file_name":"lossfunctions.py","file_ext":"py","file_size_in_byte":4463,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"33"} +{"seq_id":"38673358577","text":"# python3 -m pip install requests\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException\nimport time\n\nurl = 'http://peri.io/metrotown'\n# url = 'https://docs.google.com/forms/d/e/1FAIpQLSeB35vJidVD3GneKC7MO63NQYKTslhlqMvi8QheWKV7_A1R-Q/viewform?vc=0&c=0&w=1&flr=0'\n\nresponse = requests.get(url)\nhtml = response.text\nsoup = BeautifulSoup(html, 'html.parser')\n\n# Find all radio button elements on the page\nradio_buttons = soup.find_all('input', {'type': 'radio'})\n\n\n# response = requests.get(url)\n# html = response.text\n# soup = BeautifulSoup(html, 'html.parser')\ntarget_label = ['No', 'Take Out', 'Excellent', '10']\n# target_label = [ 'Take Out', 'Excellent', '10']\n\ndriver = webdriver.Chrome()\n\nvalue_list = []\nfor radio_button in radio_buttons:\n if radio_button.next_sibling.next_sibling.text.strip() in target_label:\n print(radio_button.next_sibling.next_sibling.text.strip() , \" : \", radio_button['value'])\n driver.get(url)\n radio_button_value = radio_button['value']\n value_list.append(radio_button_value)\n\ncount = 0\ntry:\n for radio_button_value in value_list:\n radio_button = driver.find_element(By.XPATH, f'//input[@type=\"radio\" and @value=\"{radio_button_value}\"]')\n radio_button.click()\nexcept NoSuchElementException:\n print(\"Text input nto found. Skipping...\")\n # driver.refresh()\n\n# Find text input field by IA. Fill in text.\ntry : \n text_input = driver.find_element(By.CLASS_NAME, 'textarea')\n text_input.send_keys(\"nando's chicken was so good it saved my failing marriage and cured my crippling depression\")\nexcept NoSuchElementException:\n print(\"Text input nto found. Skipping...\")\n\ntry:\n submit_button = driver.find_element(By.XPATH, '//button[@type=\"submit\"]')\n # submit_button.click()\nexcept NoSuchElementException:\n print(\"Text input nto found. Skipping...\")\n\n\nresponse = driver.page_source\nif \"Form submitted successfully!\" in response:\n print('Form submitted successfuly!')\nelse:\n print('Form submission failed. check for any unchecked boxes')\n\ntime.sleep(100)\ndriver.quit()\n","repo_name":"lla105/survey-script","sub_path":"nandos.py","file_name":"nandos.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"3573469236","text":"import abc\nimport logging\nimport os\n\nimport psycopg2\nfrom psycopg2.extensions import connection\nfrom pandas import DataFrame\n\nlogger = logging.getLogger()\n\n\nclass DatabaseHandler(metaclass=abc.ABCMeta):\n @classmethod\n def __subclasshook__(cls, subclass):\n return (hasattr(subclass, 'write_stations_statuses') and\n callable(subclass.write_stations_statuses) and\n hasattr(subclass, 'upsert_stations_inventory') and\n callable(subclass.upsert_stations_inventory) and\n hasattr(subclass, 'upsert_systems_inventory') and\n callable(subclass.upsert_systems_inventory) and\n hasattr(subclass, 'extract_hourly_aggregations') and\n callable(subclass.extract_hourly_aggregations) or\n NotImplemented)\n\n @classmethod\n @abc.abstractmethod\n def write_stations_statuses(cls, df: DataFrame) -> None:\n \"\"\"\n Load stations statuses to backend db\n \"\"\"\n raise NotImplementedError\n\n @classmethod\n @abc.abstractmethod\n def upsert_stations_inventory(cls, df: DataFrame, metadata: dict) -> None:\n \"\"\"\n Load stations inventory to backend db\n \"\"\"\n raise NotImplementedError\n\n @classmethod\n @abc.abstractmethod\n def upsert_systems_inventory(cls, metadata: dict) -> None:\n \"\"\"\n Load stations inventory to backend db\n \"\"\"\n raise NotImplementedError\n\n @classmethod\n @abc.abstractmethod\n def extract_hourly_aggregations(cls) -> DataFrame:\n \"\"\"\n Perform hourly aggregations using backend db capacities\n \"\"\"\n raise NotImplementedError\n\n\nclass PostgresHandler(DatabaseHandler):\n \"\"\"\n Handles backend storage and aggregations computing\n for PostgreSQL.\n \"\"\"\n cnx_params = {\n 'host': os.environ.get('DB_HOST'),\n 'port': str(os.environ.get('DB_PORT')),\n 'user': os.environ.get('DB_USER'),\n 'password': os.environ.get('DB_PASSWORD'),\n 'database': os.environ.get('DB_NAME')\n }\n\n @classmethod\n def create_pg_connection(cls) -> connection:\n \"\"\"\n TODO: docstring\n :return:\n \"\"\"\n cnx = psycopg2.connect(**cls.cnx_params)\n cnx.autocommit = True\n cur = cnx.cursor()\n cur.execute('SELECT version();')\n logger.debug('Postgres database version: %s', cur.fetchone()[0])\n return cnx\n\n @classmethod\n def write_stations_statuses(cls, df: DataFrame) -> None:\n sql = \"\"\"\n INSERT INTO stations.status_history(station_id, timestamp, bikes, free, ebikes, renting)\n VALUES (%s, %s, %s, %s, %s, %s)\n \"\"\"\n values = [\n (\n row['station_id'],\n row['timestamp'],\n row['bikes'],\n row['free'],\n row['ebikes'],\n row['renting']\n )\n for (index, row) in df.iterrows()\n ]\n cnx = cls.create_pg_connection()\n cursor = cnx.cursor()\n cursor.executemany(sql, values)\n cnx.close()\n\n @classmethod\n def upsert_stations_inventory(cls, df: DataFrame, metadata: dict) -> None:\n sql = \"\"\"\n INSERT INTO stations.inventory(\n id, system_name, name, latitude, longitude, payment,\n payment_terminal, has_ebikes, slots, last_updated\n ) \n VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n ON CONFLICT (id)\n DO UPDATE SET last_updated = EXCLUDED.last_updated, slots = EXCLUDED.slots;\n \"\"\"\n values = [\n (\n row['id'],\n metadata['name'],\n row['name'],\n row['latitude'],\n row['longitude'],\n row['payment'],\n row['payment_terminal'],\n row['has_ebikes'],\n row['slots'],\n row['last_updated']\n )\n for (index, row) in df.iterrows()\n ]\n cnx = cls.create_pg_connection()\n cursor = cnx.cursor()\n cursor.executemany(sql, values)\n cnx.close()\n\n @classmethod\n def upsert_systems_inventory(cls, metadata: dict) -> None:\n sql = \"\"\"\n INSERT INTO systems.inventory(\n system_name, city, country, latitude, longitude, \n company, license, ebikes, gbfs_href\n ) \n VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)\n ON CONFLICT (system_name)\n DO NOTHING;\n \"\"\"\n values = (\n metadata.get('name'),\n metadata.get('city'),\n metadata.get('country'),\n metadata.get('latitude'),\n metadata.get('longitude'),\n metadata.get('company'),\n metadata.get('license'),\n metadata.get('ebikes'),\n metadata.get('gbfs_href')\n )\n cnx = cls.create_pg_connection()\n cursor = cnx.cursor()\n cursor.execute(sql, values)\n cnx.close()\n\n @classmethod\n def extract_hourly_aggregations(cls) -> DataFrame:\n from pathlib import Path\n path = f'{str(Path(__file__).parent.resolve())}/sql/hourly_aggs.sql'\n with open(str(path), 'r') as f:\n sql = f.read()\n cnx = cls.create_pg_connection()\n cursor = cnx.cursor()\n cursor.execute(sql)\n cols = [col.name for col in cursor.description]\n rows = cursor.fetchall()\n cnx.close()\n return DataFrame(rows, columns=cols)\n","repo_name":"AlexandreVianova/micro-mobility-platform-vl","sub_path":"src/bikeshare_data_processor/database_handlers.py","file_name":"database_handlers.py","file_ext":"py","file_size_in_byte":5506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"8935454405","text":"\"\"\" Official evaluation script for v1.1 of the SQuAD dataset. \"\"\"\nfrom __future__ import print_function\n\nimport argparse\nimport json\n\nfrom jack.eval.extractive_qa_eval import *\n\n\ndef evaluate(dataset, predictions):\n f1 = exact_match = total = 0\n for article in dataset:\n for paragraph in article['paragraphs']:\n for qa in paragraph['qas']:\n total += 1\n if qa['id'] not in predictions:\n message = 'Unanswered question ' + qa['id'] + \\\n ' will receive score 0.'\n print(message, file=sys.stderr)\n continue\n ground_truths = list(map(lambda x: x['text'], qa['answers']))\n prediction = predictions[qa['id']]\n exact_match += metric_max_over_ground_truths(\n exact_match_score, prediction, ground_truths)\n f1 += metric_max_over_ground_truths(\n f1_score, prediction, ground_truths)\n\n exact_match = 100.0 * exact_match / total\n f1 = 100.0 * f1 / total\n\n return {'exact_match': exact_match, 'f1': f1}\n\n\nif __name__ == '__main__':\n expected_version = '1.1'\n parser = argparse.ArgumentParser(\n description='Evaluation for SQuAD ' + expected_version)\n parser.add_argument('dataset_file', help='Dataset file')\n parser.add_argument('prediction_file', help='Prediction File')\n args = parser.parse_args()\n with open(args.dataset_file) as dataset_file:\n dataset_json = json.load(dataset_file)\n if (dataset_json['version'] != expected_version):\n print('Evaluation expects v-' + expected_version +\n ', but got dataset with v-' + dataset_json['version'],\n file=sys.stderr)\n dataset = dataset_json['data']\n with open(args.prediction_file) as prediction_file:\n predictions = json.load(prediction_file)\n print(json.dumps(evaluate(dataset, predictions)))\n","repo_name":"uclnlp/jack","sub_path":"bin/squad_evaluate-v1.1.py","file_name":"squad_evaluate-v1.1.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","stars":254,"dataset":"github-code","pt":"33"} +{"seq_id":"42773074775","text":"from itertools import cycle\nfrom typing import Sequence\n\nfrom PyQt5.QtCore import pyqtSignal, QTimer\nfrom PyQt5.QtWidgets import QLineEdit\n\n\nclass TitleWidget(QLineEdit):\n \"\"\" Title bar widget that displays plaintext as well as simple text animations. \"\"\"\n\n submitted = pyqtSignal([str]) # Emitted with the widget's current text when Enter is pressed.\n\n def __init__(self, *args) -> None:\n super().__init__(*args)\n self._anim_timer = QTimer(self) # Animation timer for loading messages.\n self.returnPressed.connect(self._on_submit_text)\n\n def _on_submit_text(self) -> None:\n \"\"\" Emit the widget text as a signal. \"\"\"\n text = self.text()\n self.submitted.emit(text)\n\n def setText(self, text:str) -> None:\n \"\"\" Stop any animation and show normal text in the title bar. \"\"\"\n self._anim_timer.stop()\n super().setText(text)\n\n def setAnimatedText(self, text_items:Sequence[str], delay_ms:int) -> None:\n \"\"\" Set the widget text to animate over on a timed cycle.\n The first item is shown immediately, then a new one is shown every milliseconds. \"\"\"\n if text_items:\n show_next_item = map(super().setText, cycle(text_items)).__next__\n show_next_item()\n self._anim_timer.timeout.connect(show_next_item)\n self._anim_timer.start(delay_ms)\n","repo_name":"fourshade/spectra_lexer","sub_path":"spectra_lexer/qt/title.py","file_name":"title.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"33"} +{"seq_id":"15831578659","text":"import pandas as pd\nimport json\n\ndf = pd.read_excel(\"/home/vadim/K/hack/dataset/cte.xlsx\")\ndf[\"label\"] = df[\"Код КПГЗ\"].astype(str).apply(lambda x: x.split('.')[0] + \".\" + x.split('.')[1] if len(x.split('.')) != 1 else x.split('.')[0])\n\nwith open('codes.txt', 'r') as file:\n lines = file.readlines()\n\nlines = [l.strip() for l in lines if l.startswith(' ') and l[12] != ' ']\n\ncodes = {}\nfor l in lines:\n codes[l[:5]] = l[7:]\n\ndecoding = {}\nm = {}\nfor i, u in enumerate(df[\"label\"].unique()):\n m[u] = i \n if u == \"nan\":\n decoding[i] = None\n else:\n decoding[i] = codes[u]\n\nprint(list(df[\"label\"].values).count('nan'))\ndf[\"label\"] = df[\"label\"].map(m)\n\ndf[[\"Название СТЕ\", \"label\"]].to_csv(\"/home/vadim/K/hack/dataset/train_bert.csv\")\nprint(df[\"label\"].nunique())\nprint(dict(df[\"label\"].value_counts()))\n\nwith open('codes.json', 'w') as file:\n json.dump(decoding, file)","repo_name":"BurykinaA/TenderHack","sub_path":"bert/generate_labels.py","file_name":"generate_labels.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"33"} +{"seq_id":"43254431446","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Oct 12 22:40:32 2021\r\n@author : Nikhil J\r\n@github : ML-Nikhil\r\n\r\nProblem Statement : Applying DecisionTree Algorithm on \"titanic\" dataset, for \r\nSurvived and enlist the conclusion\r\n\"\"\"\r\n# Import Libraries\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport statistics as ss\r\nimport matplotlib.pyplot as plt\r\ndf = pd.read_csv('titanic.csv')\r\ndf.describe(include='all')\r\ndf.info()\r\ndf.index\r\n# Categorcal Variables : pclass, embarked, sex, survived\r\n# Quantitative Variables : age, fare, sibsp, parch but age and fare are in object\r\n# Alphanumeric Variables : Names, Ticket\r\n\r\n# 1. AGE : dtype object : has some ? values : it should be in float/int which is not\r\n# change the datatype and replace ? values as NaN\r\ndf['age'] = pd.to_numeric(df['age'], errors = 'coerce')\r\nprint('The NaN Values in Age before imputation',df['age'].isna().sum())\r\ndf.isna().sum()\r\ndf['age'].fillna(df['age'].mean(),inplace=True)\r\ndf['age'].plot.hist(alpha = 0.5,edgecolor = 'black', title = 'mean ='+ str(ss.mean(df['age'])))\r\n\r\n# 2. FARE\r\ndf.head(10)\r\n# fare also has ? values and datatype is object. \r\n# replacing ? by NaN and object datatype as float\r\ndf['fare']=pd.to_numeric(df['fare'],errors='coerce')\r\ndf['fare'].isna().sum()\r\ndf.dropna(subset = ['fare'],inplace =True)\r\ndf['fare'].plot.hist(alpha = 0.5,edgecolor = 'black')\r\n\r\n# Categorical Variables\r\n\r\n# 1. Sex - Male and Female\r\nsns.countplot(x=\"sex\",hue=\"survived\",data=df)\r\ns_dummy = pd.get_dummies(df['sex'],drop_first=True)\r\n\r\n# 2. pclass\r\nsns.countplot(x=\"pclass\",hue=\"survived\",data=df)\r\np_dummy = pd.get_dummies(df['pclass'],drop_first=True)\r\n\r\n# 3. Embarked : has some ? value replace it by mode\r\nprint('The common class in embarked :',ss.mode(df['embarked']))\r\n# replacing the ? value by S\r\ndf['embarked']=df['embarked'].replace(({'?': 'S'}))\r\nsns.countplot(x=\"embarked\",hue=\"survived\",data=df)\r\nemb_dummy = pd.get_dummies(df['embarked'],drop_first=True)\r\n\r\n\r\n# Concatenating dataset\r\n\r\ndf = pd.concat([df,s_dummy,p_dummy,emb_dummy],axis =1)\r\n\r\ndf.drop(['Passenger_id','pclass','name','ticket','embarked','sex'],axis =1,inplace=True,)\r\n\r\n# Splitting Data\r\nx = df.drop('survived',axis =1)\r\ny = df['survived']\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nx_train, x_test, y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=0)\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nRF_classifier = RandomForestClassifier(n_estimators=10,criterion='entropy',max_depth=4,min_samples_leaf=5)\r\nRF_classifier.fit(x_train,y_train)\r\n\r\nRF_classifier.feature_importances_\r\n\r\n# Important features :Male,Fare,pclass2,parch,sibsp,age,embarked\r\n\r\n# Selecting feature for tree\r\nx1 = x.iloc[:,[0,1,3,4,6,8]]\r\ny1 = y\r\n\r\nx1_train, x1_test, y1_train,y1_test = train_test_split(x1,y1,test_size=0.2,random_state=0)\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import confusion_matrix\r\nDCT_classifier=DecisionTreeClassifier(criterion='entropy',max_depth =3,min_samples_leaf=5)\r\nDCT_classifier.fit(x1_train,y1_train)\r\ny1_pred = DCT_classifier.predict(x1_test)\r\nconfusion_matrix(y1_test,y1_pred)\r\nprint('The accuracy score',round(accuracy_score(y1_test,y1_pred)*100,2))\r\nfrom sklearn import tree\r\ntree.plot_tree(DCT_classifier)\r\n#___Tree Plot__\r\nfig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (4,4), dpi=300)\r\ncn=['0','1']\r\ntree.plot_tree(DCT_classifier,class_names=cn,filled = True)\r\n\r\n#Graphiz Store the GRAPH where the directory is set\r\nfrom sklearn.tree import export_graphviz\r\ndot_data = tree.export_graphviz(DCT_classifier,feature_names=['age','sibsp','fare','male','p-class3','S'] ,class_names=['0','1'],filled=True)\r\nimport graphviz\r\ngraph = graphviz.Source(dot_data)\r\ngraph.format = \"png\"\r\ngraph.render(\"DecisionTree_Titanic\")\r\n#_\r\n# Conclusion : Max Depth :3\r\n# Female : Pclass 1,2 :fare less or euqal to $31.68 : Survived\r\n# Female : Pclass 3 :fare less or equal to $23.35 : Survived\r\n# Male : Age less or equal to 13.5 : sibsp less or 2: Survives\r\n# Male : Age more than 13.5 : fare less than 26 : No Survival\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"ML-Nikhil/AssignmentSE","sub_path":"assignment_DCT_titanic.py","file_name":"assignment_DCT_titanic.py","file_ext":"py","file_size_in_byte":4140,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"5184628695","text":"from common.methods import set_progress\r\nimport json\r\nfrom onefuse.cloudbolt_admin import CbOneFuseManager, Utilities\r\nfrom utilities.logger import ThreadLogger\r\nfrom jobs.models import Job\r\n\r\nlogger = ThreadLogger(__name__)\r\n\r\n\r\ndef run(job, *args, **kwargs):\r\n resource = job.resource_set.first()\r\n if resource:\r\n utilities = Utilities(logger)\r\n set_progress(f\"This plug-in is running for resource {resource}\")\r\n utilities.verbose_logging(f\"Dictionary of keyword args passed to this \"\r\n f\"plug-in: {kwargs.items()}\")\r\n endpoint_policy = resource.get_cfv_for_custom_field(\r\n \"OneFuse_Deployment_NamingPolicy\")\r\n if endpoint_policy: \r\n endpoint_policy = endpoint_policy.value_as_string\r\n onefuse_endpoint = endpoint_policy.split(':')[0]\r\n naming_policy_name = endpoint_policy.split(':')[1]\r\n set_progress(f\"Starting OneFuse Deployment Naming Policy: \"\r\n f\"{naming_policy_name}, Endpoint: {onefuse_endpoint}\")\r\n try: \r\n tracking_id = resource.OneFuse_Tracking_Id\r\n except: \r\n tracking_id = \"\"\r\n from xui.onefuse.globals import VERIFY_CERTS\r\n ofm = CbOneFuseManager(onefuse_endpoint, VERIFY_CERTS,\r\n logger=logger)\r\n name_json = ofm.provision_naming(naming_policy_name,resource, \r\n tracking_id) \r\n deployment_name = name_json.get(\"name\")\r\n resource.name = deployment_name\r\n utilities.check_or_create_cf(\"OneFuse_Naming_Deployment\")\r\n name_json[\"endpoint\"] = onefuse_endpoint\r\n resource.OneFuse_Naming_Deployment = json.dumps(name_json)\r\n resource.OneFuse_Tracking_Id = name_json.get(\"trackingId\")\r\n resource.save()\r\n set_progress(f\"Resource name being set to: {resource.name}\")\r\n return \"SUCCESS\", deployment_name, \"\"\r\n else: \r\n set_progress(f\"OneFuse_Deployment_NamingPolicy parameter is not set \"\r\n f\"on the resource, OneFuse deployment naming will not \"\r\n f\"be executed. Keeping existing hostname\")\r\n else: \r\n set_progress(\"Resource was not found\")\r\n","repo_name":"abudruk/github-actions-demo-project","sub_path":"CMP/ui-extension-packages/OneFuse/samples/resource_naming/provision_naming_resource.py","file_name":"provision_naming_resource.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"72082608734","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\nimport os\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\nreq = requests.get('https://www.fmkorea.com/?vid=&mid=best&category=&listStyle=webzine&search_keyword=%EB%A6%AC%EB%B2%84%ED%92%80&search_target=title_content')\n\nhtml = req.text\n\nsoup = BeautifulSoup(html, 'html.parser')\n\n\nmy_titles = soup.select(\n 'ul > li > div > h3 > a'\n )\n\ndata = {}\n\nfor title in my_titles:\n data[title.text] = title.get('href')\n \nwith open(os.path.join(BASE_DIR, 'result.json'), 'w+', encoding='utf-8') as json_file:\n json.dump(data, json_file,ensure_ascii=False)\n","repo_name":"akaster99/crawlers","sub_path":"parserVer1.py","file_name":"parserVer1.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"18829330972","text":"from ..utils import extract_subarray, translate_dq, dq_summary\n\nimport os\nimport numpy as np\nimport pytest\nfrom astropy.io import fits\nfrom jwst.saturation import SaturationStep\nfrom jwst import datamodels\n\n\n@pytest.fixture(scope='module')\ndef fits_output(fits_input):\n fname = fits_input[0].header['filename'].replace('.fits',\n '_saturationstep.fits')\n yield fits.open(fname)\n os.remove(fname)\n\n@pytest.fixture(scope='module')\ndef fits_saturation(fits_output):\n ref_path = fits_output['PRIMARY'].header['R_SATURA']\n ref_path = ref_path.replace('crds://', '/grp/crds/cache/references/jwst/')\n return fits.open(ref_path)\n\ndef test_saturation_step(fits_input):\n \"\"\"Make sure the DQInitStep runs without error.\"\"\"\n fname = fits_input[0].header['filename'].replace('.fits',\n '_saturationstep.fits')\n SaturationStep.call(datamodels.open(fits_input), output_file=fname,\n save_results=True)\n\ndef test_groupdq_flagging(fits_output, fits_saturation):\n\n satmask = extract_subarray(fits_saturation['SCI'].data, fits_output)\n dqmask = translate_dq(fits_saturation)\n dqmask = extract_subarray(dqmask, fits_output)\n # flag pixels greater than saturation threshold\n no_sat_check = (dqmask & (1 << 21)).astype(bool)\n not_nan = ~np.isnan(satmask)\n expected_groupdq = np.zeros_like(fits_output['GROUPDQ'].data)\n flagged = (fits_output['SCI'].data >= satmask) & ~no_sat_check[np.newaxis, np.newaxis, :, :] & not_nan[np.newaxis, np.newaxis, :, :]\n expected_groupdq[flagged] = 2\n\n # make sure that pixels in groups after a flagged pixel are also flagged\n flagged = np.cumsum(expected_groupdq == 2, axis=1) > 0\n expected_groupdq[flagged] = 2\n\n assert np.all(fits_output['GROUPDQ'].data == expected_groupdq)\n\ndef test_pixeldq_propagation(fits_input, fits_output, fits_saturation):\n\n # translate dq flags to standard bits\n pixeldq = translate_dq(fits_saturation)\n # extract subarray\n pixeldq = extract_subarray(pixeldq, fits_input)\n\n print('For step input')\n dq_summary(fits_input['PIXELDQ'].data)\n print('For reference file')\n dq_summary(pixeldq)\n print('For step output')\n dq_summary(fits_output['PIXELDQ'].data)\n assert np.all(fits_output['PIXELDQ'].data == np.bitwise_or(fits_input['PIXELDQ'].data, pixeldq))\n","repo_name":"spacetelescope/calibration-pipeline-testing-tool","sub_path":"caltest/test_caldetector1/test_saturation.py","file_name":"test_saturation.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"73027587614","text":"\"\"\"\nThe program was written in python3 (If you are using python2, you need to change\nquery = input.split() to query = raw_input.split())\n\nThe methods in myDB is case-insensitive\n\nThe program handles several invalid input cases, and it just do not execute\nthese queries\n\nYou hust need run this script or run solution function.\n\"\"\"\n# Time: O(1) for simple set, get, unset, numequalto method\n# Space: O(n)\n# For transaction, we only consider set and unset methods (because only set \n# and unset methods changes the data in the database)\n# For every set or unset query in a transaction, we store an inversed query in a stack\n# When rollback is called, we executed the inversed query\n# When commit is called, we just clean the stack\n\nclass MyDB():\n #lookup is for unset, set, get methods and count is for numequalto method\n def __init__(self):\n self.lookup = {}\n self.count = {}\n\n def set(self, name, value):\n self.unset(name)\n self.lookup[name] = value\n if value not in self.count:\n self.count[value] = 0\n self.count[value] += 1\n\n def get(self, name):\n if name in self.lookup:\n return self.lookup[name]\n return None\n\n def unset(self, name):\n if name in self.lookup:\n oldValue = self.lookup[name]\n self.count[oldValue] -= 1\n if not self.count[oldValue]:\n self.count.pop(oldValue)\n self.lookup.pop(name)\n\n def numequalto(self, value):\n if value in self.count:\n return self.count[value]\n return 0\n\n#ExecuteQuery function handles the query set, unset, get and numequalto query\ndef executeQuery(db, query):\n if query[0] == \"set\":\n db.set(query[1], query[2])\n elif query[0] == \"get\":\n return db.get(query[1])\n elif query[0] == \"unset\":\n db.unset(query[1])\n return db.numequalto(query[1])\n\n#Judge if the input query is valid (according to the problem, it is an optional function)\ndef isValid(query):\n if query[0] == \"set\":\n if len(query) < 3:\n return False\n return True\n elif query[0] == \"unset\":\n if len(query) < 2:\n return False\n return True\n elif query[0] == \"get\":\n if len(query) < 2:\n return False\n return True\n elif query[0] == \"numequalto\":\n if len(query) < 2:\n return False\n return True\n return False\n\n#Execute queries, main about dealing with the transcation queries \ndef solution():\n db = MyDB()\n#stack for transaction command\n#flag to record if current command is in a transaction\n stack, flag = [], False\n while True:\n query = input().split()\n if not query:\n print(\"invaild input!\")\n continue\n #Only the query is case-insentive, not the name and value.\n query[0] = query[0].lower()\n if query[0] == \"end\":\n break\n elif query[0] == \"begin\":\n stack.append(\"stop\")\n flag = True\n elif query[0] == \"rollback\":\n if not stack:\n print(\"NO TRANSACTION\")\n else:\n #Execute inversed query\n cur = stack.pop()\n while cur != \"stop\":\n executeQuery(db, cur)\n cur = stack.pop()\n if not stack:\n flag = False\n elif query[0] == \"commit\":\n stack, flag = [], False\n elif isValid(query):\n #Store inversed query\n if flag and query[0] in (\"set\", \"unset\"):\n newQuery = [\"get\", query[1]]\n oldValue = executeQuery(db, newQuery)\n if oldValue is None:\n stack.append([\"unset\", query[1]])\n else:\n stack.append([\"set\", query[1], oldValue])\n #Execute query\n res = executeQuery(db, query)\n if query[0] == \"get\":\n if res is None:\n print(\"NULL\")\n else:\n print(res)\n elif query[0] == \"numequalto\":\n print(res)\n else:\n print(\"invalid input!\")\n \nif __name__ == \"__main__\":\n solution()\n","repo_name":"zjuzpz/Algorithms","sub_path":"others/In-memory DB.py","file_name":"In-memory DB.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"33"} +{"seq_id":"72888742494","text":"import re\nfrom math import floor\nfrom copy import deepcopy\n\n\nclass bf:\n\n\t# The length of a list will always be in range [1,256].\n\tdef __init__(self, *args, **kwargs):\n\t\t# super(bf, self).__init__(*args, **kwargs)\n\t\tself.data = {}\n\t\tself.proc_cmd = []\n\n\tdef cmd_prsr(self, cmdstr):\n\t\tcmd = []\n\t\tfor var in re.findall(r'[^\\s]+', cmdstr):\n\t\t\tcmd.append(var)\n\t\t# return cmd\n\t\t# Make upper vars\n\t\tcmd = [cmd[0]] + [c.upper() for c in cmd[1:]]\n\t\tcmd[0] = cmd[0].lower()\n\t\t# print(cmd)\n\n\t\t# Increase tolerance of array declaration. x [ 10 ] -> x[10]\n\t\tremlist = []\n\t\tfor i, s in enumerate(cmd):\n\t\t\t# print(cmd)\n\t\t\tif re.match(r'\\[[0-9]\\]', s) is not None:\n\n\t\t\t\tcmd[i-1] = cmd[i-1] + s\n\t\t\t\tcmd.pop(i)\n\n\t\t\telif re.match(r'\\[$', s) is not None:\n\n\t\t\t\tend = [re.match(r'\\]', s) is not None for s in cmd].index(True)\n\t\t\t\tcmd[i-1] = ''.join(cmd[i-1:end+1])\n\t\t\t\tfor j in range(i, end+1):\n\t\t\t\t\tremlist.append(cmd[j])\n\n\t\tfor r in remlist:\n\t\t\tcmd.remove(r)\n\t\tprint(cmd)\n\t\tprint(self.proc_cmd)\n\n\t\tif sum([1 if c in ['ifeq', 'ifneq', 'wneq', 'proc'] else 0 for c in self.proc_cmd]) != sum([1 if c == 'end' else 0 for c in self.proc_cmd]):\n\n\t\t\tself.proc_cmd.extend(cmd)\n\n\t\telif self.proc_cmd == []:\n\n\t\t\tif cmd[0] == 'var':\n\t\t\t\tself.var(cmd[1:])\n\t\t\telif cmd[0] == 'set':\n\t\t\t\tself.set(cmd[1], cmd[2])\n\t\t\telif cmd[0] == 'inc':\n\t\t\t\tself.inc(cmd[1], cmd[2])\n\t\t\telif cmd[0] == 'dec':\n\t\t\t\tself.dec(cmd[1], cmd[2])\n\t\t\telif cmd[0] == 'add':\n\t\t\t\tself.add(cmd[1], cmd[2], cmd[3])\n\t\t\telif cmd[0] == 'sub':\n\t\t\t\tself.sub(cmd[1], cmd[2], cmd[3])\n\t\t\telif cmd[0] == 'mul':\n\t\t\t\tself.mul(cmd[1], cmd[2], cmd[3])\n\t\t\telif cmd[0] == 'divmod':\n\t\t\t\tself.divmod(cmd[1], cmd[2], cmd[3], cmd[4])\n\t\t\telif cmd[0] == 'div':\n\t\t\t\tself.div(cmd[1], cmd[2], cmd[3])\n\t\t\telif cmd[0] == 'mod':\n\t\t\t\tself.mod(cmd[1], cmd[2], cmd[3])\n\t\t\telif cmd[0] == 'cmp':\n\t\t\t\tself.cmp(cmd[1], cmd[2], cmd[3])\n\t\t\telif cmd[0] == 'msg':\n\t\t\t\tself.msg(*cmd[1:])\n\t\t\telif cmd[0] == 'read':\n\t\t\t\tself.read(cmd[1])\n\t\t\telif cmd[0] == 'b2a':\n\t\t\t\tself.b2a(cmd[1], cmd[2], cmd[3], cmd[4])\n\t\t\telif cmd[0] == 'a2b':\n\t\t\t\tself.a2b(cmd[1], cmd[2], cmd[3], cmd[4])\n\t\t\telif cmd[0] == 'lset':\n\t\t\t\tself.lset(cmd[1], cmd[2], cmd[3])\n\t\t\telif cmd[0] == 'lget':\n\t\t\t\tself.lget(cmd[1], cmd[2], cmd[3])\n\t\t\telif cmd[0] in ['ifeq', 'ifneq', 'wneq', 'proc']:\n\t\t\t\tself.proc_cmd.extend(cmd)\n\t\t# impliceitly filled and completed\n\t\telse:\n\n\t\t\tif cmd[0] == 'ifeq':\n\t\t\t\tself.ifeq(cmd[1], cmd[2], cmd[3:])\n\t\t\tif cmd[0] == 'ifneq':\n\t\t\t\tself.ifneq(cmd[1], cmd[2], cmd[3:])\n\n\n\n\t\t\tself.proc_cmd.clear()\n\n\t# consider making it *args\n\t# set limit to 256\n\tdef var(self, args):\n\t\tarray_detector = [re.match(r'[A-z]\\[[0-9]+\\]', i) is not None for i in args]\n\t\t# spaced_array_detector = [re.match(r'\\[[0-9]+\\]', i) is not None for i in args]\n\n\t\t# print(args)\n\t\t# print(\"array declared\\t{}\\narray spaced\\t{}\".format(array_detector, spaced_array_detector))\n\n\t\tfor i, arg in enumerate(args):\n\t\t\tif array_detector[i]:\n\t\t\t\t# if array_detector[i]:\n\t\t\t\tself.data[arg[0]] = [0 for i in range(int(re.findall(r'[0-9]+', arg)[0]))]\n\t\t\t\t# else:\n\t\t\t\t# \tself.data[args[i-1]] = [0 for i in range(int(re.findall(r'[0-9]+', arg)[0]))]\n\t\t\telse:\n\t\t\t\tself.data[arg] = 0\n\n\tdef prsr(self, val):\n\t\t# char to int; 'X' -> 88\n\t\tif re.match(r'\\'[A-z]\\'', val):\n\t\t\treturn ord(val[1])\n\t\t# variable\n\t\telif re.match(r'[A-z]', val):\n\t\t\treturn self.data[val]\n\t\t# val\n\t\telif re.match(r'-[0-9]+|[0-9]+', val):\n\t\t\treturn int(val) % 256\n\n\tdef set(self, reg, val):\n\t\tself.data[reg] = self.prsr(val)\n\n\tdef inc(self, reg, val):\n\t\tself.data[reg] += self.prsr(val)\n\n\tdef dec(self, reg, val):\n\t\tself.data[reg] -= self.prsr(val)\n\n\tdef add(self, val1, val2, reg):\n\t\tself.data[reg] = self.prsr(val1) + self.prsr(val2)\n\n\tdef sub(self, val1, val2, reg):\n\t\tself.data[reg] = self.prsr(val1) - self.prsr(val2)\n\n\tdef mul(self, val1, val2, reg):\n\t\tself.data[reg] = self.prsr(val1) * self.prsr(val2)\n\n\t# Divisor will not be 0\n\tdef divmod(self, val1, val2, reg1, reg2):\n\t\ta = self.prsr(val1)\n\t\tb = self.prsr(val2)\n\t\tself.data[reg1] = floor(a / b)\n\t\tself.data[reg2] = a % b\n\n\tdef div(self, val1, val2, reg):\n\t\tself.data[reg] = floor(self.prsr(val1) / self.prsr(val2))\n\n\tdef mod(self, val1, val2, reg):\n\t\tself.data[reg] = self.prsr(val1) % self.prsr(val2)\n\n\tdef cmp(self, val1, val2, reg):\n\t\t# If a < b store -1(255) charo c.\n\t\t# If a == b store 0 charo c.\n\t\t# If a > b store 1 charo c.\n\t\ta = self.prsr(val1)\n\t\tb = self.prsr(val2)\n\n\t\tif a < b:\n\t\t\tself.data[reg] = 255\n\t\telif a == b:\n\t\t\tself.data[reg] = 0\n\t\telif a > b:\n\t\t\tself.data[reg] = 1\n\n\t# ascii digits should be turned charo their assvi values or their char values?\n\tdef a2b(self, val1, val2, val3, reg):\n\t\ta = self.prsr(val1)\n\t\tb = self.prsr(val2)\n\t\tc = self.prsr(val3)\n\t\tself.data[reg] = 100*(a-48) + 10*(b-48) + (c-48)\n\n\tdef b2a(self, val, reg1, reg2, reg3):\n\t\ta = self.prsr(val)\n\t\tself.data[reg1] = 48 + floor(a / 100)\n\t\tself.data[reg2] = 48 + floor(a / 10 % 10)\n\t\tself.data[reg3] = 48 + (a % 10)\n\n\t# IndexError will not be evaluated\n\tdef lset(self, reg, i, val):\n\t\tself.data[reg][self.prsr(i)] = self.prsr(val)\n\n\tdef lget(self, arr, i, reg):\n\t\tself.data[reg] = self.data[arr][self.prsr(i)]\n\n\tdef msg(self, *args):\n\t\tlst = [str(self.data[arg]) if arg in self.data.keys() else arg for arg in args]\n\t\tprint(''.join(lst))\n\n\tdef read(self, val):\n\t\tprint(self.prsr(val))\n\n\tdef ifeq(self, val1, val2, body):\n\t\tif self.prsr(val1) == self.prsr(val2):\n\t\t\tprint(body)\n\n\tdef ifneq(self, val1, val2, body):\n\t\tif self.prsr(val1) != self.prsr(val2):\n\t\t\tprint(body)\n\n\ndef kcuf(code):\n\tb = bf()\n\tfor line in re.findall(r'[^\\n]+', code):\n\n\t\tprint(line)\n\t\tb.cmd_prsr(line)\n\t\tprint(b.data)\n\t\tprint(\"-------\")\n\n\n# make case insensitive\n\n\n# kcuf(\"\"\"\n# var F L[5] X\n# set F 0\n# add 10 10 X\n# wneq F 5\n# \tlset L F X\n# \tinc F 1\n# \tdec X 1\n# end\n# //L == [20,19,18,17,16]\n\n# wneq F 0\n# \tinc F -1\n# \tlget L F X\n# \tmsg X\n# end\n\n# set F 10\n# wneq F 0\n# \tifeq F 10\n# \t\tset F 5\n# \tend\n# \tdec F 1\n# \tlget L F X\n# \tifneq X 18\n# \t\tmsg F X\n# \tend\n# end\n# ifeq F 0\n# \tifneq X 50\n# \t\tmsg \";-)\"\n# \tend\n# end\n# \"\"\")\n\nkcuf(\"\"\"\nifeq 0 0\n\tmsg 'X'\nend\n\n\"\"\")","repo_name":"EdvinAlvarado/Code-Wars","sub_path":"ToBrainfuck-Transpiler.py","file_name":"ToBrainfuck-Transpiler.py","file_ext":"py","file_size_in_byte":5992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"28621253775","text":"import sys \ninput = sys.stdin.readline\n\nN = int(input())\npeople = [list(map(int,input().split())) for _ in range(N)]\nvisited = [False for _ in range(N)]\nINF = 2147000000\nmin_ = INF\n\ndef divide_team(depth,idx):\n global min_\n # N명이 있을 때 팀은 N//2 명으로 구성되기 때문에 depth == N//2 일 때 가지치기 시작\n if depth == N//2:\n start,link =0, 0\n for i in range(N):\n for j in range(N):\n if visited[i] and visited[j]:\n start += people[i][j]\n elif not visited[i] and not visited[j]:\n link += people[i][j]\n min_ = min(min_, abs(start-link))\n return\n for i in range(idx, N):\n if not visited[i] :\n visited[i] = True\n divide_team(depth+1,i+1)\n visited[i] = False\n\ndivide_team(0,0)\nprint(min_)","repo_name":"sukkkuuuu/Alogorithm","sub_path":"backtracking/No.14889.py","file_name":"No.14889.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"4551026090","text":"# 边缘保留滤波 EPF\nimport cv2 as cv\nimport numpy as np\n\n# 边缘保留滤波,高斯磨皮\ndef bi_demo(image):\n dst = cv.bilateralFilter(image, 0, 100, 15)\n cv.imshow(\"bi_demo\",dst)\n\n# 均值迁移\ndef shift_demo(image):\n dst = cv.pyrMeanShiftFiltering(image, 10, 20)\n cv.imshow(\"shift_demo\", dst)\n\nsrc = cv.imread(\"F:\\\\C++\\\\test\\\\3432.png\") # 地址\ncv.namedWindow(\"input image\", cv.WINDOW_AUTOSIZE) # 窗口设置名称,自由尺寸\ncv.imshow(\"input image\",src) # 打开图片\nt1 = cv.getTickCount()\nbi_demo(src)\nshift_demo(src)\nt2 = cv.getTickCount()\nprint((t2 - t1)/cv.getTickFrequency() * 1000)\ncv.waitKey(3000)","repo_name":"baisupicshow/Python","sub_path":"opencv/example8.py","file_name":"example8.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"19407460309","text":"from rl_games.common import object_factory\nimport rl_games.algos_torch\nfrom rl_games.algos_torch import network_builder\nfrom rl_games.algos_torch import models\n\nNETWORK_REGISTRY = {}\nMODEL_REGISTRY = {}\n\ndef register_network(name, target_class):\n NETWORK_REGISTRY[name] = lambda **kwargs: target_class()\n\ndef register_model(name, target_class):\n MODEL_REGISTRY[name] = lambda network, **kwargs: target_class(network)\n\n\nclass NetworkBuilder:\n def __init__(self):\n self.network_factory = object_factory.ObjectFactory()\n self.network_factory.set_builders(NETWORK_REGISTRY)\n self.network_factory.register_builder('actor_critic', lambda **kwargs: network_builder.A2CBuilder())\n self.network_factory.register_builder('resnet_actor_critic',\n lambda **kwargs: network_builder.A2CResnetBuilder())\n self.network_factory.register_builder('rnd_curiosity', lambda **kwargs: network_builder.RNDCuriosityBuilder())\n self.network_factory.register_builder('soft_actor_critic', lambda **kwargs: network_builder.SACBuilder())\n\n def load(self, params):\n network_name = params['name']\n network = self.network_factory.create(network_name)\n network.load(params)\n\n return network\n\n\nclass ModelBuilder:\n def __init__(self):\n self.model_factory = object_factory.ObjectFactory()\n self.model_factory.set_builders(MODEL_REGISTRY)\n self.model_factory.register_builder('discrete_a2c', lambda network, **kwargs: models.ModelA2C(network))\n self.model_factory.register_builder('multi_discrete_a2c',\n lambda network, **kwargs: models.ModelA2CMultiDiscrete(network))\n self.model_factory.register_builder('continuous_a2c',\n lambda network, **kwargs: models.ModelA2CContinuous(network))\n self.model_factory.register_builder('continuous_a2c_logstd',\n lambda network, **kwargs: models.ModelA2CContinuousLogStd(network))\n self.model_factory.register_builder('soft_actor_critic',\n lambda network, **kwargs: models.ModelSACContinuous(network))\n self.model_factory.register_builder('central_value',\n lambda network, **kwargs: models.ModelCentralValue(network))\n self.network_builder = NetworkBuilder()\n\n def get_network_builder(self):\n return self.network_builder\n\n def load(self, params):\n model_name = params['model']['name']\n network = self.network_builder.load(params['network'])\n model = self.model_factory.create(model_name, network=network)\n return model\n","repo_name":"Denys88/rl_games","sub_path":"rl_games/algos_torch/model_builder.py","file_name":"model_builder.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","stars":585,"dataset":"github-code","pt":"33"} +{"seq_id":"18842579228","text":"\"\"\"\r\ncomputes normalized Shannon entropy and a statistical complexity measure called\r\nMPR. Implementation is based on the article \"Cancer Biomarker Discovery\"\r\nby Beretta / Moscato in Plosone* (see section Materials and Methods) and\r\nRosso, Craig, Moscato: \"Shakespeare and other English Renaissance authors\" in\r\nPhysica A 388 (2009) 916-926.\r\nThe use of the complexity measure based on jensen shannon divergence is proposed\r\nby Martin, Plastino, Russo, therefore the name ComplMPR\r\nBeware: the numbers given in the Plosone paper for the jsd are wrong, because the\r\nauthors used the natural log to compute the results instead of the log2, which is\r\nused in the formula in the paper.\r\n\r\ntodo:\r\n - still cannot replicate the complexity measure for the gene expression files\r\n (see plosone article). Check with Hugh whether Pave is calculated correctly\r\n (jsd should work fine)\r\n - fix bug with using the file with the wordcounts; getting different results\r\n_____\r\n*http://www.plosone.org/article/info:doi/10.1371/journal.pone.0012262\r\n\r\nAuthor: Fotis Jannidis.\r\nAll errors introduced by me when adapting this are of course my fault (#cf)\r\n\r\n\"\"\"\r\n\r\nimport glob\r\nimport os\r\nimport math\r\nimport pandas as pd\r\nimport datetime\r\nimport re\r\nfrom collections import Counter\r\nimport csv\r\n\r\n##########################################################################\r\n# configuration\r\n##########################################################################\r\n#where to find the corpus\r\nsubdir = \"txt\"\r\n\r\n#number of words to use from the wordlist\r\n#set to 0 to use all\r\nmfwords = 5000\r\n\r\n#use existing wordlist\r\nuse_wordlist = False\r\n\r\n#switch to extract only a sample\r\nset_limit = True\r\n\r\n#sample size\r\nlimit = 20000\r\n\r\n#all words in lower case?\r\nlower_case = True\r\n\r\n#name of the file where the complete wordlist is saved\r\ncorpuswords = \"data_corpuswords.csv\"\r\n\r\n#use filenames as labels in plot\r\nfilenames_labels = True\r\n\r\n#use groups to color output and in legend (alternative to filename labels)\r\n#groups = True\r\n\r\n#label size\r\n#label_size = 8\r\n\r\n#heading of the plotted diagram\r\n#heading = \"Complexity and Entropy in German novels around 1890\"\r\n\r\n#save results to file results.csv\r\nsave_results = True\r\n\r\n#debug\r\ndebug = False\r\n\r\n#defines word boundaries for the tokenization\r\n#yes, this could be done more sophisticated using nltk\r\n#and no, you don't want to install nltk 3.0alpha with python 3 ;-)\r\npattern = re.compile(\"\\W\")\r\n\r\n##########################################################################\r\n# functions\r\n##########################################################################\r\ndef process_files(encoding=\"utf-8\"):\r\n \"\"\"\r\n preprocessing all files ending with *.txt in corpus subdir\r\n all files are tokenized\r\n a table of all word and their freq in all texts is created\r\n \"\"\"\r\n filelist = glob.glob(subdir + os.sep + \"*.txt\")\r\n corpus_words = pd.DataFrame()\r\n for file in filelist:\r\n df = tokenize_file(file,encoding)\r\n corpus_words = pd.concat([corpus_words,df],axis=1)\r\n return corpus_words\r\n\r\n\r\ndef tokenize_file (filename,encoding):\r\n \"\"\"\r\n tokenizes file and returns an unordered pandas.DataFrame\r\n containing the words and frequencies\r\n standard encoding = utf-8\r\n \"\"\"\r\n all_words = {}\r\n\r\n #read file, tokenize it, count words\r\n read_text_length = 0\r\n with open (filename,\"r\",encoding=encoding) as filein: #encoding=\"utf-8\"\r\n print (\"processing \" + os.path.basename(filename))\r\n for line in filein:\r\n if set_limit == True:\r\n if read_text_length > limit:\r\n break\r\n else:\r\n read_text_length += len(line)\r\n words = regex_tokenizer (line)\r\n for w in words:\r\n if lower_case == True:\r\n w = w.lower()\r\n if w not in all_words.keys():\r\n all_words[w] = 1\r\n else:\r\n all_words[w] += 1\r\n filename = os.path.basename(filename)\r\n return pd.DataFrame(pd.Series(all_words),columns=[filename])\r\n\r\n\r\ndef regex_tokenizer (line):\r\n \"\"\"\r\n regex based tokenizer using unicode based whitespace\r\n information\r\n the pattern is defined above to avoid repeated compilation\r\n \"\"\"\r\n words = pattern.split(line)\r\n while \"\" in words:\r\n words.remove(\"\")\r\n return words\r\n\r\n\r\ndef save_file(corpus_words):\r\n \"\"\"\r\n saves wordlists to file\r\n using global var save_file\r\n \"\"\"\r\n print (\"Saving wordlist to file \" + corpuswords)\r\n corpus_words.to_csv(corpuswords, encoding=\"utf-8\",na_rep=0,quoting=csv.QUOTE_NONNUMERIC)\r\n\r\n\r\ndef read_corpus():\r\n \"\"\"\r\n reads wordlist from file\r\n \"\"\"\r\n return pd.read_csv(corpuswords,encoding=\"utf-8\",index_col=0)\r\n\r\n\r\ndef preprocess_mfw_table (corpus):\r\n \"\"\"\r\n sorts the table containing the frequency lists\r\n by the sum of all word freq\r\n returns the corpus list shortened to the most frequent words\r\n number defined by mfwords\r\n \"\"\"\r\n nr = []\r\n #cols = corpus.columns\r\n for i in corpus.index:\r\n nr += [corpus.loc[i].sum()]\r\n su = pd.Series(nr,index=corpus.index,name=\"sum\")\r\n\r\n\r\n corpus = corpus.fillna(0) \r\n corpus = corpus.loc[corpus.sum(axis=1).sort_values(inplace=False, ascending=False).index] \r\n #print(corpus)\r\n \r\n #slice only mfwords from total list\r\n if mfwords != 0:\r\n corpus = corpus[:mfwords]\r\n return corpus #\r\n\r\ndef JSDvsEntropy (corpus_words):\r\n entropies = [] #stores the entropies of all texts\r\n jsds = [] #stores all distance measures\r\n #compute Pave, the average probablity distribution, which is used\r\n #as reference in the jcd for each text\r\n\r\n Pave = p_ave(corpus_words)\r\n\r\n for text in corpus_words.columns:\r\n text_words = corpus_words[text]\r\n p_text_words = prob (text_words)\r\n #compute for all texts the normalized Shannon entropy (step a)\r\n entropy = normalized_entropy(p_text_words)\r\n entropies += [entropy]\r\n #compute the jsd from a texts to Pave (step b i)\r\n\r\n jsd_res = jsd(p_text_words,Pave)\r\n jsds += [jsd_res]\r\n if debug==True:\r\n print (text + \": jsd: \" + str(jsd_res) + \" nse: \" + str(entropy) + \" -- \" + text)\r\n entropies = pd.Series(entropies,name=\"entropy\",index=corpus_words.columns)\r\n #print(entropies)\r\n jsds = pd.Series(jsds,name=\"jsd\",index=corpus_words.columns) \r\n results = pd.concat([jsds,entropies],axis=1)\r\n results.reset_index(level=0, inplace=True)\r\n results.rename(columns={\"index\": \"idno\"}, inplace=True)\r\n results.replace(\".txt\", \"\", regex=True, inplace=True)\r\n print(results)\r\n return results\r\n\r\n\r\n\r\n\r\n#reads in all files and tokenizes them and creates a wordfreq. list in a dataframe\r\ndef ComplMPR (corpus_words):\r\n \"\"\"\r\n it consists of the product of:\r\n a) the normalized Shannon entropy\r\n b) and a disequilibrium, a fixed reference state, which is computed as the product of\r\n i) the Jensen-Shannon divergence and\r\n ii) a normalization constant equal to the inverse of maximum possible values\r\n of jsd\r\n this function assumes that the complete wordlist DataFrame has been already\r\n truncated to the smaller set you want to actually use for the computation\r\n therefore corpus_words.index contains all words to be computed on\r\n returns a list with the normalized entropies and a list with the complexity measures\r\n \"\"\"\r\n# jsd_all = [] #stores all jcd for debugging\r\n entropies = [] #stores the entropies of all texts\r\n complMPR = [] #stores all complexity measures\r\n jsd_res = 0\r\n\r\n #calculate the normalization constant (step b ii)\r\n N = len(corpus_words.index)\r\n Q_0 = q_0(N)\r\n if debug==True:\r\n print(\"N: \" + str(N) + \"\\nQ_0: \" + str(Q_0) )\r\n\r\n for text in corpus_words.columns:\r\n text_words = corpus_words[text]\r\n p_text_words = prob (text_words)\r\n #compute for all texts the normalized Shannon entropy (step a)\r\n entropy = normalized_entropy(p_text_words)\r\n entropies += [entropy]\r\n #compute the jsd from a text to Pe\r\n jsd_res = jsd(p_text_words,p_eq(p_text_words))\r\n\r\n complMPR += [Q_0 * jsd_res * entropy]\r\n if debug==True:\r\n print (text + \": jsd: \" + str(jsd_res) + \" nse: \" + str(entropy) + \" -- \" + text)\r\n entropies = pd.Series(entropies,name=\"entropy\",index=corpus_words.columns)\r\n complMPR = pd.Series(complMPR,name=\"complexity\",index=corpus_words.columns)\r\n return pd.concat([entropies,complMPR],axis=1)\r\n\r\n#reads in all files and tokenizes them and creates a wordfreq. list in a dataframe\r\ndef ComplM (corpus_words):\r\n \"\"\"\r\n it consists of the product of:\r\n a) the normalized Shannon entropy\r\n b) and the Jensen-Shannon divergence of one text to the average (Pave)\r\n\r\n this function assumes that the complete wordlist DataFrame has been already\r\n truncated to the smaller set you want to actually use for the computation\r\n therefore corpus_words.index contains all words to be computed on\r\n returns a list with the normalized entropies and a list with the complexity measures\r\n \"\"\"\r\n# jsd_all = [] #stores all jcd for debugging\r\n entropies = [] #stores the entropies of all texts\r\n complM = [] #stores all complexity measures\r\n jsd_res = 0\r\n\r\n\r\n #compute Pave, the average probablity distribution, which is used\r\n #as reference in the jcd for each text\r\n Pave = p_ave(corpus_words)\r\n\r\n for text in corpus_words.columns:\r\n text_words = corpus_words[text]\r\n p_text_words = prob (text_words)\r\n #compute for all texts the normalized Shannon entropy (step a)\r\n entropy = normalized_entropy(p_text_words)\r\n entropies += [entropy]\r\n #compute the jsd from a texts to Pave (step b i)\r\n\r\n jsd_res = jsd(p_text_words,Pave)\r\n\r\n complM += [jsd_res * entropy]\r\n if debug==True:\r\n print (text + \": jsd: \" + str(jsd_res) + \" nse: \" + str(entropy) + \" -- \" + text)\r\n entropies = pd.Series(entropies,name=\"entropy\",index=corpus_words.columns)\r\n complM = pd.Series(complM,name=\"complexity\",index=corpus_words.columns)\r\n return pd.concat([entropies,complM],axis=1)\r\n\r\n\r\n#computes jensen-shannon divergence for 2 lists in form of pandas.Series\r\n#return one value\r\ndef jsd (p_1,p_2):\r\n \"\"\"\r\n computes the Jensen Shannon divergence between two lists of values\r\n see Regina Berretta1,2, Pablo Moscato: Cancer Biomarker Discovery:\r\n The Entropic Hallmark. Plos One August 18, 2010, for details on the formula.\r\n The values in this text don't match my results using the jsd and also\r\n not 2 other implementations of the jsd (mystery solved: the formula in the\r\n paper uses log2 to compute entropy while the results of the paper are\r\n really computed using the natural log.\r\n >>> jsd(prob(pd.Series([2,2,2,2,2])),prob(pd.Series([2,2,2,2,2])))\r\n 0.0\r\n >>> jsd(prob(pd.Series([2,2,2,2,2])),prob(pd.Series([5,2,5,1,3])))\r\n 0.035851483945529505\r\n >>> jsd(prob(pd.Series([4,3,2,1,0.1])),prob(pd.Series([2,2,2,2,2])))\r\n 0.082684827683680462\r\n >>> jsd(prob(pd.Series([4,3,2,1,0.1])),prob(pd.Series([5,2,5,1,3])))\r\n 0.077848851295847954\r\n \"\"\"\r\n J1 = entropy ((p_1 + p_2) / 2)\r\n J2 = (entropy(p_1) + entropy(p_2)) / 2\r\n if debug == True:\r\n print (\"J1: \" + str(J1) + \" J2: \" + str(J2))\r\n JS = J1 - J2\r\n if debug == True:\r\n print (\"jsd: \" + str(JS))\r\n return JS\r\n\r\n\r\ndef prob (values):\r\n \"\"\"\r\n computes probabilites by dividing all values through the sum of all values.\r\n returns a pandas.Series containing the probablities\r\n Usage:\r\n >>> prob(pd.Series([1,2,3]))\r\n 0 0.166667\r\n 1 0.333333\r\n 2 0.500000\r\n dtype: float64\r\n \"\"\"\r\n if not isinstance(values,pd.core.series.Series):\r\n values = pd.Series(values)\r\n return (values / values.sum())\r\n\r\ndef p_eq(series):\r\n \"\"\"\r\n Computes the equilibrium\r\n >>> p_eq(pd.Series([3,2,1,3,2,1]))\r\n\r\n \"\"\"\r\n l = len (series)\r\n return pd.Series([1/l]*l,index=series.index)\r\n\r\ndef p_ave (df):\r\n \"\"\"\r\n Computes p ave, that is the average probability for each word over all texts\r\n #df = {\"one\" : pd.Series([3,5],index=['a','b']), \"two\": pd.Series([1,4],index=['a','c']),\"three\": pd.Series([7,2],index=['b','c'])}\r\n >>> df = pd.concat([pd.Series([3,5],index=['a','b'],name=\"one\"),pd.Series([1,4],index=['a','c'],name=\"two\"),pd.Series([7,2],index=['b','c'],name=\"three\")],axis=1)\r\n >>> p_ave(df)\r\n a 0.181818\r\n b 0.545455\r\n c 0.272727\r\n dtype: float64\r\n \"\"\"\r\n\r\n df = df.fillna(0)\r\n p = []\r\n for row in df.index:\r\n p += [(df.loc[row].sum() / df.loc[row].count())]\r\n p_ave = pd.Series(p,index=df.index)\r\n #get the ratio = probabilities\r\n p_ave = prob(p_ave)\r\n return p_ave\r\n\r\n\r\n\r\ndef entropy (values):\r\n \"\"\"\r\n computes the Shannon entropy\r\n S(E) = minus sum of (p(i) * log(p(i)))\r\n where p is the probability of the event x\r\n so first one has to compute the probability of the events\r\n and then feed this list to entropy\r\n >>> entropy(prob(pd.Series([2,2,2,2])))\r\n 1.3862943611198906\r\n >>> entropy(prob(pd.Series([1,2,3,4])))\r\n 1.2798542258336676\r\n \"\"\"\r\n #apply it to all values\r\n values = values.apply(help_se)\r\n return - values.sum()\r\n\r\n\r\ndef help_se (value):\r\n \"\"\"\r\n small function to calculate the basis value for Shannon Entropy\r\n maybe it is better to switch to math.log2 here?\r\n and actually this is the reason the results published in thr paper by\r\n Regina Berretta1,2, Pablo Moscato are wrong\r\n \"\"\"\r\n if value == 0:\r\n return 0\r\n else:\r\n return value * math.log(value)\r\n\r\n\r\n#unused function, useful for debugging the entropy func\r\n#see http://rosettacode.org/wiki/Entropy#Python\r\ndef entropy_S(s):\r\n \"\"\"\r\n computes entropy on a string\r\n >>> entropy_S(\"1223334444\")\r\n 1.8464393446710154\r\n >>> entropy_S(\"11223344\")\r\n 2.0\r\n\r\n \"\"\"\r\n p, lns = Counter(s), float(len(s))\r\n return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\r\n\r\n\r\ndef normalized_entropy (values):\r\n \"\"\"calculates Normalized Shannon Entropy\r\n assumes values are not raw values but already probabilities\r\n >>> normalized_entropy(prob([5,2,5,1,3]))\r\n 0.9158830010682758\r\n >>> normalized_entropy(prob([2,2,2,2,2]))\r\n 1.0000000000000002\r\n >>> normalized_entropy(prob([4,3,2,1,0.1]))\r\n 0.8218574117493731\r\n \"\"\"\r\n\r\n if not isinstance(values,pd.core.series.Series):\r\n values = pd.Series(values)\r\n\r\n #apply it to all values\r\n values = values.apply(help_se)\r\n #do the rest of the formula\r\n result = - values.sum() / math.log(values.count())\r\n return result\r\n\r\n\r\n#helper function to compute Q_0, the normalization constant which is only\r\n#dependent on N\r\n#formula not given in the Plosone paper but in the Physica A\r\n\r\ndef q_0 (N):\r\n \"\"\"\r\n >>> q_0(10)\r\n 1.9025971948407798\r\n \"\"\"\r\n if N != 0:\r\n q = -2 * (( ((N + 1) / N ) * math.log (N+1)) - 2 * math.log(2*N) + math.log(N))**-1\r\n else:\r\n print (\"Warning: N: 0 --doesn't make sense\")\r\n q = 1\r\n return q\r\n\r\ndef testme():\r\n groupnames = {}\r\n with open (subdir + os.sep + \"groups.csv\",\"r\",encoding=\"utf-8\") as filein:\r\n for line in filein:\r\n (text,group) = line.split(\"\\t\")\r\n groupnames[text] = group\r\n for i in groupnames.keys():\r\n print (i + \" : \" + groupnames[i])\r\n\r\n\r\ndef file_name (filename):\r\n \"\"\"\r\n small helper function to get rid of the extension\r\n and shorten the name and the the title\r\n \"\"\"\r\n tf = []\r\n ntitle = \"\"\r\n (author,title) = filename.split(\"_\")\r\n if \",-\" in author:\r\n (author,firstname) = author.split(\",-\")\r\n if \".txt\" in title:\r\n title = title[:-4]\r\n if \" \" in title:\r\n tf = title.split(\" \")\r\n for w in tf:\r\n if w not in [\"Der\",\"Das\",\"Die\",\"Ein\",\"Eine\",\"Und\"]:\r\n ntitle += w\r\n title = ntitle\r\n break\r\n return author + \"_\" + title\r\n\r\ndef date_time():\r\n dt = datetime.datetime.now()\r\n return dt.strftime(\"%Y-%m-%d_%H-%M-%S\")\r\n\r\n##########################################################################\r\n# main\r\n##########################################################################\r\n\r\ndef main():\r\n if use_wordlist == False:\r\n corpus = process_files(encoding=\"utf-8\")\r\n save_file(corpus)\r\n else:\r\n corpus = read_corpus()\r\n corpus = preprocess_mfw_table(corpus)\r\n results = JSDvsEntropy(corpus)\r\n if save_results == True:\r\n results.to_csv(\"entropy_results.csv\")\r\n #plot2(results,\"jsdentr\")\r\n\r\nmain()\r\n\r\n","repo_name":"cligs/toolbox","sub_path":"analyse/complexity_entropy.py","file_name":"complexity_entropy.py","file_ext":"py","file_size_in_byte":16847,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"33"} +{"seq_id":"6534623926","text":"import os, sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport statsmodels as sm\nimport requests\nimport json\nimport plotly.express as px\nimport dash\nimport pickle\n\n\nfrom dash import dcc\nfrom dash import html\nfrom dash.dependencies import Input, Output\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split,cross_val_score\nfrom sklearn.preprocessing import StandardScaler,PolynomialFeatures\nfrom sklearn.metrics import r2_score\nfrom sklearn.linear_model import LassoCV,RidgeCV\nfrom sklearn.metrics import confusion_matrix\nfrom collections import ChainMap\n\n\nfrom scipy import stats\nimport statsmodels.api as sm\n\ndf=pd.read_csv('GHG_Data_2010_2019_data_Dec172020.csv')\n\nCity=df['Facility City'].unique()\n\nwith open (\"Municipal_Boundary_-_Lower_and_Single_Tier.geojson\",'r') as geo_file:\n obj_Ontario=json.load(geo_file)\n\ncity_id_map_New={}\nfor feature in obj_Ontario['features']:\n feature['id']=feature['properties']['MUNID']\n city_id_map_New[feature['properties']['MUNICIPAL_NAME_SHORTFORM']]=feature['id']\n # feature['geometry']['coordinates'][0]=feature['geometry']['coordinates'][0][::-1]\n\ndf['Facility City_upper']=df['Facility City'].str.upper()\n\ndf.dropna(subset=['Facility City_upper'],inplace=True)\n\nnot_available=[]\nfor item in City:\n item=str(item).upper()\n if item not in list(city_id_map_New.keys()):\n not_available.append(item)\n\ndf_revised_plus=df[~df['Facility City_upper'].isin (not_available)]\n\ndf_revised_plus['id']=df_revised_plus['Facility City_upper'].apply(lambda x:city_id_map_New[x])\n\n# df_revised_plus['log_Reporting Amount in CO2e (t)']=np.log10(df_revised_plus['Reporting Amount in CO2e (t)'])\n\n# NEW_Agg_MAP={}\n# list_year=[]\n# for year in df_revised_plus['Year']:\n# for CITY in df_revised_plus['Facility City_upper']:\n# NEW_Agg_MAP[f\"{CITY}-{year}\"]=df_revised_plus[(df_revised_plus['Year']==year) & (df_revised_plus['Facility City_upper']==CITY)]['Reporting Amount in CO2e (t)'].sum()\n\na_file = open(\"NEW_Agg_MAP.pkl\", \"rb\")\nNEW_Agg_MAP = pickle.load(a_file)\n\nsum_final=list(NEW_Agg_MAP.values())\n\nyear=[]\ncities=[]\nfor item in list(NEW_Agg_MAP.keys()):\n year.append(item.split(\"-\")[1])\n cities.append(item.split(\"-\")[0])\n\nyear = list(map(int, year))\nw=[]\nagg_df=pd.DataFrame(w)\n\nagg_df['Year']=year\nagg_df['CITY']=cities\nagg_df['SUM_CO2']=sum_final\nagg_df['LOG_SUM_CO2']=np.log10(agg_df['SUM_CO2'])\n\nagg_df['id']=agg_df['CITY'].apply(lambda x:city_id_map_New[x])\n\nnot_available_plus=[]\nfor item in list(city_id_map_New.keys()) :\n if item not in agg_df['CITY'].unique():\n not_available_plus.append(item)\n\nwrong_geojson=['QUINTE WEST', 'FRONTENAC ISLANDS', 'CENTRE WELLINGTON',\n'RAMARA', 'MACHIN', 'CHATHAM-KENT', 'SOUTH BRUCE PENINSULA','GREENSTONE',\n 'THE NORTH SHORE', 'THE ARCHIPELAGO', 'BRANT', 'ASSIGINACK', 'TAY', 'TINY',\n 'TYENDINAGA', 'RYERSON', 'STRATHROY-CARADOC', 'TEMAGAMI', 'AMHERSTBURG',\n 'LAMBTON SHORES', 'TUDOR AND CASHEL']\n\nnot_available_plus=[item for item in not_available_plus if item not in wrong_geojson]\n\n\nCITY_column=[]\nYear=[]\nSUM_CO2=[]\nLOG_SUM_CO2=[]\nfor item in agg_df['Year'].unique():\n for CITY in not_available_plus:\n # for CITY in ['CARLING',\n # 'WAINFLEET',\n # 'CLARENCE-ROCKLAND',\n # 'JOHNSON',\n # 'MALAHIDE',\n # 'BRETHOUR',\n # 'BRACEBRIDGE',\n # 'BRIGHTON',\n # 'HAVELOCK-BELMONT-METHUEN',\n # 'SOUTH RIVER',\n # 'POINT EDWARD',\n # 'GEORGIAN BLUFFS',\n # 'MANITOUWADGE',\n # 'BILLINGS',\n # 'BLACK RIVER-MATHESON',\n # 'OPASATIKA',\n # 'CONMEE',\n # 'CENTRAL ELGIN',\n # 'HORNEPAYNE',\n # 'THAMES CENTRE',\n # 'ELLIOT LAKE',\n # 'DEEP RIVER',\n # 'HEAD, CLARA AND MARIA',\n # 'NORTH ALGONA WILBERFORCE',\n # 'PERRY',\n # 'WHITCHURCH-STOUFFVILLE',\n # 'OWEN SOUND',\n # 'COLEMAN',\n # 'TRENT LAKES',\n # 'MATTAWAN',\n # 'BROCK',\n # 'SIOUX NARROWS-NESTOR FALLS',\n # 'EAST HAWKESBURY',\n # 'LAKE OF BAYS',\n # 'LARDER LAKE',\n # 'HORTON',\n # 'CHISHOLM',\n # 'BROCKTON',\n # 'PRINCE',\n # 'JOLY',\n # 'GEORGIAN BAY',\n # 'SOUTH STORMONT',\n # 'PLUMMER ADDITIONAL',\n # 'THORNLOE',\n # 'LEEDS AND THE THOUSAND ISLANDS',\n # 'NIPISSING',\n # 'UXBRIDGE',\n # 'OTONABEE-SOUTH MONAGHAN',\n # 'ALBERTON',\n # 'BURPEE AND MILLS',\n # 'JOCELYN',\n # 'DUTTON/DUNWICH',\n # 'GORDON / BARRIE ISLAND',\n # 'KAWARTHA LAKES',\n # 'ATHENS',\n # 'KINCARDINE',\n # 'MCKELLAR',\n # 'CENTRE HASTINGS',\n # 'TEMISKAMING SHORES',\n # 'SOUTH FRONTENAC',\n # 'GRAVENHURST',\n # 'RED ROCK',\n # 'TAY VALLEY',\n # 'MERRICKVILLE-WOLFORD',\n # 'ADDINGTON HIGHLANDS',\n # 'GANANOQUE',\n # 'WARWICK',\n # 'NORWICH',\n # 'PETROLIA',\n # 'SABLES-SPANISH RIVERS',\n # 'LAIRD',\n # 'ORILLIA',\n # 'BRADFORD WEST GWILLIMBURY',\n # 'MORLEY',\n # 'NORFOLK COUNTY',\n # 'BARRIE',\n # 'MEAFORD',\n # 'RAINY RIVER',\n # 'LA VALLEE',\n # 'LAURENTIAN HILLS',\n # 'WEST ELGIN',\n # 'LOYALIST',\n # 'CHATSWORTH',\n # 'MCDOUGALL',\n # 'WASAGA BEACH',\n # 'CHAMPLAIN',\n # 'HARRIS',\n # 'NORTH FRONTENAC',\n # 'KING',\n # 'ST. CLAIR',\n # 'NORTH KAWARTHA',\n # 'MCNAB/BRAESIDE',\n # 'BONFIELD',\n # 'ORO-MEDONTE',\n # 'KILLARNEY',\n # 'ST. JOSEPH',\n # 'BECKWITH',\n # 'HIGHLANDS EAST',\n # 'CHAPPLE',\n # 'MCGARRY',\n # 'SOUTH GLENGARRY',\n # 'BRUDENELL, LYNDOCH AND RAGLAN',\n # 'MIDLAND',\n # 'ST.-CHARLES',\n # 'CRAMAHE',\n # 'LAURENTIAN VALLEY',\n # 'MUSKOKA LAKES',\n # 'ARNPRIOR',\n # 'SOUTHWOLD',\n # 'ARRAN-ELDERSLIE',\n # 'SOUTHGATE',\n # 'BANCROFT',\n # 'MACDONALD, MEREDITH AND ABERDEEN ADDITIONAL',\n # 'MELANCTHON',\n # \"BURK'S FALLS\",\n # 'CLARINGTON',\n # 'NEWBURY',\n # 'GEORGINA',\n # 'SOUTH HURON',\n # 'DYSART, DUDLEY, HARCOURT, GUILFORD, HARBURN, BRUTO',\n # 'HUDSON',\n # 'AJAX',\n # 'STRONG',\n # 'CENTRAL FRONTENAC',\n # 'NORTHERN BRUCE PENINSULA',\n # 'NORTHEASTERN MANITOULIN AND THE ISLANDS',\n # 'GILLIES',\n # 'NORTH DUMFRIES',\n # 'TWEED',\n # 'SOUTHWEST MIDDLESEX',\n # 'DESERONTO',\n # 'MONO',\n # 'WELLINGTON NORTH',\n # 'AUGUSTA',\n # 'MISSISSIPPI MILLS',\n # 'LUCAN BIDDULPH',\n # 'BRUCE MINES',\n # 'JAMES',\n # 'MAPLETON',\n # 'HASTINGS HIGHLANDS',\n # 'CASEY',\n # 'MACHAR',\n # 'OIL SPRINGS',\n # 'MARATHON',\n # 'SHUNIAH',\n # 'SEVERN',\n # 'CALVIN',\n # 'FAUQUIER-STRICKLAND',\n # 'INNISFIL',\n # 'WHITEWATER REGION',\n # 'CAVAN MONAGHAN',\n # 'ENNISKILLEN',\n # 'BALDWIN',\n # 'LASALLE',\n # 'STIRLING-RAWDON',\n # 'SOUTH ALGONQUIN',\n # 'WILMOT',\n # 'MULMUR',\n # 'NEW TECUMSETH',\n # 'HURON SHORES',\n # 'BAYHAM',\n # 'CENTRAL MANITOULIN',\n # 'PELHAM',\n # 'DOURO-DUMMER',\n # 'FRENCH RIVER',\n # 'HILTON BEACH',\n # 'ALFRED AND PLANTAGENET',\n # 'RENFREW',\n # 'ADJALA-TOSORONTIO',\n # 'PARRY SOUND',\n # 'PERTH',\n # 'MATTICE-VAL CÔTÉ',\n # 'NEEBING',\n # 'ALNWICK/HALDIMAND',\n # 'MAGNETAWAN',\n # 'MARMORA AND LAKE',\n # 'HOWICK',\n # 'MOOSONEE',\n # 'OLIVER PAIPOONGE',\n # 'PUSLINCH',\n # 'TRENT HILLS',\n # 'NAIRN AND HYMAN',\n # 'CENTRAL HURON',\n # 'ASHFIELD-COLBORNE-WAWANOSH',\n # 'PAPINEAU-CAMERON',\n # 'AMARANTH',\n # 'ARMOUR',\n # 'MINDEN HILLS',\n # 'COBALT',\n # 'ERIN',\n # 'GRAND VALLEY',\n # 'HURON-KINLOSS',\n # 'CHAMBERLAIN',\n # 'MINTO',\n # 'ADELAIDE-METCALFE',\n # 'HARLEY',\n # 'SOUTH DUNDAS',\n # 'THE BLUE MOUNTAINS',\n # 'GAUTHIER',\n # 'NORTH DUNDAS',\n # 'BLANDFORD-BLENHEIM',\n # 'MARKSTAY-WARREN',\n # 'TECUMSEH',\n # 'CALEDON',\n # 'AURORA',\n # 'KEARNEY',\n # 'NORTH GRENVILLE',\n # 'WEST GREY',\n # 'LATCHFORD',\n # 'GORE BAY',\n # 'PENETANGUISHENE',\n # 'ARMSTRONG',\n # 'CALLANDER',\n # 'NORTH MIDDLESEX',\n # 'DORION',\n # 'SIOUX LOOKOUT',\n # 'SCUGOG',\n # 'LIMERICK',\n # 'EDWARDSBURGH/CARDINAL',\n # 'MATTAWA',\n # 'HANOVER',\n # 'SCHREIBER',\n # 'NORTH PERTH',\n # 'THESSALON',\n # 'SMITHS FALLS',\n # 'ESSA',\n # 'IGNACE',\n # 'PELEE',\n # 'ALGONQUIN HIGHLANDS',\n # 'SPANISH',\n # 'BONNECHERE VALLEY',\n # 'NORTH STORMONT',\n # 'TARBUTT',\n # 'MADAWASKA VALLEY',\n # 'FRONT OF YONGE',\n # 'GREY HIGHLANDS',\n # 'DAWSON',\n # 'WELLESLEY',\n # 'NIAGARA-ON-THE-LAKE',\n # 'SAUGEEN SHORES',\n # 'NORTH GLENGARRY',\n # 'CHARLTON AND DACK',\n # 'TEHKUMMAH',\n # 'HILTON',\n # 'SMOOTH ROCK FALLS',\n # 'ASPHODEL-NORWOOD',\n # 'KERNS',\n # 'WOLLASTON',\n # 'SUNDRIDGE',\n # 'VAL RITA-HARTY',\n # \"O'CONNOR\",\n # 'WOOLWICH',\n # 'WHITE RIVER',\n # 'GREATER MADAWASKA',\n # 'ADMASTON/BROMLEY',\n # 'MCMURRICH/MONTEITH',\n # 'GREATER SUDBURY',\n # 'CARLOW/MAYO',\n # 'SHELBURNE',\n # 'STONE MILLS',\n # 'WESTPORT',\n # 'PERTH SOUTH',\n # 'ZORRA',\n # 'MORRIS-TURNBERRY',\n # 'SOUTH-WEST OXFORD',\n # 'HURON EAST',\n # 'NORTH HURON',\n # 'EAST FERRIS',\n # 'ELIZABETHTOWN-KITLEY',\n # 'PRINCE EDWARD',\n # 'CARLETON PLACE',\n # 'KILLALOE, HAGARTY AND RICHARDS',\n # 'FARADAY',\n # 'CHAPLEAU',\n # 'LINCOLN',\n # 'PLYMPTON-WYOMING',\n # 'ORANGEVILLE',\n # 'LAKE OF THE WOODS',\n # 'BLUEWATER',\n # 'RIDEAU LAKES',\n # 'WEST NIPISSING',\n # 'BROOKE-ALVINSTON',\n # 'HILLIARD',\n # 'POWASSAN',\n # 'SELWYN',\n # 'MONTAGUE',\n # 'LANARK HIGHLANDS',\n # 'PICKLE LAKE',\n # 'THE NATION',\n # 'SEGUIN',\n # 'DRUMMOND/NORTH ELMSLEY',\n # 'COCKBURN ISLAND',\n # 'WEST PERTH',\n # 'MIDDLESEX CENTRE',\n # 'EVANTUREL',\n # 'COBOURG',\n # 'EAST GWILLIMBURY',\n # 'SOUTH BRUCE',\n # 'CLEARVIEW',\n # 'EAST GARAFRAXA',\n # 'CASSELMAN',\n # 'EAST ZORRA-TAVISTOCK',\n # 'PERTH EAST',\n # 'EAR FALLS',\n # 'RUSSELL',\n # 'TILLSONBURG',\n # 'WHITESTONE',\n # 'DAWN-EUPHEMIA',\n # 'MOONBEAM',\n # 'GUELPH/ERAMOSA',\n # 'SPRINGWATER',\n # 'RICHMOND HILL']:\n Year.append(item)\n CITY_column.append(CITY)\n SUM_CO2.append(1)\n\n\n\nagg_df_plus=pd.DataFrame()\nagg_df_plus['Year']=Year\nagg_df_plus['CITY']=CITY_column\nagg_df_plus['SUM_CO2']=SUM_CO2\nagg_df_plus['LOG_SUM_CO2']=np.log10(agg_df_plus['SUM_CO2'])\nagg_df_plus['id']=agg_df_plus['CITY'].apply(lambda x:city_id_map_New[x])\n\nfor feature in obj_Ontario['features']:\n feature['geometry']['coordinates'][0]=feature['geometry']['coordinates'][0][::-1]\n\n# for feature in obj_Ontario['features']:\n# if feature['properties']['MUNICIPAL_NAME_SHORTFORM'] in wrong_geojson:\n# feature['geometry']['coordinates'][0]=feature['geometry']['coordinates'][0][::-1]\n\nagg_final=pd.concat([agg_df,agg_df_plus])\n# agg_final=agg_df\n# agg_final=agg_df_plus\n\n\napp = dash.Dash(__name__)\n\napp.layout = html.Div([\n html.P(\"Year:\"),\n dcc.Slider(agg_final['Year'].unique().min(),agg_final['Year'].unique().max(),\n value=agg_final['Year'].unique().max(),step=None,\n marks={str(year):str(year) for year in agg_final['Year'].unique()},id='year'),\n dcc.Graph(id=\"graph_with_slider\"),\n])\n\n@app.callback(\n Output(\"graph_with_slider\", \"figure\"),\n Input(\"year\", \"value\"))\n\ndef display_choropleth(year):\n filtered_agg_df=agg_final[agg_final['Year']==year]\n fig = px.choropleth(\n filtered_agg_df, geojson=obj_Ontario, color='LOG_SUM_CO2',\n hover_name='CITY',locations=\"id\",color_continuous_scale=\"Turbo\")\n # fig = px.scatter_geo(\n # filtered_agg_df, geojson=obj_Ontario,size='SUM_CO2',\n # hover_name='CITY',locations=\"id\",\n # color_continuous_scale=\"Blues\")\n fig.update_geos(fitbounds=\"locations\", visible=False)\n fig.update_layout(margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0},\n annotations = [dict(\n x=0,\n y=0,\n xref='paper',\n yref='paper',\n text='Source: \\\n Greenhouse gas emissions reporting by facility_Ontario',\n showarrow = False\n )])\n\n return fig\nif __name__ == '__main__':\n app.run_server(debug=True)\n # app.run_server(use_reloader=False)\n","repo_name":"alihabibiAB/CO2_Emission_Ontario","sub_path":"Final_ontario+.py","file_name":"Final_ontario+.py","file_ext":"py","file_size_in_byte":11278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"4304361063","text":"import argparse\nfrom machine_learning_handle import get_rgb, regression\n\n\ndef parseargs(required_args=True):\n # Format help\n class formatter(\n argparse.ArgumentDefaultsHelpFormatter, argparse.RawTextHelpFormatter\n ):\n pass\n\n epilog = \"\"\n parser = argparse.ArgumentParser(\n description=\"Feature engineering to decide\",\n epilog=epilog,\n formatter_class=formatter,\n )\n parser.add_argument(\n \"-tm\",\n \"--train_images\",\n help=\"Image path location\",\n default=\".\",\n )\n parser.add_argument(\n \"-tc\",\n \"--train_concentration\",\n help=\"Image path location\",\n )\n parser.add_argument(\n \"-d\",\n \"--degree\",\n help=\"Method for regression\",\n default=1,\n )\n parser.add_argument(\n \"-o\",\n \"--outdir\",\n help=\"Path location for output\",\n default=\".\",\n )\n args = parser.parse_args()\n\n return args\n\n\ndef main(args):\n # Step 1: Extract the RGB value of target datasets\n rgb_path = get_rgb(args.train_images, args.outdir)\n # Step 2: Regression to get the value\n regression(\n rgb_path=rgb_path,\n train_concentration=args.train_concentration,\n degree=args.degree,\n outdir=args.outdir,\n )\n\n\nif __name__ == \"__main__\":\n args = parseargs()\n main(args)\n","repo_name":"giangbioinformatics/smart-optical-sensor","sub_path":"smartsensor/machine_learning.py","file_name":"machine_learning.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"16950836550","text":"from .controll import Controll as Ctl\r\nfrom .player import Player\r\nfrom .dealer import Dealer\r\nfrom .card import Card\r\nimport sys\r\n\r\nclass Game():\r\n def __init__(self):\r\n self.status = \"Start\"\r\n self.round = 0\r\n\r\n def Start(self, Card_list, player, dealer):\r\n self.status = \"Start\"\r\n \r\n if self.round == 0:\r\n answer = Ctl.gets_answer(\"ゲームを開始しますか?\")\r\n \r\n if answer:\r\n print(\"ゲームを終了します。\")\r\n sys.exit()\r\n else:\r\n Ctl.clear()\r\n print(\"ゲームが開始されました。\")\r\n self.round += 1\r\n dealer.show()\r\n player.show()\r\n else:\r\n Ctl.clear()\r\n print(\"ゲームが開始されました。\")\r\n dealer.show()\r\n player.show()\r\n\r\n if player.total == dealer.total and player.is_21():\r\n Ctl.clear()\r\n player.show()\r\n dealer.show_all()\r\n\r\n print(\"二人ともブラックジャック!!\")\r\n print(\"引き分けです!\")\r\n self.End()\r\n elif dealer.is_21():\r\n Ctl.clear()\r\n player.show()\r\n dealer.show_all()\r\n\r\n print(\"ブラックジャック!\")\r\n print(\"ディーラーの勝ちです\")\r\n self.End()\r\n elif player.is_21():\r\n Ctl.clear()\r\n player.show()\r\n dealer.show_all()\r\n \r\n print(\"ブラックジャック!\")\r\n print(\"あなたの勝ち!\")\r\n self.End()\r\n else:\r\n self.Next(Card_list, player, dealer)\r\n \r\n def Next(self, cards, player, dealer):\r\n answer = Ctl.gets_answer(\"HIT or STAND\", [\"H\", \"Hit\"], [\"S\", \"Stand\"])\r\n\r\n if answer:\r\n self.Battle(cards, player, dealer)\r\n else:\r\n player.cards.append(cards.hit())\r\n player.show()\r\n\r\n if player.is_bust():\r\n print(\"バースト!\")\r\n print(\"ディーラーの勝ち!\")\r\n self.End()\r\n elif player.is_21():\r\n print(\"ブラックジャック\")\r\n print(\"あなたの勝ち!\")\r\n self.End()\r\n else:\r\n self.Next(cards, player, dealer)\r\n \r\n def Battle(self, cards, player, dealer):\r\n Ctl.clear()\r\n dealer.show_all()\r\n\r\n if dealer.is_more_17 and dealer.total > player.total:\r\n print(\"ディーラーの勝ち!\")\r\n self.End()\r\n else:\r\n while True:\r\n dealer.cards.append(cards.hit())\r\n dealer.total = Card.counter(dealer.cards)\r\n dealer.show_all()\r\n\r\n if dealer.is_bust():\r\n print(\"ディーラーがバーストした!\")\r\n print(\"あなたの勝ち!\")\r\n self.End()\r\n break\r\n elif dealer.is_more_17:\r\n if player.total == dealer.total:\r\n print(\"引き分けです!\")\r\n player.show()\r\n self.End()\r\n break\r\n elif dealer.is_21():\r\n print(\"ブラックジャック!\")\r\n player.show()\r\n self.End()\r\n break\r\n elif player.total > dealer.total:\r\n print(\"あなたの勝ち!\")\r\n player.show()\r\n self.End()\r\n break\r\n else:\r\n print(\"ディーラーの勝ち!\")\r\n player.show()\r\n self.End()\r\n break\r\n else:\r\n pass\r\n\r\n\r\n\r\n def End(self):\r\n self.status = \"End\"\r\n\r\n if Ctl.gets_answer(\"もう一度プレイしますか?\"):\r\n sys.exit()\r\n else:\r\n Card_list = Card()\r\n player = Player(Card_list)\r\n dealer = Dealer(Card_list)\r\n self.Start(Card_list, player, dealer)\r\n","repo_name":"HEKUCHAN/Old-Python-BlackJack","sub_path":"src/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4317,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"15218796657","text":"# This is the class you derive to create a plugin\nfrom airflow.plugins_manager import AirflowPlugin\n\nfrom airflow.contrib.hooks.salesforce_hook import SalesforceHook\nfrom airflow.hooks.S3_hook import S3Hook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n\nimport logging\nfrom tempfile import NamedTemporaryFile\n\n\nclass SalesforceToS3Operator(BaseOperator):\n \"\"\"\n Make a query against Salesforce and\n write the resulting data to a file.\n \"\"\"\n template_fields = (\"query\", )\n\n @apply_defaults\n def __init__(\n self,\n sf_conn_id,\n obj,\n output,\n s3_conn_id,\n s3_bucket,\n fields=None,\n fmt=\"csv\",\n query=None,\n relationship_object=None,\n record_time_added=False,\n coerce_to_timestamp=False,\n *args,\n **kwargs\n ):\n \"\"\"\n Initialize the operator\n :param conn_id: name of the Airflow connection that has\n your Salesforce username, password and\n security_token\n :param obj: name of the Salesforce object we are\n fetching data from\n :param output: name of the file where the results\n should be saved\n :param fields: *(optional)* list of fields that you want\n to get from the object.\n If *None*, then this will get all fields\n for the object\n :param fmt: *(optional)* format that the output of the\n data should be in.\n *Default: CSV*\n :param query: *(optional)* A specific query to run for\n the given object. This will override\n default query creation.\n *Default: None*\n :param relationship_object: *(optional)* Some queries require\n relationship objects to work, and\n these are not the same names as\n the SF object. Specify that\n relationship object here.\n *Default: None*\n :param record_time_added: *(optional)* True if you want to add a\n Unix timestamp field to the resulting data\n that marks when the data was\n fetched from Salesforce.\n *Default: False*.\n :param coerce_to_timestamp: *(optional)* True if you want to convert\n all fields with dates and datetimes\n into Unix timestamp (UTC).\n *Default: False*.\n \"\"\"\n\n super(SalesforceToS3Operator, self).__init__(*args, **kwargs)\n\n self.sf_conn_id = sf_conn_id\n self.output = output\n self.s3_conn_id = s3_conn_id\n self.s3_bucket = s3_bucket\n self.object = obj\n self.fields = fields\n self.fmt = fmt.lower()\n self.query = query\n self.relationship_object = relationship_object\n self.record_time_added = record_time_added\n self.coerce_to_timestamp = coerce_to_timestamp\n\n def special_query(self, query, sf_hook, relationship_object=None):\n if not query:\n raise ValueError(\"Query is None. Cannot query nothing\")\n\n sf_hook.sign_in()\n\n results = sf_hook.make_query(query)\n if relationship_object:\n records = []\n for r in results['records']:\n if r.get(relationship_object, None):\n records.extend(r[relationship_object]['records'])\n results['records'] = records\n\n return results\n\n def execute(self, context):\n \"\"\"\n Execute the operator.\n This will get all the data for a particular Salesforce model\n and write it to a file.\n \"\"\"\n logging.info(\"Prepping to gather data from Salesforce\")\n\n # open a name temporary file to\n # store output file until S3 upload\n with NamedTemporaryFile(\"w\") as tmp:\n\n # load the SalesforceHook\n # this is what has all the logic for\n # connecting and getting data from Salesforce\n hook = SalesforceHook(\n conn_id=self.sf_conn_id,\n output=tmp.name\n )\n\n # attempt to login to Salesforce\n # if this process fails, it will raise an error and die right here\n # we could wrap it\n hook.sign_in()\n\n # get object from Salesforce\n # if fields were not defined,\n # then we assume that the user wants to get all of them\n if not self.fields:\n self.fields = hook.get_available_fields(self.object)\n\n logging.info(\n \"Making request for\"\n \"{0} fields from {1}\".format(len(self.fields), self.object)\n )\n\n if self.query:\n query = self.special_query(\n self.query,\n hook,\n relationship_object=self.relationship_object\n )\n else:\n query = hook.get_object_from_salesforce(self.object, self.fields)\n\n # output the records from the query to a file\n # the list of records is stored under the \"records\" key\n logging.info(\"Writing query results to: {0}\".format(tmp.name))\n hook.write_object_to_file(\n query['records'],\n filename=tmp.name,\n fmt=self.fmt,\n coerce_to_timestamp=self.coerce_to_timestamp,\n record_time_added=self.record_time_added\n )\n\n # flush the temp file\n # upload temp file to S3\n tmp.flush()\n dest_s3 = S3Hook(s3_conn_id=self.s3_conn_id)\n dest_s3.load_file(\n filename=tmp.name,\n key=self.output,\n bucket_name=self.s3_bucket,\n replace=True\n )\n dest_s3.connection.close()\n tmp.close()\n logging.info(\"Query finished!\")\n\nclass SalesforcePlugin(AirflowPlugin):\n name = \"salesforce_plugin\"\n operators = [SalesforceToS3Operator]\n # A list of class(es) derived from BaseHook\n hooks = []\n # A list of class(es) derived from BaseExecutor\n executors = []\n # A list of references to inject into the macros namespace\n macros = []\n # A list of objects created from a class derived\n # from flask_admin.BaseView\n admin_views = []\n # A list of Blueprint object created from flask.Blueprint\n flask_blueprints = []\n # A list of menu links (flask_admin.base.MenuLink)\n menu_links = []","repo_name":"MartijnSch/example-dags","sub_path":"salesforce_to_slack/plugins/salesforce_operator.py","file_name":"salesforce_operator.py","file_ext":"py","file_size_in_byte":7149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"8513490323","text":"names = []\r\nfor i in range(5):\r\n names.append(input(\"names=>\"))\r\n\r\nfor name in names:\r\n print(name[::-1])\r\n\r\n# 2 wap to print a fibonacci series using the concept of list\r\n\r\nfib = [0,1]\r\nfor i in range(15):\r\n fib.append( fib[-1] + fib[-2])\r\nprint(fib)\r\n\r\n# 3 wap to generate a new list that contains squares of each no. from existing list\r\n\r\nx = [1,2,3,3,4,5,2,2]\r\nx2 = []\r\nfor num in x:\r\n x2.append(num ** 2)\r\nprint(x)\r\nprint(x2)\r\n\r\n# 4\r\n\r\nx = [1,2,3,3,4,5,6,7]\r\nxodd = []\r\nfor i in x:\r\n if i % 2 != 0:\r\n xodd.append(i)\r\nprint(xodd)\r\n\r\n# -------> list comprehension\r\nxodd = [i for i in x if i % 2 != 0]\r\n# -------> list comprehension\r\n\r\n# 5\r\nx = [1,2,3,4,2,3,4]\r\ny = [5,7,2,1,3,2,3]\r\nz = []\r\n\r\nfor i,j in zip(x,y):\r\n z.append(i + j)\r\nprint(x)\r\nprint(y)\r\nprint(z)\r\n\r\nfor i in range(1,11):\r\n print(f'2 * {i} = {2*i}')","repo_name":"Nupur832/digipodium-classes","sub_path":"list_ex5.py","file_name":"list_ex5.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"5479597855","text":"from selenium.webdriver.common.by import *\nfrom model.group import Group\n\n\nclass GroupHelper:\n def __init__(self, app):\n self.app = app\n\n def open_groups_page(self):\n wd = self.app.wd\n if not (wd.current_url.endswith(\"/group.php\") and len(wd.find_elements(By.NAME, \"new\")) > 0):\n wd.find_element(By.LINK_TEXT, \"groups\").click()\n\n def create(self, group):\n wd = self.app.wd\n self.open_groups_page()\n wd.find_element(By.NAME, \"new\").click()\n self.fill_group_data(wd, group, \"submit\")\n self.group_cache = None\n\n def delete_first_group(self):\n self.delete_group_by_index(0)\n\n def delete_group_by_index(self, index):\n wd = self.app.wd\n self.open_groups_page()\n wd.find_elements(By.NAME, \"selected[]\")[index].click()\n wd.find_element(By.NAME, \"delete\").click()\n self.return_to_groups_page()\n self.group_cache = None\n\n def delete_group_by_id(self, id):\n wd = self.app.wd\n self.open_groups_page()\n wd.find_element(By.CSS_SELECTOR, \"input[value='%s']\" % id).click()\n wd.find_element(By.NAME, \"delete\").click()\n self.return_to_groups_page()\n self.group_cache = None\n\n def edit_group_by_index(self, group, index):\n wd = self.app.wd\n self.open_groups_page()\n wd.find_elements(By.NAME, \"selected[]\")[index].click()\n wd.find_element(By.NAME, \"edit\").click()\n self.fill_group_data(wd, group, \"update\")\n self.group_cache = None\n\n def edit_group_by_id(self, group, id):\n wd = self.app.wd\n self.open_groups_page()\n wd.find_element(By.CSS_SELECTOR, \"input[value='%s']\" % id).click()\n wd.find_element(By.NAME, \"edit\").click()\n self.fill_group_data(wd, group, \"update\")\n self.group_cache = None\n\n def fill_group_data(self, wd, group, flag):\n self.fill_field_value(\"group_name\", group.name)\n self.fill_field_value(\"group_header\", group.header)\n self.fill_field_value(\"group_footer\", group.footer)\n if flag == \"submit\":\n wd.find_element(By.NAME, \"submit\").click()\n if flag == \"update\":\n wd.find_element(By.NAME, \"update\").click()\n self.return_to_groups_page()\n\n def fill_field_value(self, field_id, value):\n wd = self.app.wd\n if value is not None:\n wd.find_element(By.NAME, field_id).click()\n wd.find_element(By.NAME, field_id).clear()\n wd.find_element(By.NAME, field_id).send_keys(value)\n\n def return_to_groups_page(self):\n wd = self.app.wd\n wd.find_element(By.LINK_TEXT, \"group page\").click()\n\n def groups_count(self):\n wd = self.app.wd\n self.open_groups_page()\n return len(wd.find_elements(By.NAME, \"selected[]\"))\n\n def check_group_name(self, group_name_to_check):\n wd = self.app.wd\n self.open_groups_page()\n rows_count = len(wd.find_elements(By.CLASS_NAME, 'group'))\n if rows_count > 0:\n group_names = []\n for i in range(rows_count):\n row_index = str(i + 1)\n group = wd.find_element(By.XPATH, \"/html[1]/body[1]/div[1]/div[4]/form[1]/span[\" + row_index + \"]\").text\n group_names.append(group)\n if group_name_to_check in group_names:\n return True\n\n\n group_cache = None\n\n def get_groups_list(self):\n if self.group_cache is None:\n wd = self.app.wd\n self.open_groups_page()\n self.group_cache = []\n for i in wd.find_elements(By.CSS_SELECTOR, \"span.group\"):\n group_name = i.text\n group_id = i.find_element(By.NAME, \"selected[]\").get_attribute(\"value\")\n self.group_cache.append(Group(id=group_id, name=group_name))\n return list(self.group_cache)\n","repo_name":"alexeev-anton/python-training","sub_path":"fixture/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":3875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"11192722418","text":"# types\nimport nltk\nnltk.download('punkt')\nfrom nrclex import NRCLex as nl\nimport numpy as np\nfrom matplotlib import pyplot as plt\nbackend = plt.get_backend()\nimport jpcm\nplt.switch_backend(backend)\nimport io,base64\n\nkeys = np.array(['fear', 'anger', 'trust', 'surprise', 'positive', 'negative', 'sadness', 'disgust', 'joy', 'anticipation'])\ncs = [jpcm.maps.murasaki,jpcm.maps.nakabeni,jpcm.maps.chigusa_iro,jpcm.maps.shinshu,jpcm.maps.sora_iro,jpcm.maps.kokushoku,\n jpcm.maps.benihibata,jpcm.maps.omeshi_onando,jpcm.maps.tomorokoshi_iro,jpcm.maps.enji_iro]\nn_keys = len(keys)\n\ndef norm(v):\n return v/np.linalg.norm(v) if any(v) != 0 else v\n\ndef nlparse(tx):\n item = nl(text=tx)\n res = item.affect_frequencies\n rkeys = res.keys()\n effect = np.zeros(n_keys)\n for j in range(n_keys):\n key = keys[j]\n if key in rkeys:\n effect[j] = res[key]\n return norm(effect)\n\ndef img(fig):\n my_stringIObytes = io.BytesIO()\n fig.savefig(my_stringIObytes, format='jpg', dpi=160)\n my_stringIObytes.seek(0)\n return base64.b64encode(my_stringIObytes.read())\n # canvas=FigureCanvas(fig)\n # response=HttpResponse(content_type='image/png')\n # fig.savefig(response, format='png', dpi=600)\n # return response.content\n\ndef draw(inp,name,figsize=(10,8)):\n fig=plt.figure(figsize=figsize)\n if len(inp.shape)==2:\n for i in inp.shape[1]:\n plt.plot(inp[:,i], c=cs[i])\n if inp.shape[1]==n_keys:\n plt.legend(keys)\n else:\n plt.legend(list(range(inp.shape[1])))\n plt.ylabel(name)\n plt.title(name)\n plt.xlabel('X')\n out = img(fig)\n plt.close()\n return out","repo_name":"akhilsadam/compose-dev","sub_path":"app/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"19317229979","text":"from django.conf.urls import url\n\nurlpatterns = [\n url(r'^get_year/', 'vtmultiscale.views.get_year', name='get_year'),\n url(\n r'^search_station/',\n 'vtmultiscale.views.search_station',\n name='search_station'\n ),\n url(\n r'^stations_ordered/',\n 'vtmultiscale.views.stations_ordered',\n name='stations_ordered'\n ),\n]\n","repo_name":"guilhermelou/tcc","sub_path":"project/tcc/vtmultiscale/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"10415637909","text":"from asyncio import sleep\nfrom hashlib import md5\nfrom lzma import compress\n\nimport asynctest\nfrom aiofile import AIOFile\n\nimport siaslice as ss\n\n\nclass TestTaskGenerator(asynctest.TestCase):\n\n async def test_await_all(self):\n mock = asynctest.CoroutineMock()\n async def cor():\n await mock(1)\n await ss.await_all(cor() for i in range(10))\n mock.assert_has_awaits([asynctest.call(1)]*10)\n\n async def test_limit_concurrency(self):\n mock = asynctest.CoroutineMock()\n v = 0\n async def cor():\n nonlocal v\n new_v = v + 1\n await sleep(1)\n v = new_v\n await mock(v)\n await ss.await_all(ss.limit_concurrency((cor() for i in range(10)), 1))\n mock.assert_has_awaits([asynctest.call(i) for i in range(1, 11)])\n\n\nclass TestGenerators(asynctest.TestCase):\n\n async def test_afp_generator(self):\n async with AIOFile('40MiBempty.img', mode='rb') as afp:\n reference = await afp.read()\n read = b''.join([chunk async for chunk\n in ss.region_read(afp, 0, 40*1000*1000)])\n self.assertEqual(read, reference)\n\n async def test_is_zeroes(self):\n async with AIOFile('40MiBempty.img', mode='rb') as afp:\n self.assertTrue(await ss.is_zeroes(ss.region_read(afp, 0, 40*1000*1000)))\n\n async def test_is_not_zeroes(self):\n async def agen(gen):\n for x in gen:\n yield x\n chunks = [b'\\0\\0\\0\\0', b'\\0\\0\\0\\0', b'\\0\\0\\0X', b'\\0\\0\\0\\0']\n self.assertFalse(await ss.is_zeroes(agen(iter(chunks))))\n\n async def test_md5_hasher(self):\n async with AIOFile('40MiBempty.img', mode='rb') as afp:\n reference = md5(await afp.read()).hexdigest()\n compare = await ss.md5_hasher(ss.region_read(afp, 0, 40*1000*1000))\n self.assertEqual(compare, reference)\n\n async def test_lzma_compress(self):\n async with AIOFile('40MiBempty.img', mode='rb') as afp:\n reference = compress(await afp.read())\n agen = ss.region_read(afp, 0, 40*1000*1000)\n compare = b''.join([chunk async for chunk in ss.lzma_compress(agen)])\n self.assertEqual(compare, reference)\n\n\nif __name__ == '__main__':\n asynctest.main()\n\n","repo_name":"YoRyan/sia-slice","sub_path":"tests/test_misc.py","file_name":"test_misc.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"44"} +{"seq_id":"17834278710","text":"import pickle\nimport copy\nfrom functions.utils import print_stuff\nfrom functions.utils import colour_it\nfrom functions.utils import Color\nfrom functions.utils import clear\n\n\nachievements = {\n\t\"resourceful\": {\n\t\t\"name\": \"Resourceful\",\n\t\t\"description\": \"Complete a combat encounter without using items.\",\n\t\t\"completed\": \"You completed a combat encounter without using items.\",\n\t\t\"unlocked\": False\n\t},\n\t\"untouchable\": {\n\t\t\"name\": \"Untouchable\",\n\t\t\"description\": \"Complete a combat encounter of three or more enemies without taking damage.\",\n\t\t\"completed\": \"You completed a combat encounter of three or more enemies without taking damage.\",\n\t\t\"unlocked\": False\n\t},\n\t\"body_count\": {\n\t\t\"name\": \"Body Count\",\n\t\t\"description\": \"Defeat a group of three or more enemies in the same amount of turns.\",\n\t\t\"completed\": \"You defeated a group of three or more enemies in the same amount of turns.\",\n\t\t\"unlocked\": False\n\t},\n\t\"knife_master\": {\n\t\t\"name\": \"Knife Master\",\n\t\t\"description\": \"Kill an enemy using only knives.\",\n\t\t\"completed\": \"You killed an enemy using only knives.\",\n\t\t\"unlocked\": False\n\t},\n\t\"counter_kill\": {\n\t\t\"name\": \"Counter Kill\",\n\t\t\"description\": \"Defeat a group of two or more enemies using only Counter Parry.\",\n\t\t\"completed\": \"You defeated a group of two or more enemies using only Counter Parry.\",\n\t\t\"unlocked\": False\n\t},\n\t\"back_for_more\": {\n\t\t\"name\": \"Back for More\",\n\t\t\"description\": \"Drop to 0 health three times in the same combat encounter... and win.\",\n\t\t\"completed\": \"You dropped to 0 health three times in the same combat encounter... and won.\",\n\t\t\"unlocked\": False\n\t},\n\t\"bleed_out\": {\n\t\t\"name\": \"Bleed Out\",\n\t\t\"description\": \"Kill an enemy with bleeding damage.\",\n\t\t\"completed\": \"You killed an enemy with bleeding damage.\",\n\t\t\"unlocked\": False\n\t},\n\t\"jack_of_all_trades\": {\n\t\t\"name\": \"Jack of all Trades\",\n\t\t\"description\": \"Complete a combat encounter with at least one strike, parry, and distract.\",\n\t\t\"completed\": \"You completed a combat encounter with at least one strike, parry, and distract.\",\n\t\t\"unlocked\": False\n\t},\n\t\"swordmaster\": {\n\t\t\"name\": \"Swordmaster\",\n\t\t\"description\": \"Complete a combat encounter while using at least three different strikes.\",\n\t\t\"completed\": \"You completed a combat encounter while using at least three different strikes.\",\n\t\t\"unlocked\": False\n\t},\n\t\"teamwork\": {\n\t\t\"name\": \"Teamwork\",\n\t\t\"description\": \"Kill an enemy while an ally has either goaded or distracted them.\",\n\t\t\"completed\": \"You killed an enemy while an ally has either goaded or distracted them\",\n\t\t\"unlocked\": False\n\t},\n}\n\nbackup = copy.deepcopy(achievements)\n\ndef save_achievements():\n\tglobal achievements\n\tdata = copy.deepcopy(achievements)\n\twith open(f'Achievements.dat', 'wb') as f:\n\t\t\tpickle.dump(data, f, protocol=2)\n\n\ndef get_achievement(gained):\n\tglobal achievements\n\tif achievements[gained]['unlocked'] != True:\n\t\tachievements[gained]['unlocked'] = True\n\t\tprint_stuff([f'''{colour_it(f\"Achievement Unlocked: {achievements[gained]['name']}!\", Color.YELLOW)}'''])\n\t\tsave_achievements()\n\telse:\n\t\treturn\n\n\ndef load_achievements():\n\tglobal achievements\n\twith open(f'Achievements.dat', 'rb') as f:\n\t\tdata = pickle.load(f)\n\tachievements = copy.deepcopy(data)\n\n\ndef view_achievements():\n\tglobal achievements\n\tglobal backup\n\tclear()\n\tprint(f\"\"\"{colour_it(\"~ THE NIGHTHAWK ~\", Color.RED)}\n\"\"\")\n\tkeys = achievements.keys()\n\tload_achievements()\n\tif achievements.keys() != keys:\n\t\tfor achievement in achievements:\n\t\t\tif achievements[achievement]['unlocked']:\n\t\t\t\tbackup[achievement]['unlocked'] = True\n\t\tachievements = copy.deepcopy(backup)\n\tview = \"\"\n\tfor achievement in achievements:\n\t\tif achievements[achievement]['unlocked']:\n\t\t\tview = view + f\"\"\"~{colour_it(achievements[achievement]['name'], Color.GREEN)}~\n{achievements[achievement]['completed']}\n\n\"\"\"\n\t\telse:\n\t\t\tview = view + f\"\"\"~{colour_it(achievements[achievement]['name'], Color.RED)}~\n{achievements[achievement]['description']}\n\n\"\"\"\n\tprint(view)\n\tprint_stuff([''])\n\n\n\n\n","repo_name":"jessebro/nighthawkadventure","sub_path":"functions/achievements.py","file_name":"achievements.py","file_ext":"py","file_size_in_byte":3939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"20290536454","text":"BAND = 'T'\nSUMSER = 0\nI = 2\nwhile (I <= 1800):\n SUMSER += 1\n print(\"incremento de valor:\" , I)\n if BAND == 'T' :\n BAND = 'F' \n I += 3\n else:\n BAND = 'T' \n I += 2\nprint(\"Los términos de la serie son:\" , SUMSER)\nprint(\"FIN DEL PROGRAMA\")\n","repo_name":"Areli-vazquez/CYPAreliVS","sub_path":"LIBRO/problemas_resueltos/capitulo3/problema3_2.py","file_name":"problema3_2.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"25993414457","text":"\n# coding: utf-8\n\n# # 作業\n# ### 用 iris (dataset.load_iris()) 資料嘗試跑 kmeans (可以測試不同的群數 , init 等)\n\n# In[9]:\n\n\nimport numpy as np\nfrom sklearn import datasets\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\niris = datasets.load_iris()\nX = iris.data\ny = iris.target\n\n\n# ### 載入 相關套件 並 執行 kmean 實驗 ...\n# \n# - 實驗測試不同的群數\n# - 實驗測試不同的初始值\n# - 呈現結果\n\n\n# 設定 模型 估計參數\nestimators = [('k_means_8', KMeans(n_clusters=8)),\n ('k_means_3', KMeans(n_clusters=3)),\n ('k_means_bad_init', KMeans(n_clusters=3, n_init=1,\n init='random'))]\n \n \nfignum = 1\ntitles = ['8 clusters', '3 clusters', '3 clusters, bad initialization']\nfor name, est in estimators:\n fig = plt.figure(fignum, figsize=(4, 3))\n ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)\n \n ## fit data\n est.fit(X)\n \n labels = est.labels_\n\n ax.scatter(X[:, 3], X[:, 0], X[:, 2],\n c=labels.astype(np.float), edgecolor='k')\n\n ax.w_xaxis.set_ticklabels([])\n ax.w_yaxis.set_ticklabels([])\n ax.w_zaxis.set_ticklabels([])\n ax.set_title(titles[fignum - 1])\n ax.dist = 12\n fignum = fignum + 1\n","repo_name":"Martin8202/ML-100-Days","sub_path":"homework/Day_055_HW.py","file_name":"Day_055_HW.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"71286879493","text":"\"\"\"lincy URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\n\nfrom django.urls import path\nfrom.import views\n\n\n\nurlpatterns = [\n # path('home/',include('doctorapp.urls')),\n # path('admin/', admin.site.urls),\n #path('reg/', views.doctor, name = 'doctor'),\n path('patientdetails', views.patientdetails, name = 'patientdetails'),\n path('doctordetails', views.doctordetails, name = 'doctordetails'),\n path('consultation', views.consulting, name = 'consult'),\n path('doctor_availability', views.doctoravail, name = 'consult'),\n path('doctor_schedule', views.doctorschedule, name = 'consult'),\n path('doctor_save', views.availsave, name = 'consult'),\n path('list', views.hosplist, name = 'eachlist'),\n path('doctordelete', views.deletelist, name = 'eachlist'),\n path('newdata', views.patientnewdata, name = 'eachlist'),\n path('doctorupdate', views.updatelist, name = 'eachlist'),\n path('doctor_update', views.availupdate, name = 'update'),\n path('booking', views.booking, name = 'booking'),\n path('patientbooklist', views.pbooklist, name = 'bookinglist'),\n path('patientstate', views.pstate, name = 'patientstate'),\n path('cancelpatient', views.cancelpatient, name = 'patientcancel'),\n path('doctorhome', views.doctorhome, name = 'doctorhome'),\n \n]\n","repo_name":"lincysam/lincy","sub_path":"doctorapp2/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"20166331163","text":"import pygame\r\nimport pandas as pd\r\nfrom openpyxl import load_workbook\r\n\r\nfrom omok_project.button import Button\r\n\r\ndef get_font(size): # Returns Press-Start-2P in the desired size\r\n return pygame.font.Font(\"tway_sky.ttf\", size)\r\n\r\ndef main():\r\n screen = pygame.display.set_mode((1280, 800))\r\n\r\n font = pygame.font.Font(None, 32)\r\n clock = pygame.time.Clock()\r\n input_box = pygame.Rect(100, 100, 140, 32)\r\n color_inactive = pygame.Color('lightskyblue3')\r\n color_active = pygame.Color('dodgerblue2')\r\n color = color_inactive\r\n rec = pygame.image.load(\"image/loading.jpg\")\r\n text = ''\r\n active = False\r\n done = False\r\n\r\n data = load_workbook('ranking.xlsx')\r\n ws = data.active\r\n name_list = []\r\n for row in ws.rows:\r\n name_list.append(row[0].value)\r\n\r\n print(name_list)\r\n print(type(name_list))\r\n name_index = 4\r\n\r\n while True:\r\n screen.fill((0, 0, 0))\r\n screen.blit(rec, (0, 0))\r\n MENU_POS = pygame.mouse.get_pos()\r\n # Render the current text.\r\n txt_surface = font.render(text, True, color)\r\n\r\n # Resize the box if the text is too long.\r\n width = max(200, txt_surface.get_width()+10)\r\n input_box.w = width\r\n # Blit the text.\r\n screen.blit(txt_surface, (input_box.x+5, input_box.y+5))\r\n # Blit the input_box rect.\r\n pygame.draw.rect(screen, color, input_box, 2)\r\n\r\n add_name_button = Button(image=pygame.image.load(\"image/Play Rect.png\"), pos=(450, 500),\r\n text_input=\"WIN\", font=get_font(40), base_color=\"#d7fcd4\",\r\n hovering_color=\"White\")\r\n\r\n back_button = Button(image=pygame.image.load(\"image/Play Rect.png\"), pos=(850, 500),\r\n text_input=\"LOSE\", font=get_font(40), base_color=\"#d7fcd4\", hovering_color=\"White\")\r\n\r\n for button in [add_name_button, back_button]:\r\n button.changeColor(MENU_POS)\r\n button.update(screen)\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n pygame.exit()\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n if add_name_button.checkForInput(MENU_POS):\r\n ws[\"B\"+str((name_index + 1))] = (int(ws[\"B\"+str((name_index + 1))].value) + 1)\r\n data.save(\"ranking.xlsx\")\r\n if back_button.checkForInput(MENU_POS):\r\n ws[\"C\"+str((name_index + 1))] = (int(ws[\"C\"+str((name_index + 1))].value) + 1)\r\n data.save(\"ranking.xlsx\")\r\n\r\n pygame.display.update()\r\n\r\n\r\nif __name__ == '__main__':\r\n pygame.init()\r\n main()\r\n\r\n","repo_name":"Jun-yong-lee/Omok_robot","sub_path":"omok_project_final/prac_text.py","file_name":"prac_text.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"29406273948","text":"import auth\nimport database_handling as dbh\nimport json\nimport sqlalchemy as db\n\nwith open('db_secrets.json', 'r') as json_data:\n db_secrets = json.load(json_data)\n db_user = db_secrets[\"db_user\"]\n db_password = db_secrets[\"db_password\"]\n db_url = db_secrets[\"db_url\"]\n db_ports = db_secrets[\"db_ports\"]\n db_name = db_secrets[\"db_name\"] \n\nengine = db.create_engine('mysql+pymysql://'+db_user+':'+db_password+'@'+db_url+':'+db_ports+'/'+db_name)\nmetadata = db.MetaData()\nminifigure_parts = db.Table('minifigure_parts', metadata, autoload=True, autoload_with=engine)\n\ndef get_db_entries():\n db_entries = []\n with engine.connect() as connection:\n query = connection.execute(minifigure_parts.select()).fetchall()\n for item in query:\n minifigure_id = item[1]\n if minifigure_id not in db_entries:\n db_entries.append(minifigure_id)\n return db_entries\n\ndef generate_parts_list(minifigure_id):\n client = auth.auth_on_bricklink()\n url = 'https://api.bricklink.com/api/store/v1/items/minifig/'+minifigure_id+'/subsets?direction=in'\n response = client.get(url)\n parts_json = response.json()['data']\n parts_count = len(parts_json)\n parts_list = []\n for i in range(0,parts_count):\n if len(parts_json) == 0:\n continue\n else:\n entry = parts_json[i]['entries'][0]\n parts_item_dict = {\n 'minifigure_id': minifigure_id,\n 'part_id': entry['item']['no'],\n 'part_color': entry['color_id'],\n 'part_quantity': entry['quantity'],\n 'key': minifigure_id+entry['item']['no']+str(entry['color_id'])\n }\n parts_list.append(parts_item_dict)\n print(parts_item_dict)\n return parts_list\n\ndef fetch_and_save_minifigure_parts(category_number):\n minifigure_list = dbh.get_minifigures_of_category(category_number)\n db_entries = get_db_entries()\n for minifigure in minifigure_list:\n if minifigure not in db_entries:\n parts_list = generate_parts_list(minifigure)\n dbh.save_minifigure_parts(parts_list)","repo_name":"dominikfranzen/Unbrickable","sub_path":"save_parts.py","file_name":"save_parts.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"17555686076","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils.encoding import python_2_unicode_compatible\n\n# Create your models here.\n\n@python_2_unicode_compatible\nclass Type(models.Model):\n name = models.CharField(max_length=150, verbose_name=\"Type de jeu\")\n slug = models.SlugField(unique=True, verbose_name=\"Slug\")\n class Meta:\n verbose_name = 'Categorie'\n verbose_name_plural = 'Categories'\n def __str__(self):\n return self.name\n\n@python_2_unicode_compatible\nclass Jeux(models.Model):\n title = models.CharField(max_length=150, verbose_name=\"Nom du jeu\")\n body = models.TextField(verbose_name=\"Déscription\")\n slug = models.SlugField(unique=True, verbose_name=\"Slug\")\n author = models.ForeignKey(User)\n created = models.DateTimeField(auto_now_add=True, verbose_name=\"Date de création\")\n picture = models.ImageField(verbose_name=\"Image\")\n types = models.ManyToManyField(Type, verbose_name=\"Type de jeu\")\n class Meta:\n verbose_name = 'Jeu'\n verbose_name_plural = 'Jeux'\n def __str__(self):\n return self.title\n\n@python_2_unicode_compatible\nclass Commentaire(models.Model):\n title = models.CharField(max_length=150, verbose_name=\"Titre du commentaire\")\n body = models.TextField(verbose_name=\"Commentaire\")\n slug = models.SlugField(unique=True, verbose_name=\"Slug\")\n author = models.ForeignKey(User, verbose_name=\"Auteur\")\n created = models.DateTimeField(auto_now_add=True, verbose_name=\"Date de création\")\n modified = models.DateTimeField(auto_now_add=True, verbose_name=\"Date de modification\")\n def __str__(self):\n return self.title","repo_name":"millecius/python","sub_path":"django/blog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"23847036739","text":"# -*- coding: utf-8 -*-\r\nfrom init import app\r\nfrom flask import render_template, flash, redirect, url_for, request, g\r\nfrom forms import LoginForm, SearchForm, BookEditForm, AddFormBook, DeleteFormBook, AddFormAuthor, DeleteFormAuthor, RegistrationForm\r\nfrom models import User, Book, Author\r\nfrom init import dbs\r\nfrom flask_login import login_user\r\nfrom init import login_manager\r\nfrom flask.ext.login import login_required, current_user, logout_user\r\n\r\n\r\n@login_manager.user_loader\r\ndef load_user(user_id):\r\n return User.query.get(user_id)\r\n\r\n\r\n@app.route(\"/\")\r\n@app.route(\"/index\")\r\ndef index():\r\n return render_template('index.html', user=current_user)\r\n\r\n\r\n@app.route(\"/logout\")\r\n@login_required\r\ndef logout():\r\n logout_user()\r\n flash('logged out')\r\n return redirect(url_for('index'))\r\n\r\n\r\n@app.route(\"/settings\")\r\n@login_required\r\ndef settings():\r\n flash(current_user.get_id())\r\n return redirect(url_for('index'))\r\n\r\n\r\n@app.route('/library')\r\ndef library():\r\n title = 'test'\r\n books = Book.query.all()\r\n return render_template('library.html',\r\n title=title,\r\n books=books,\r\n user=current_user)\r\n\r\n\r\n@app.route('/book/')\r\ndef book(param):\r\n current_book = Book.query.get(param)\r\n return render_template('book.html', book=current_book, user=current_user)\r\n\r\n\r\n@app.route('/registration', methods=['GET', 'POST'])\r\ndef register():\r\n form = RegistrationForm()\r\n if form.validate_on_submit():\r\n if User.query.filter_by(login=form.login.data).first():\r\n flash(u'Пользователь с таким логином уже существует')\r\n return redirect(url_for('register'))\r\n if form.password.data != form.confirm_password.data:\r\n flash(u'Пароли не совпадают')\r\n return redirect(url_for('register'))\r\n user = User(\r\n login=form.login.data,\r\n password=form.password.data\r\n )\r\n dbs.session.add(user)\r\n dbs.session.commit()\r\n login_user(user)\r\n flash(form.login.data + u', вы успешно зарегистрировались')\r\n return redirect(url_for('index'))\r\n return render_template('registration.html',\r\n form=form,\r\n user=current_user)\r\n\r\n\r\n@app.route('/login', methods=['GET', 'POST'])\r\ndef login():\r\n form = LoginForm()\r\n if form.validate_on_submit():\r\n user = User.query.filter_by(login=form.login.data).first()\r\n if user and user.password == form.password.data:\r\n login_user(user)\r\n flash(form.login.data + u', вы успешно авторизовались')\r\n return redirect(url_for('index'))\r\n elif user:\r\n flash('Неверный пароль')\r\n else:\r\n flash('Пользователя с таким логином не существует')\r\n return render_template('login.html',\r\n form=form,\r\n user=current_user)\r\n\r\n\r\n@app.route(\"/search\", methods=['GET', 'POST'])\r\ndef search():\r\n form = SearchForm()\r\n if form.validate_on_submit():\r\n if form.search_radio.data == 'book':\r\n books = Book.query.filter(Book.bookname.contains(form.search_attr.data)).all()\r\n if not books:\r\n flash(u\"Нет такой книги\")\r\n return render_template('search.html',\r\n form=form,\r\n user=current_user,\r\n books=books)\r\n else:\r\n authors = Author.query.filter(Author.authorname.contains(form.search_attr.data)).all()\r\n if not authors:\r\n flash(u\"Нет такого автора\")\r\n return render_template('search.html',\r\n form=form,\r\n user=current_user,\r\n authors=authors)\r\n return render_template('search.html',\r\n form=form,\r\n user=current_user)\r\n\r\n\r\n@app.route(\"/bookpreedit\")\r\ndef bookpreedit():\r\n return render_template('bookpreedit.html', user=current_user)\r\n\r\n\r\n@app.route(\"/authorpreedit\")\r\ndef authorpreedit():\r\n return render_template('authorpreedit.html', user=current_user)\r\n\r\n\r\n@app.route(\"/editbook\", methods=['GET', 'POST'])\r\ndef bookedit():\r\n form = BookEditForm()\r\n form.list_of_books.choices = [(book.id, book.bookname) for book in Book.query.all()]\r\n form.list_of_authors.choices = [(author.id, author.authorname) for author in Author.query.all()]\r\n book = Book.query.all()[0]\r\n if request.method == 'POST':\r\n if request.form['submit'] == u'Показать авторский состав выбранной книги':\r\n book = Book.query.get(form.list_of_books.data)\r\n return render_template('editing.html',\r\n form=form,\r\n user=current_user,\r\n book=book)\r\n if request.form['submit'] == u'Добавить выбранного автора в авторский состав выбранной книги':\r\n author = Author.query.get(form.list_of_authors.data)\r\n book = Book.query.get(form.list_of_books.data)\r\n book.authors.append(author)\r\n dbs.session.add(book)\r\n dbs.session.commit()\r\n return render_template('editing.html',\r\n form=form,\r\n user=current_user,\r\n book=book)\r\n if request.form['submit'] == u'Удалить выбранного автора из авторского состава выбранной книги':\r\n author = Author.query.get(form.list_of_authors.data)\r\n book = Book.query.get(form.list_of_books.data)\r\n if author in book.authors:\r\n book.authors.remove(author)\r\n dbs.session.add(book)\r\n dbs.session.commit()\r\n return render_template('editing.html',\r\n form=form,\r\n user=current_user,\r\n book=book)\r\n return render_template('editing.html',\r\n form=form,\r\n user=current_user,\r\n book=book)\r\n\r\n\r\n@app.route(\"/editbook1\", methods=['GET', 'POST'])\r\ndef authoredit():\r\n pass\r\n\r\n\r\n@app.route(\"/addbook\", methods=['GET', 'POST'])\r\ndef addbook():\r\n form = AddFormBook()\r\n if form.validate_on_submit():\r\n if Book.query.filter_by(bookname=form.name.data).first():\r\n flash(u'Эта книга уже есть в библиотеке')\r\n return redirect(url_for(\"addbook\"))\r\n book = Book(bookname=form.name.data)\r\n dbs.session.add(book)\r\n dbs.session.commit()\r\n flash(u'Книга:%s была добавлена в библиотеку' % book.bookname)\r\n return redirect(url_for(\"addbook\"))\r\n return render_template('addbook.html',\r\n form=form,\r\n user=current_user)\r\n\r\n\r\n@app.route(\"/deletebook\", methods=['GET', 'POST'])\r\ndef deletebook():\r\n form = DeleteFormBook()\r\n form.list_of_obj.choices = [(book.id, book.bookname) for book in Book.query.all()]\r\n if request.method == 'POST':\r\n if request.form['submit'] == u'Удалить книгу':\r\n book = Book.query.get(form.list_of_obj.data)\r\n dbs.session.delete(book)\r\n dbs.session.commit()\r\n flash(u'Книга:%s была удалена из библиотеки' % book.bookname)\r\n return redirect(url_for('deletebook'))\r\n if request.form['submit'] == u'Показать авторский состав выбранной книги':\r\n book = Book.query.get(form.list_of_obj.data)\r\n return render_template('deletebook.html',\r\n form=form,\r\n user=current_user,\r\n book=book)\r\n return render_template('deletebook.html',\r\n form=form,\r\n user=current_user)\r\n\r\n\r\n@app.route(\"/addauthor\", methods=['GET', 'POST'])\r\ndef addauthor():\r\n form = AddFormAuthor()\r\n if form.validate_on_submit():\r\n if Author.query.filter_by(authorname=form.name.data).first():\r\n flash(u'Этот автор уже есть в общем списке авторов')\r\n return redirect(url_for(\"addauthor\"))\r\n author = Author(authorname=form.name.data)\r\n dbs.session.add(author)\r\n dbs.session.commit()\r\n flash(u'Автор:%s был добавлен в общий список авторов.' % author.authorname )\r\n return redirect(url_for(\"addauthor\"))\r\n return render_template('addauthor.html',\r\n form=form,\r\n user=current_user)\r\n\r\n\r\n@app.route(\"/deleteauthor\", methods=['GET', 'POST'])\r\ndef deleteauthor():\r\n form = DeleteFormAuthor()\r\n form.list_of_obj.choices = [(author.id, author.authorname) for author in Author.query.all()]\r\n if request.method == \"POST\":\r\n if request.form['submit'] == u'Удалить автора':\r\n author = Author.query.get(form.list_of_obj.data)\r\n dbs.session.delete(author)\r\n dbs.session.commit()\r\n return redirect(url_for('deleteauthor'))\r\n if request.form['submit'] == u'Показать показать книги с этим автором':\r\n author = Author.query.get(form.list_of_obj.data)\r\n return render_template('deleteauthor.html',\r\n form=form,\r\n user=current_user,\r\n author=author)\r\n return render_template('deleteauthor.html',\r\n form=form,\r\n user=current_user)\r\n\r\n\r\n\r\n","repo_name":"nlkek/flasklibraryproject","sub_path":"flasktestlibrary/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"20580324855","text":"import os\nimport sys\nimport h5py\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import TensorDataset, DataLoader\nimport numpy as np\nfrom torch.cuda.amp import GradScaler, autocast\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n\nSCALE = True # True for mixed precision\n\n#%% Data set class\nclass ASCAD():\n def __init__(self, X, Y) -> None:\n self.X = X\n self.Y = Y\n self.X = self.X.view(dtype=np.uint8)\n\n def __len__(self):\n return len(self.X)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n trace = torch.tensor(self.X[idx]).int()\n label = torch.tensor(self.Y[idx]).int()\n label = self.Y[idx].astype('long')\n sample = {'trace': trace, 'label': label}\n return sample\n\ndef check_file_exists(file_path):\n\tfile_path = os.path.normpath(file_path)\n\tif os.path.exists(file_path) == False:\n\t\tprint(\"Error: provided file path '%s' does not exist!\" % file_path)\n\t\tsys.exit(-1)\n\treturn\n\n# def load_sca_model(model_file):\n# \tcheck_file_exists(model_file)\n# \ttry:\n# model = load_model(model_file)\n# \texcept:\n# \t\tprint(\"Error: can't load Keras model file '%s'\" % model_file)\n# \t\tsys.exit(-1)\n# \treturn model\n\n#### ASCAD helper to load profiling and attack data (traces and labels)\n# Loads the profiling and attack datasets from the ASCAD\n# database\ndef load_ascad(ascad_database_file, load_metadata=False):\n\tcheck_file_exists(ascad_database_file)\n\t# Open the ASCAD database HDF5 for reading\n\ttry:\n\t\tin_file = h5py.File(ascad_database_file, \"r\")\n\texcept:\n\t\tprint(\"Error: can't open HDF5 file '%s' for reading (it might be malformed) ...\" % ascad_database_file)\n\t\tsys.exit(-1)\n\t# Load profiling traces\n\tX_profiling = np.array(in_file['Profiling_traces/traces'], dtype=np.int8)\n\t# Load profiling labels\n\tY_profiling = np.array(in_file['Profiling_traces/labels'])\n\t# Load attacking traces\n\tX_attack = np.array(in_file['Attack_traces/traces'], dtype=np.int8)\n\t# Load attacking labels\n\tY_attack = np.array(in_file['Attack_traces/labels'])\n\tif load_metadata == False:\n\t\treturn (X_profiling, Y_profiling), (X_attack, Y_attack)\n\telse:\n\t\treturn (X_profiling, Y_profiling), (X_attack, Y_attack), (in_file['Profiling_traces/metadata'], in_file['Attack_traces/metadata'])\n\nEMBED = True\nREPORT = False\nMORELINEAR = True\nNEWLIN = False\nbatch_size = 20\n\nclass LSTMNet(nn.Module):\n def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5):\n super(LSTMNet, self).__init__()\n self.output_size = output_size\n self.n_layers = n_layers\n self.hidden_dim = hidden_dim\n if (EMBED):\n self.embedding = nn.Embedding(vocab_size, embedding_dim)\n self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=drop_prob, batch_first=True)\n else:\n self.lstm = nn.LSTM(700, hidden_dim, n_layers, dropout=drop_prob, batch_first=True)\n self.dropout = nn.Dropout(drop_prob)\n if (NEWLIN):\n self.fc1 = nn.Linear(hidden_dim, 1024)\n self.fc2 = nn.Linear(1024, 1024)\n self.fc3 = nn.Linear(1024, 1024)\n self.fc4 = nn.Linear(1024, 1024)\n self.fc = nn.Linear(1024, output_size)\n elif (MORELINEAR):\n self.fc1 = nn.Linear(hidden_dim, 4096)\n self.fc2 = nn.Linear(4096, 4096)\n self.fc = nn.Linear(4096, output_size)\n else:\n self.fc = nn.Linear(hidden_dim, output_size)\n \n # self.softmax = nn.Softmax()\n \n def forward(self, x, hidden):\n # x = x.long()\n # xt[:,:,2] = x[2]\n if (REPORT):\n print(\"input shape: {}\".format(x.shape))\n print(\"input: {}\".format(x))\n if (EMBED):\n embeds = self.embedding(x)\n if (REPORT):\n print(\"embeds shape: {}\".format(embeds.shape))\n print(\"embeds: {}\".format(embeds))\n lstm_out, hidden = self.lstm(embeds, hidden)\n else:\n xt = x.view(x.shape[0], 1, x.shape[1])\n # print(\"xt shape: {}\".format(xt.shape))\n lstm_out, hidden = self.lstm(xt, hidden)\n\n if (REPORT):\n print(\"lstm_out: {}\".format(lstm_out))\n lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim)\n if (REPORT):\n print(\"lstm_out_contig: {}\".format(lstm_out))\n \n out = self.dropout(lstm_out)\n if (REPORT):\n print(\"dropout: {}\".format(out))\n \n \n if (NEWLIN):\n out = self.fc1(out) \n out = self.fc2(out) \n out = self.fc3(out) \n out = self.fc4(out) \n out = self.fc(out)\n elif (MORELINEAR):\n out = self.fc1(out)\n out = self.fc2(out)\n out = self.fc(out)\n else:\n out = self.fc(out)\n \n # out = self.softmax(out)\n if (REPORT):\n print(\"fc: {}\".format(out))\n out = out.view(batch_size, -1)\n # out = out[:,-1]\n return out, hidden\n \n def init_hidden(self, batch_size):\n weight = next(self.parameters()).data\n hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().to(device),\n weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().to(device))\n return hidden\n\n#%% Training\nif __name__ == \"__main__\":\n dataset_root_dir = \"/home/vernam/dl-project/ASCAD/ATMEGA_AES_v1/\"\n #default parameters values\n ascad_database = dataset_root_dir + \"/ATM_AES_v1_fixed_key/ASCAD_data/ASCAD_databases/ASCAD.h5\"\n #load traces\n (X_profiling, Y_profiling), (X_attack, Y_attack) = load_ascad(ascad_database)\n\n\n\n X_train, X_val, y_train, y_val = train_test_split(X_profiling,Y_profiling, shuffle = True,test_size=0.20, random_state=33)\n\n train_data = ASCAD(X_train, y_train)\n val_data = ASCAD(X_val, y_val)\n test_data = ASCAD(X_attack, Y_attack)\n\n # load data sets\n train_loader = DataLoader(train_data, batch_size=batch_size,\n shuffle=True, num_workers=10) \n val_loader = DataLoader(val_data, batch_size=batch_size,\n shuffle=False, num_workers=10) \n\n vocab_size = 257\n output_size = 256\n embedding_dim = 400\n hidden_dim = 512\n n_layers = 2\n\n # torch.cuda.is_available() checks and returns a Boolean True if a GPU is available, else it'll return False\n is_cuda = torch.cuda.is_available()\n\n # If we have a GPU available, we'll set our device to GPU. We'll use this device variable later in our code.\n if is_cuda:\n device = torch.device(\"cuda:1\")\n else:\n device = torch.device(\"cpu\")\n # device = torch.device(\"cpu\")\n\n\n model = LSTMNet(vocab_size, output_size, embedding_dim, hidden_dim, n_layers).to(device)\n # model.to(device)\n\n lr=1e-3\n # criterion = nn.functional.cross_entropy()\n # criterion = nn.NLLLoss() \n # optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, betas=(0.9, 0.98), eps=1e-9)\n\n epochs = 50\n counter = 0\n print_every = 100\n clip = 5\n valid_loss_min = np.Inf\n\n torch.autograd.set_detect_anomaly(True)\n\n # epochs = 75\n # if is_cuda:\n # device.empty_cache()\n # device.memory_summary(device=None, abbreviated=False)\n\n ### training\n # train_model(X_profiling, Y_profiling, best_model, training_model, epochs, batch_size)\n\n train_losses_all = []\n val_losses_all = []\n\n # print(len(X_attack))\n model.train()\n if SCALE:\n scaler = GradScaler()\n\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', verbose=True)\n\n\n for epoch in range(epochs):\n h = model.init_hidden(batch_size)\n\n total_loss_train = 0\n total_loss_val = 0\n\n for i_train, data in enumerate(train_loader, 0):\n # print(\"train {}\".format(i))\n inputs = data['trace']\n labels = data['label']\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n counter += 1\n h = tuple([e.data for e in h])\n # if torch.cuda.is_available():\n # print(inputs)\n # inputs, labels = inputs.to(device), labels.to(device) \n # inputs, labels = inputs.to(device), labels.to(device)\n model.zero_grad()\n with autocast():\n output, h = model(inputs, h)\n # print(output.squeeze().shape)\n # print(output)\n # loss = criterion(output.squeeze(), labels.float())\n # loss = criterion(torch.log(output.squeeze()), labels)\n loss = nn.functional.cross_entropy(output.squeeze(), labels)\n total_loss_train += loss.item()\n\n\n if SCALE:\n scaler.scale(loss).backward()\n scaler.step(optimizer)\n scaler.update()\n else:\n loss.backward()\n optimizer.step()\n\n # loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), clip)\n # optimizer.step()\n\n if counter%print_every == 0:\n val_h = model.init_hidden(batch_size)\n val_losses = []\n model.eval()\n for i_val, data in enumerate(val_loader, 0):\n inp = data['trace'].to(device)\n lab = data['label'].to(device)\n\n val_h = tuple([each.data for each in val_h])\n # inp, lab = inp.to(device), lab.to(device)\n out, val_h = model(inp, val_h)\n # val_loss = criterion(torch.log_softmax(out.squeeze()).clamp(min=1e-4), lab)\n val_loss = nn.functional.cross_entropy(out.squeeze(), lab)\n val_losses.append(val_loss.item())\n total_loss_val += val_loss.item()\n\n model.train()\n print(\"Epoch: {}/{}...\".format(epoch+1, epochs),\n \"Step: {}...\".format(counter),\n \"Loss: {:.6f}...\".format(loss.item()),\n \"Val Loss: {:.6f}\".format(np.mean(val_losses)))\n if np.mean(val_losses) <= valid_loss_min:\n torch.save(model.state_dict(), '/home/vernam/dl-project/bert_sca/lstm_save/state_dict.pt')\n print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(valid_loss_min,np.mean(val_losses)))\n valid_loss_min = np.mean(val_losses)\n # avg_val_loss = total_loss_val / i_val\n\n train_losses_all.append(total_loss_train / i_train)\n val_losses_all.append(np.mean(val_losses))\n plt.plot(np.arange(epoch+1), np.array(train_losses_all), 'b', label='LSTM_Train_Loss')\n plt.plot(np.arange(epoch+1), np.array(val_losses_all), 'r', label='LSTM_Val_Loss')\n plt.savefig(\"/home/vernam/dl-project/bert_sca/lstm_save/lstm_loss.png\")\n plt.close()\n","repo_name":"richa-design/DeepLearning-Based-SideChannelAnalysis","sub_path":"src/lstm_lrscaler.py","file_name":"lstm_lrscaler.py","file_ext":"py","file_size_in_byte":11101,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"34551945362","text":"# -*- coding: utf-8 -*-\n#Question:\n#給一個字串,如果他任一排列組合,是否有回文的可能性\n#---------------------\n#Answer:\n#該種類的字母數量是偶數,則不影響回文\n#如果奇數的字母超過兩種,就不能構成回文了\n#----------------------\ntring = raw_input()\nstring = list(string)\ncollect = {}\nfound = True\n\nfor i in range(len(string)):\n if string[i] in collect.keys():\n collect[string[i]] +=1\n else:\n collect[string[i]] = 1 \n\nodd = 0\nfor i in collect.keys():\n if collect[i] % 2 != 0:\n odd += 1\n\nif odd > 1:\n found = False\n \n\n# Write the code to find the required palindrome and then assign the variable 'found' a value of True or False\n\nif not found:\n print(\"NO\")\nelse:\n print(\"YES\")","repo_name":"TonyPythoneer/hacker-rank","sub_path":"Algorithms/Warmup/Game_of_Thrones-I.py","file_name":"Game_of_Thrones-I.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"22729624188","text":"import SimpleITK as sitk\nimport torch\nimport torchio as tio\nfrom torchio.data.io import sitk_to_nib\n\nfrom ...utils import TorchioTestCase\n\n\nclass TestPad(TorchioTestCase):\n \"\"\"Tests for `Pad`.\"\"\"\n\n def test_pad(self):\n image = self.sample_subject.t1\n padding = 1, 2, 3, 4, 5, 6\n sitk_image = image.as_sitk()\n low, high = padding[::2], padding[1::2]\n sitk_padded = sitk.ConstantPad(sitk_image, low, high, 0)\n tio_padded = tio.Pad(padding, padding_mode=0)(image)\n sitk_tensor, sitk_affine = sitk_to_nib(sitk_padded)\n tio_tensor, tio_affine = sitk_to_nib(tio_padded.as_sitk())\n self.assert_tensor_equal(sitk_tensor, tio_tensor)\n self.assert_tensor_equal(sitk_affine, tio_affine)\n\n def test_nans_history(self):\n padded = tio.Pad(1, padding_mode=2)(self.sample_subject)\n again = padded.history[0](self.sample_subject)\n assert not torch.isnan(again.t1.data).any()\n\n def test_padding_modes(self):\n def padding_func():\n return\n\n for padding_mode in [0, *tio.Pad.PADDING_MODES, padding_func]:\n tio.Pad(0, padding_mode=padding_mode)\n\n with self.assertRaises(KeyError):\n tio.Pad(0, padding_mode='abc')\n\n def test_padding_mean_label_map(self):\n with self.assertWarns(RuntimeWarning):\n tio.Pad(1, padding_mode='mean')(self.sample_subject.label)\n","repo_name":"fepegar/torchio","sub_path":"tests/transforms/preprocessing/test_pad.py","file_name":"test_pad.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","stars":1864,"dataset":"github-code","pt":"44"} +{"seq_id":"40772653835","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : Rock Wayne \n# @Created : 2020-07-13 14:51:21\n# @Last Modified : 2020-07-13 14:51:21\n# @Mail : lostlorder@gmail.com\n# @Version : alpha-1.0\n\n\"\"\"\n# 设计一个方法,找出任意指定单词在一本书中的出现频率。 \n# \n# 你的实现应该支持如下操作: \n# \n# \n# WordsFrequency(book)构造函数,参数为字符串数组构成的一本书 \n# get(word)查询指定单词在书中出现的频率 \n# \n# \n# 示例: \n# \n# WordsFrequency wordsFrequency = new WordsFrequency({\"i\", \"have\", \"an\", \"apple\n# \", \"he\", \"have\", \"a\", \"pen\"});\n# wordsFrequency.get(\"you\"); //返回0,\"you\"没有出现过\n# wordsFrequency.get(\"have\"); //返回2,\"have\"出现2次\n# wordsFrequency.get(\"an\"); //返回1\n# wordsFrequency.get(\"apple\"); //返回1\n# wordsFrequency.get(\"pen\"); //返回1\n# \n# \n# 提示: \n# \n# \n# book[i]中只包含小写字母 \n# 1 <= book.length <= 100000 \n# 1 <= book[i].length <= 10 \n# get函数的调用次数不会超过100000 \n# \n# Related Topics 设计 哈希表 \n# 👍 7 👎 0\n\n\"\"\"\n\nimport collections\nfrom typing import List\n\nimport pytest\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass WordsFrequency:\n\n def __init__(self, book: List[str]):\n self.counter = collections.Counter(book)\n\n def get(self, word: str) -> int:\n return self.counter[word]\n\n\n# Your WordsFrequency object will be instantiated and called as such:\n# obj = WordsFrequency(book)\n# param_1 = obj.get(word)\n# leetcode submit region end(Prohibit modification and deletion)\n\ndef test_solution():\n wordsFrequency = WordsFrequency([\"i\", \"have\", \"an\", \"apple\", \"he\", \"have\", \"a\", \"pen\"])\n assert wordsFrequency.get(\"you\") == 0\n assert wordsFrequency.get(\"have\") == 2\n assert wordsFrequency.get(\"an\") == 1\n assert wordsFrequency.get(\"apple\") == 1\n assert wordsFrequency.get(\"pen\") == 1\n\n\nif __name__ == '__main__':\n pytest.main([\"-q\", \"--color=yes\", \"--capture=no\", __file__])\n","repo_name":"Wang-Yann/LeetCodeMe","sub_path":"python/CrackingTheCodingInterview_6/16_02_words-frequency-lcci.py","file_name":"16_02_words-frequency-lcci.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"16379698780","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 23 13:19:03 2021\n\n@author: jackhayley\n\"\"\"\n\nimport json\n\ntry:\n from .constants import TOOLS, TOOL_TYPES, resource_path\nexcept ValueError:\n from constants import TOOLS, TOOL_TYPES, resource_path\n\n\nclass Tool:\n\n def __init__(self, *args, **kwargs):\n if len(kwargs) == 0:\n self.data = args[1]\n return\n else:\n self.data = {}\n self.init_data(*args, **kwargs)\n\n def init_data(self, *args, **kwargs):\n self.data['id'] = self.get_id(*args)\n for kw in kwargs:\n self.data[kw] = kwargs[kw]\n print(self.data)\n\n def get_id(self, *args):\n text = TOOL_TYPES[args[0]]\n if (args[1][text]) >= 9:\n text += '_' + str(args[1][text] + 1)\n else:\n text += '_0' + str(args[1][text] + 1)\n return text\n\n def _insert_dict(m_obj1, m_obj2=('Diameter', 'Stepover', 'FRATE')):\n \"\"\"Generates job dictionary based on given values and keys. In this case the\n program utilizes its default case to give job dictionary based on cutting\n info for each material type\"\"\"\n x_1, y_1, z_1 = map(str, m_obj2)\n x_2, y_2, z_2 = map(float, m_obj1)\n return {x_1: x_2, y_1: y_2, z_1: z_2}\n\n\nclass _Standard(Tool):\n\n def __init__(self, *args, **kwargs):\n super().__init__('Tip-radius', *args, **kwargs)\n\n\nclass _Ball(Tool):\n\n def __init__(self, *args, **kwargs):\n super().__init__('Ball-nose', *args, **kwargs)\n\n\nclass _Drill(Tool):\n\n def __init__(self, *args, **kwargs):\n super().__init__('Drill', *args, **kwargs)\n\n\nclass ToolManager():\n toolTypes = {\"tip\": _Standard,\n \"bll\": _Ball,\n \"djt\": _Drill}\n\n def __init__(self):\n pass\n\n def add_tool(self):\n\n with open(TOOLS, 'r', encoding=\"utf-8\", errors=\"replace\") as file:\n current_tools = json.load(file)\n tool_info = input(\"Input tool info: \").split()\n tool_info[1:] = [float(info) for info in tool_info[1:]]\n\n tool = ToolManager.toolTypes[tool_info[0]](self.get_tool_types(\n current_tools),\n job='stamping',\n diameter=tool_info[1],\n radius=tool_info[2],\n stepdown=tool_info[3],\n stepover=tool_info[4],\n feedrate=tool_info[5],\n weight=tool_info[6])\n current_tools.append(tool.data)\n print(current_tools)\n file = open(TOOLS, 'w', encoding=\"utf-8\", errors=\"replace\")\n file.write(json.dumps(current_tools, sort_keys=False, indent=4))\n file.close()\n\n def get_tool_types(self, tools):\n types = {'tip': 0, 'bll': 0, 'djt': 0}\n for i_1, tool in enumerate(tools):\n for i_2, t_type in enumerate(list(types.keys())):\n if t_type in tool['id']:\n types[t_type] += 1\n return types\n\n def get_job_tools(self, job_type):\n with open(resource_path(TOOLS), 'r', encoding=\"utf-8\", errors=\"replace\") as file:\n tools = json.load(file)\n return_tools = []\n for tool in tools:\n if tool['job'] == job_type:\n return_tools.append(ToolManager.toolTypes[tool['id'][:3]](tool))\n print('Tool added:', return_tools[-1].data)\n\n return return_tools\n\n\n# =============================================================================\n# file = open(TOOLS, 'job',encoding=\"utf-8\", errors=\"replace\")\n# file.write(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))\n# file.close()\n# \n# file = open(TOOLS, 'r',encoding=\"utf-8\", errors=\"replace\")\n# print(file.read())\n# file.close()\n# =============================================================================\n\n# file = open(file_name, \"r\", encoding=\"utf-8\", errors=\"replace\")\n\n\nif __name__ == '__main__':\n # ToolManager.add_tool()\n tm = ToolManager()\n # while True:\n #\n # tm.add_tool()\n # if input(\"Continue? \") != '0': continue\n # break\n print(tm.get_job_tools('stamping'))\n pass\n","repo_name":"acheong08/Quote-Assistant","sub_path":"src/pttech/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":4149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"14830920697","text":"def floorSqrt(x):\n return(math.floor(x**(0.5)))\n\n#{ \n# Driver Code Starts\n#Initial Template for Python 3\n\nimport math\n\n\n\ndef main():\n T=int(input())\n while(T>0):\n \n x=int(input())\n \n print(floorSqrt(x))\n \n T-=1\n\n\nif __name__ == \"__main__\":\n main()\n# } Driver Code Ends\n","repo_name":"Utkarshmalik99/DSA-GeeksforGeeks","sub_path":"Searching/Square root.py","file_name":"Square root.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"9262572191","text":"import pygame\nfrom square import Square\nimport setup\nfrom button import Button\nfrom getcode import GetCode\n\n\nclass Manager:\n\n def __init__(self):\n self.sq = []\n self.trigger = False\n for i in range(20):\n self.sq.append([])\n for j in range(20):\n self.sq[i].append(Square(setup.BLANK_FIELD + i * setup.SIZE,\n setup.BLANK_FIELD + j * setup.SIZE,\n setup.SIZE))\n\n self.get_code_button = Button(578, 757, '../png/button_get.png')\n self.clear_button = Button(64, 757, '../png/button_delete.png')\n\n def draw(self, scene: pygame):\n for i in range(len(self.sq)):\n for j in range(len(self.sq[i])):\n self.sq[i][j].drawIJ(scene, setup.BLANK_FIELD + i * setup.SIZE, setup.BLANK_FIELD + j * setup.SIZE)\n # self.sq[i][j].draw(scene)\n\n self.get_code_button.draw(scene)\n self.clear_button.draw(scene)\n\n def get_xy_coordinate_from_mouse(self, x, y):\n p1 = (x - setup.BLANK_FIELD) // setup.SIZE\n p2 = (y - setup.BLANK_FIELD) // setup.SIZE\n return p1, p2\n\n def click(self, x, y):\n p1, p2 = self.get_xy_coordinate_from_mouse(x, y)\n if (p1 >= 0 and p1 < len(self.sq) and p2 >= 0 and p2 < len(self.sq[0])):\n self.sq[p1][p2].enabled = self.trigger\n\n def newMotion(self, x, y):\n p1, p2 = self.get_xy_coordinate_from_mouse(x, y)\n\n if (self.get_code_button.is_pressed(x, y)):\n GetCode().get_code(self.sq)\n\n if (self.clear_button.is_pressed(x, y)):\n for i in range(len(self.sq)):\n for j in range(len(self.sq[i])):\n self.sq[i][j].enabled = False\n\n\n # print(x, y)\n\n if (p1 >= 0 and p1 < len(self.sq) and p2 >= 0 and p2 < len(self.sq[0])):\n self.trigger = not self.sq[p1][p2].enabled\n\n # Вернёт True, если клетка закрашена\n def getEnabled(self, x, y):\n p1, p2 = self.get_xy_coordinate_from_mouse(x, y)\n if (p1 >= 0 and p1 < len(self.sq) and p2 >= 0 and p2 < len(self.sq[0])):\n return self.sq[p1][p2].enabled","repo_name":"Fox-Bella/nonogramms","sub_path":"editor/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"15174073143","text":"import os\r\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\"\r\nimport tensorflow as tf\r\nimport tensorflow.contrib.slim.nets as nets\r\nfrom PIL import Image\r\n\r\nclass ResNetDetector:\r\n def __init__(self, RootImageFolderPath, ModelLoadName, ImageWidth, ImageHeight, LabelNum):\r\n super().__init__()\r\n\r\n self.RootImageFolderPath = RootImageFolderPath\r\n self.ModelLoadName = ModelLoadName\r\n self.ImageWidth = ImageWidth\r\n self.ImageHeight = ImageHeight\r\n self.LabelNum = LabelNum\r\n\r\n if self.RootImageFolderPath[-1] != \"/\":\r\n self.RootImageFolderPath += \"/\"\r\n \r\n self.ImageFormart = [\"jpg\"]\r\n\r\n def detect(self, ImagePath):\r\n x = tf.placeholder(tf.float32, [None, self.ImageWidth, self.ImageHeight, 3])\r\n classes = [str(i) for i in range(self.LabelNum)] # 标签顺序\r\n\r\n classes = os.listdir(self.RootImageFolderPath)\r\n\r\n pred, end_points = nets.resnet_v2.resnet_v2_50(x, num_classes=self.LabelNum, is_training=True)\r\n pred = tf.reshape(pred, shape=[-1, self.LabelNum])\r\n a = tf.argmax(pred, 1)\r\n saver = tf.train.Saver()\r\n with tf.Session() as sess:\r\n sess.run(tf.global_variables_initializer())\r\n saver.restore(sess, self.ModelLoadName)\r\n\r\n img = Image.open(img_path)\r\n img = img.resize((self.ImageWidth, self.ImageHeight))\r\n img = tf.reshape(img, [1, self.ImageWidth, self.ImageHeight, 3])\r\n img1 = tf.reshape(img, [1, self.ImageWidth, self.ImageHeight, 3])\r\n img = tf.cast(img, tf.float32) / 255.0\r\n b_image, b_image_raw = sess.run([img, img1])\r\n t_label = sess.run(a, feed_dict={x: b_image})\r\n index_ = t_label[0]\r\n predict = classes[index_]\r\n print(predict)\r\n \r\n def detectOnFolder(self):\r\n sourceDatasetPath = self.RootImageFolderPath + \"resize_dataset/\"\r\n\r\n x = tf.placeholder(tf.float32, [None, self.ImageWidth, self.ImageHeight, 3])\r\n classes = [str(i) for i in range(self.LabelNum)] # 标签顺序\r\n\r\n classes = os.listdir(self.RootImageFolderPath + \"sources/\")\r\n\r\n pred, end_points = nets.resnet_v2.resnet_v2_50(x, num_classes=self.LabelNum, is_training=True)\r\n pred = tf.reshape(pred, shape=[-1, self.LabelNum])\r\n a = tf.argmax(pred, 1)\r\n saver = tf.train.Saver()\r\n with tf.Session() as sess:\r\n sess.run(tf.global_variables_initializer())\r\n saver.restore(sess, self.ModelLoadName)\r\n\r\n ImageFolderPath_list = os.listdir(sourceDatasetPath)\r\n\r\n currentImageFolderIndex = 0\r\n totalImageFolderNum = len(ImageFolderPath_list)\r\n for ImageFolderPath in ImageFolderPath_list:\r\n currentImageFolderIndex += 1\r\n currentImageFolderPath = sourceDatasetPath + ImageFolderPath + \"/\"\r\n if os.path.isdir(currentImageFolderPath):\r\n ImagePath_list = os.listdir(currentImageFolderPath)\r\n currentImageIndex = 0\r\n totalImageNum = len(ImagePath_list)\r\n print(\"====Folder of : \" + classes[currentImageFolderIndex - 1] + \"====\")\r\n for ImagePath in ImagePath_list:\r\n currentImageIndex += 1\r\n if not os.path.isdir(currentImageFolderPath + ImagePath):\r\n if ImagePath.split(\".\")[1] in self.ImageFormart:\r\n currentImagePath = currentImageFolderPath + ImagePath\r\n img = Image.open(currentImagePath)\r\n img = img.resize((self.ImageWidth, self.ImageHeight))\r\n img = tf.reshape(img, [1, self.ImageWidth, self.ImageHeight, 3])\r\n img1 = tf.reshape(img, [1, self.ImageWidth, self.ImageHeight, 3])\r\n img = tf.cast(img, tf.float32) / 255.0\r\n b_image, b_image_raw = sess.run([img, img1])\r\n t_label = sess.run(a, feed_dict={x: b_image})\r\n index_ = t_label[0]\r\n predict = classes[index_]\r\n print(predict)\r\n \r\nif __name__ == \"__main__\":\r\n label_list = os.listdir(os.getcwd() + \"/sources/\")\r\n\r\n resnet_detector = ResNetDetector(RootImageFolderPath=os.getcwd(), \\\r\n ModelLoadName=os.getcwd() + \"/models/train_sandstone.model-600\", \\\r\n ImageWidth=224, \\\r\n ImageHeight=224, \\\r\n LabelNum=7)\r\n \r\n resnet_detector.detectOnFolder()\r\n\r\n print(\"label : \")\r\n for i in range(len(label_list)):\r\n print(i, label_list[i])","repo_name":"565353780/filter-socket","sub_path":"src/Python/ResNet/resnet_detect.py","file_name":"resnet_detect.py","file_ext":"py","file_size_in_byte":4908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"35548499076","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 15 08:52:16 2021\n\n@author: chris.kerklaan\n\n#TODO:\n \n# The current threedi_model_checker has needs an 'migrated sqlite'. However,\nwhen you update the migrated sqlite, you increase\n \n\"\"\"\n\n# First-party imports\nimport shutil\nimport pathlib\nimport logging\nimport types\n\n# Third-party imports\nfrom osgeo import ogr\nfrom osgeo import osr\n\n# Local imports\nimport threedi_edits as te\nfrom threedi_edits.gis.vectorgroup import VectorGroup\nfrom threedi_edits.gis.vector import Vector\nfrom threedi_edits.threedi.vector import ThreediVector\nfrom threedi_edits.globals import SUPPORTED_THREEDI_VERSIONS\nfrom threedi_edits.threedi.constants import get_version\n\n# Globals\nFILE_PATH = pathlib.Path(__file__)\nEMPTY_SQLITE_PATH = str(\n FILE_PATH.parent / \"data\" / SUPPORTED_THREEDI_VERSIONS[0] / \"empty_klondike.sqlite\"\n)\nV = get_version(SUPPORTED_THREEDI_VERSIONS[0])\n\n# Drivers\nOGR_SQLITE_DRIVER = ogr.GetDriverByName(\"SQLite\")\n\n# Logger\nlogger = logging.getLogger(__name__)\n\n\nclass ThreediVectorGroup(VectorGroup):\n \"\"\"\n ThreediVectorGroup's makes it easier to read, write and copy threedi-objectes.\n params:\n ogr_ds: ogr.DataSource\n mode:\n 'write': Used to write a file\n 'empty': Returns an empty in-mem ogr threedi model\n 'memory': The threedimodel is copied into memory, makes speedy edits\n 'read': Used for reading a model only\n\n\n \"\"\"\n\n instance = \"threedi.vectorgroup.VectorGroup\"\n\n def __init__(self, ogr_ds: ogr.DataSource, mode=\"memory\"):\n\n self.ds = ogr_ds # must be here to ensure correct copying.\n if mode == \"write\":\n super().__init__(ogr_ds=ogr_ds, memory=False, write=True)\n elif mode == \"read\":\n super().__init__(ogr_ds=ogr_ds, memory=False, write=False)\n elif mode == \"empty\":\n super().__init__(ogr_ds=create_empty_model().ds, memory=False)\n elif mode == \"memory\":\n super().__init__(ogr_ds=self._copy(ogr_ds), memory=False)\n\n logger.debug(f\"Opened threedi model in {mode} mode\")\n\n self.srs = osr.SpatialReference()\n self.srs.ImportFromEPSG(4326)\n self.mode = mode\n\n def __str__(self):\n return \"3Di model\"\n\n def __repr__(self):\n return f\"({self.instance}) 3Di model\"\n\n def __iter__(self):\n for table_name in V.TABLES[\"all\"]:\n if table_name in self.layers:\n yield self._table(table_name)\n\n def _tables(self):\n tables = types.SimpleNamespace()\n for table in V.TABLES[\"all\"]:\n if table in V.TRANSLATE:\n setattr(tables, V.TRANSLATE[table], self._table(table))\n\n return tables\n\n def _table(self, table_name):\n return ThreediVector(self.ds, table_name)\n\n def __getitem__(self, table):\n return self._table(table)\n\n def __setitem__(self, table_name, ogr_layer):\n \"\"\"replaces an entire table\"\"\"\n self.ds.DeleteLayer(table_name)\n self.ds.CreateLayer(ogr_layer)\n\n def _copy(\n self, memory: bool = True, path: str = None, quiet=True\n ) -> ogr.DataSource:\n \"\"\"Copies the current either to memory or to a path\"\"\"\n if memory:\n output = create_empty_model()\n else:\n output = create_output_model(path)\n\n current_layers = output.layers\n for table in self:\n # Some layers are remove, so we are skipping some things.\n if table.name not in current_layers:\n continue\n if table.name in V.TABLES[\"skip\"]:\n continue\n\n table_output = output[table.name]\n subject = f\"Copying {table.name} ({table.count} rows)\"\n for feature in te.Progress(table, subject, quiet):\n table_output.add(\n items=feature.evaluate_types(),\n geometry=feature.geometry,\n fid=feature.fid,\n )\n table_output = None\n\n return output.ds\n\n def _write(self, path, quiet=False):\n \"\"\"\n Whilst copy layer is faster than iterating over every feature,\n we want check the feature on field types and use the sqlite constraints\n therefore iteration is chosen here\n \"\"\"\n self._copy(False, path, quiet)\n\n\ndef create_output_model(path):\n \"\"\"Creates an empty sqlite\"\"\"\n shutil.copyfile(EMPTY_SQLITE_PATH, path)\n output = ThreediVectorGroup(ogr.Open(path, 1), mode=\"write\")\n empty_tables = [\n \"v2_global_settings\",\n \"v2_aggregation_settings\",\n \"v2_numerical_settings\",\n \"schema_version\",\n ]\n\n for empty_table in empty_tables:\n table = output[empty_table]\n table.table\n for fid in table.fids:\n table.delete(fid)\n table = None\n\n return output\n\n\ndef create_empty_model():\n \"\"\"creates a ThreediModelBase from scratch\"\"\"\n group = VectorGroup.from_scratch(name=\"Threedi Model\")\n for name, threedi_property in V.Properties():\n\n # create vector, with the right geometry and fields\n if \"the_geom\" in threedi_property:\n geometry_type = threedi_property[\"the_geom\"][\"type\"]\n else:\n geometry_type = ogr.wkbUnknown\n\n vector = Vector.from_scratch(name, geometry_type, 4326)\n\n for i, (field_name, field_values) in enumerate(threedi_property.items()):\n if field_name in [\"connected_tables\", \"the_geom\", \"id\"]:\n continue\n vector.add_field(field_name, field_values[\"type\"])\n\n # add to the group\n group.add(vector, name)\n\n return group\n","repo_name":"threedi/threedi-edits","sub_path":"threedi_edits/threedi/vectorgroup.py","file_name":"vectorgroup.py","file_ext":"py","file_size_in_byte":5655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"71848757574","text":"import speech_recognition as sr\n\n\nclass User:\n \"\"\"\n A class used to represent a user of the assistant\n\n Attributes\n ----------\n engine : Engine\n a TTS engine\n\n Methods\n -------\n speak: str\n Sets a text for the engine to say\n \"\"\"\n\n def __init__(self):\n self._recognizer = sr.Recognizer()\n\n def speak(self):\n \"\"\"\n Wait for user commands\n \"\"\"\n\n with sr.Microphone() as source:\n self._recognizer.adjust_for_ambient_noise(source)\n print(\"Listening...\")\n audio = self._recognizer.listen(source)\n\n try:\n audio = self._recognizer.recognize_google(audio)\n print(\"Google Speech Recognition thinks you said \" + audio)\n exception = -1\n except sr.UnknownValueError as e:\n print(\"Google Speech Recognition could not understand audio: \", e)\n exception = 1\n except sr.RequestError as e:\n print(\"Could not request results from Google Speech Recognition service; {0}\".format(e))\n exception = 2\n \n return audio, exception\n","repo_name":"albaramosp/voiceAssistant","sub_path":"user/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"33910958715","text":"#!/usr/bin/env python3\n\n# get the flipped time for TABOO task 3.\n\n# for every thme, just substracted the largest time and get absolute value.\n\ndef flip_time(time_his_file, flipped_time_file):\n \"\"\"\n\n :param time_his_file: time history file\n :return:\n \"\"\"\n\n time_his_file = str(time_his_file)\n flipped_time_file = str(flipped_time_file)\n time = list()\n flipped_time = list()\n thickness = list()\n\n with open(time_his_file, 'r') as fip:\n # data = fip.readlines()\n for line in fip:\n line = line.split()\n time.append(float(line[0]))\n thickness.append(line[1])\n\n # print(time)\n # print(thickness)\n largest_time = max(time)\n # print(largest_time)\n\n for item in time:\n flipped_time.append(abs(item - largest_time))\n print(flipped_time)\n flipped_time.reverse()\n thickness.reverse()\n print(flipped_time)\n\n with open(flipped_time_file, 'w') as fop:\n length = len(flipped_time)\n\n if length != len(thickness):\n print('wrong!!! time and thickness should have same numbers')\n\n for i in range(length):\n fop.write(str(format(flipped_time[i], '.4f')).ljust(8))\n fop.write(thickness[i])\n fop.write('\\n')\n\n# flip_time('Wanghs_TH.dat', 'Wanghs_TH_flipped.dat')\nflip_time('Lambeck_TH_selected_abs.dat', 'Lambeck_TH_selected_abs_flipped.dat')","repo_name":"sangchengfang/timehistory","sub_path":"time_flip.py","file_name":"time_flip.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"27287377089","text":"import cv2\nimport numpy as np\nimport torch\n\ndef shiftImage(image):\n left_image = image[:, :,0:-1]\n right_image = image[:, :,1:]\n new_image = torch.abs(left_image - right_image).sum()\n # model suma de new image\n new_image = np.concatenate((new_image, image[:,-1].reshape(-1, 1)),axis=1)\n new_image = np.concatenate((image[:,0].reshape(-1, 1), new_image),axis=1)\n\n return new_image\n\ndef epe(output, target):\n return np.linalg.norm(output - target) / (output.shape[0] * output.shape[1])\n\noutput = np.random.rand(32, 384, 768)\ntarget = np.random.rand(32, 384, 768)\n\nprint(epe(output, target))\nprint(shiftImage(output).shape)\n\n\n","repo_name":"adbobes/DispNet","sub_path":"Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"24602587624","text":"import logging\n\nfrom taskcounter.db import SQL, Day, Task, Week, fn\nfrom taskcounter.enum import ResultColumn, WeekDay\nfrom taskcounter.model import DayModel, SettingModel\nfrom taskcounter.utility import seven_days_of_week, weekday_from_date\n\n\nclass WeekModel:\n \"\"\"Wrapper for the week model.\"\"\"\n\n def __init__(self, year, week_number, parent=None):\n \"\"\"Construct a week wrapper object.\"\"\"\n self.logger = logging.getLogger(__name__)\n self.parent = parent\n # get the default work time, to use it as this week value\n default_time = SettingModel.default_week_time()\n self.logger.info('Default time for new week: %s', default_time)\n self._week = Week.get_or_create(year=year,\n week_number=week_number,\n defaults={'minutes_to_work':\n default_time})[0]\n self.logger.debug('Week: %s', self._week)\n self.__create_days()\n\n @property\n def minutes_to_work(self):\n \"\"\"Get work time in minutes of this week instance.\"\"\"\n minutes = self._week.minutes_to_work\n self.logger.debug('Get minutes to work: %s', minutes)\n return minutes\n\n @minutes_to_work.setter\n def minutes_to_work(self, minutes_to_work):\n \"\"\"Set work time in minutes of this week instance.\"\"\"\n self.logger.debug('Set minutes to work: %s', minutes_to_work)\n self._week.minutes_to_work = minutes_to_work\n self._week.save()\n\n def __getitem__(self, week_day):\n \"\"\"\n Get item with bracket operator. Take a WeekDay value.\n\n Return a DayModel.\n \"\"\"\n if week_day in WeekDay:\n for day in (Day.select(Day)\n .join(Week)\n .where((Week.week_number == self._week.week_number) &\n (Week.year == self._week.year))\n .order_by(Day.date)):\n if week_day is weekday_from_date(day.date):\n day_model = DayModel(day.date, day.week, self.parent)\n self.logger.debug('Get day model: %s', day_model)\n return day_model\n return None\n\n def __create_days(self):\n \"\"\"Create the days of this week.\"\"\"\n for date_ in seven_days_of_week(self._week.year,\n self._week.week_number):\n DayModel(date_, self._week, self.parent)\n\n @property\n def minutes_of_week(self):\n \"\"\"Get the total time in minutes of week's tasks.\"\"\"\n minutes = (Task.select(fn.SUM((fn.strftime('%s', Task.end_time)\n - fn.strftime('%s', Task.start_time))\n .cast('real') / 60).alias('sum')\n ).join(Day)\n .where((Day.week == self._week)\n & Task.start_time.is_null(False)\n & Task.end_time.is_null(False)\n )\n .scalar())\n self.logger.debug('Get minutes of week: %s', minutes)\n return minutes or 0\n\n @property\n def total_time_to_work(self):\n \"\"\"Get the total time (minutes) to work for the entire period.\"\"\"\n # we ignore time of weeks that do not have tasks.\n minutes = (Week.select(fn.SUM(Week.minutes_to_work))\n .where(Week.id\n .in_(Week.select(Week.id).distinct()\n .join(Day).join(Task)\n .where(Task.start_time.is_null(False) &\n Task.end_time.is_null(False))))\n .scalar())\n self.logger.debug('Get total minutes to work: %s', minutes)\n return minutes or 0\n\n @property\n def total_time_worked(self):\n \"\"\"Get the total worked time (minutes) for the entire period.\"\"\"\n minutes = (Task.select(fn.SUM((fn.strftime('%s', Task.end_time)\n - fn.strftime('%s', Task.start_time))\n .cast('real') / 60).alias('sum')\n )\n .where(Task.start_time.is_null(False)\n & Task.end_time.is_null(False)\n )\n .scalar())\n self.logger.debug('Get total time worked: %s', minutes)\n return minutes or 0\n\n def week_summary(self, man_day_minutes):\n \"\"\"Get the week summary: tasks and total time in minutes.\"\"\"\n query = (Task.select(Task.name,\n fn.SUM((fn.strftime('%s', Task.end_time) -\n fn.strftime('%s', Task.start_time))\n .cast('real') / 60).alias('sum')\n )\n .join(Day)\n .where((Day.week == self._week)\n & Task.start_time.is_null(False)\n & Task.end_time.is_null(False)\n )\n .group_by(Task.name)\n .order_by(SQL('sum').desc()))\n\n tasks = self.__summary_from_query(man_day_minutes, query)\n self.logger.debug('Week summary: %s', tasks)\n return tasks\n\n def daily_summary(self, today_date, man_day_minutes):\n \"\"\"Get the day summary: tasks and total time in minutes.\"\"\"\n query = (Task.select(Task.name,\n fn.SUM((fn.strftime('%s', Task.end_time) -\n fn.strftime('%s', Task.start_time))\n .cast('real') / 60).alias('sum')\n )\n .join(Day)\n .where((Day.date == today_date)\n & Task.start_time.is_null(False)\n & Task.end_time.is_null(False)\n )\n .group_by(Task.name)\n .order_by(SQL('sum').desc()))\n\n tasks = self.__summary_from_query(man_day_minutes, query)\n self.logger.debug('Daily summary: %s', tasks)\n return tasks\n\n @staticmethod\n def __summary_from_query(man_day_minutes, query):\n \"\"\"Return the summary (tasks and total time in minutes) from an\n executed query.\"\"\"\n tasks = {}\n for counter, row in enumerate(query):\n task = {ResultColumn.Task: row.name, ResultColumn.Time: row.sum,\n ResultColumn.Decimal_Time: row.sum}\n if man_day_minutes:\n task[ResultColumn.Man_Day] = round(row.sum /\n man_day_minutes, 2)\n else:\n task[ResultColumn.Man_Day] = ''\n tasks[counter] = task\n return tasks\n","repo_name":"ardeidae/taskcounter","sub_path":"taskcounter/model/weekmodel.py","file_name":"weekmodel.py","file_ext":"py","file_size_in_byte":6843,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"44"} +{"seq_id":"31394611743","text":"# To be used with the following installation\n#\n# cmsrel CMSSW_10_6_20\n# cd CMSSW_10_6_20/src\n# cmsenv\n#\n#\n# git clone git@github.com:robervalwalsh/analysis-ntuplizer.git Analysis/Ntuplizer\n# scram b -j4\n#________________________________________________________________________________________________________________________________________________\n\nimport os\n\nimport FWCore.ParameterSet.Config as cms\n\nfrom Configuration.StandardSequences.Eras import eras\nfrom Configuration.Eras.Modifier_run2_jme_2017_cff import run2_jme_2017\n\n## Let it begin\nprocess = cms.Process('MssmHbb',eras.Run2_2017)\n\nprocess.options = cms.untracked.PSet(\n)\n\n# execution with 4cores\nprocess.options.numberOfThreads=cms.untracked.uint32(4)\n\n\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(100000)\n\nprocess.load('Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff')\nprocess.load('Configuration.Geometry.GeometryRecoDB_cff')\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')\nfrom Configuration.AlCa.GlobalTag import GlobalTag\nprocess.GlobalTag = GlobalTag(process.GlobalTag, '106X_dataRun2_v33')\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1000) )\n\n## TFileService\noutput_file = 'ntuple_test3-v5.root'\nprocess.TFileService = cms.Service('TFileService',\n fileName = cms.string(output_file)\n)\n\n## b tag algorithms\nfrom Analysis.Ntuplizer.NtuplizerBTag_cfi import *\n\n## Trigger information\nfrom Analysis.Ntuplizer.TriggerInfo_cfi import *\ntriggerInfo = triggerInfo('trigger_info_v5.yml')\n\n# Apply JES corrections\nprocess.load('Analysis.Ntuplizer.JetCorrections_cff')\n\n# Retrieve b jet regression correction factors\nprocess.load('Analysis.Ntuplizer.BJetRegression_cff')\n\n## Trigger filter: FOR DATA ONLY!!!\nprocess.triggerSelection = cms.EDFilter( 'TriggerResultsFilter',\n triggerInfo['triggerResultsFilter'],\n hltResults = cms.InputTag( 'TriggerResults', '', 'HLT' ),\n l1tResults = cms.InputTag( '' ),\n l1tIgnoreMask = cms.bool( False ),\n l1techIgnorePrescales = cms.bool( False ),\n daqPartitions = cms.uint32( 1 ),\n throw = cms.bool( False )\n)\n\n## Filter counter (maybe more useful for MC)\nprocess.TotalEvents = cms.EDProducer('EventCountProducer')\nprocess.FilteredEvents = cms.EDProducer('EventCountProducer')\n\n# ## Primary vertex\n# process.primaryVertexFilter = cms.EDFilter('VertexSelector',\n# src = cms.InputTag('offlineSlimmedPrimaryVertices'), # primary vertex collection name\n# cut = cms.string('!isFake && ndof > 4 && abs(z) <= 24 && position.Rho <= 2'), # ndof>thr=4 corresponds to sum(track_weigths) > (thr+3)/2 = 3.5 so typically 4 good tracks\n# filter = cms.bool(True), # otherwise it won't filter the events, just produce an empty vertex collection.\n# )\n\n\n## Ntuplizer\nprocess.MssmHbb = cms.EDAnalyzer('Ntuplizer',\n # Imported settings (always at the beginning)\n ntuplizerBTag,\n triggerInfo['ntuplizerTriggerPaths'],\n triggerInfo['ntuplizerL1Seeds'],\n triggerInfo['ntuplizerTriggerObjects'],\n\n MonteCarlo = cms.bool(False),\n ###################\n TotalEvents = cms.InputTag ('TotalEvents'),\n FilteredEvents = cms.InputTag ('FilteredEvents'),\n PatJets = cms.VInputTag( cms.InputTag('updatedJets'), ),\n JECRecords = cms.vstring ( 'AK4PFchs', ), # for the JEC uncertainties\n JERRecords = cms.vstring ( 'AK4PFchs', ), # for the JER uncertainties\n FixedGridRhoAll = cms.InputTag ('fixedGridRhoAll'),\n PatMuons = cms.VInputTag(cms.InputTag('slimmedMuons') ),\n PrimaryVertices = cms.VInputTag(cms.InputTag('offlineSlimmedPrimaryVertices') ),\n TriggerResults = cms.VInputTag(cms.InputTag('TriggerResults','','HLT') ),\n L1TJets = cms.VInputTag(cms.InputTag('caloStage2Digis','Jet','RECO'), ),\n L1TMuons = cms.VInputTag(cms.InputTag('gmtStage2Digis','Muon','RECO'), ),\n TriggerObjectStandAlone = cms.VInputTag(cms.InputTag('slimmedPatTrigger'), ),\n\n)\n\n## Do the stuff!\nprocess.p = cms.Path(process.TotalEvents +\n process.triggerSelection +\n process.FilteredEvents +\n process.MssmHbb,\n process.BJetRegression,\n process.AK4Jets,\n )\n\n## Inputs\nreadFiles = cms.untracked.vstring()\nsecFiles = cms.untracked.vstring()\nprocess.source = cms.Source ('PoolSource',fileNames = readFiles, secondaryFileNames = secFiles)\nreadFiles.extend( [\n\n# 302663\n'/store/data/Run2017D/BTagCSV/MINIAOD/UL2017_MiniAODv2-v1/270000/3A3DF494-008A-1D49-9A95-0D9E334783A2.root',\n#'/store/data/Run2017D/BTagCSV/MINIAOD/UL2017_MiniAODv2-v1/270000/8D468225-570E-6946-B269-E4F496256B62.root',\n#'/store/data/Run2017D/BTagCSV/MINIAOD/UL2017_MiniAODv2-v1/270000/AED0DB9D-D7D5-8846-8E16-6742202A0298.root',\n#'/store/data/Run2017D/BTagCSV/MINIAOD/UL2017_MiniAODv2-v1/270000/F8EE18DA-4D95-C44C-87EE-B265360F78BB.root',\n#'/store/data/Run2017D/BTagCSV/MINIAOD/UL2017_MiniAODv2-v1/270000/F9C56F58-979D-7049-9DFD-B60E80F9F28A.root',\n] );\n\n\nsecFiles.extend( [\n ] )\n\n# # ============ Output MiniAOD ======================\n# process.out = cms.OutputModule(\"PoolOutputModule\",\n# fileName = cms.untracked.string('patTuple.root'),\n# outputCommands = cms.untracked.vstring('keep *' )\n# )\n# process.outpath = cms.EndPath(process.out)\n# #\n## ============ JSON Certified data =============== BE CAREFUL!!!\n## Don't use with CRAB!!!\n# import FWCore.PythonUtilities.LumiList as LumiList\n# import FWCore.ParameterSet.Types as CfgTypes\n# process.source.lumisToProcess = CfgTypes.untracked(CfgTypes.VLuminosityBlockRange())\n# JSONfile = 'json_302663_reference.txt'\n# myLumis = LumiList.LumiList(filename = JSONfile).getCMSSWString().split(',')\n# process.source.lumisToProcess.extend(myLumis)\n","repo_name":"desy-cms/analysis-ntuplizer","sub_path":"test/archive/ntuplizer_106X_data_ul-2017-v5.py","file_name":"ntuplizer_106X_data_ul-2017-v5.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"18140209628","text":"# -*- coding: utf-8 -*-\n# @Time : 19-5-5 15:55\n# @Author : yanqi\n# @File : test_denoising.py\n# @IDE: PyCharm\n\"\"\"\ntest denoising model\n\"\"\"\nimport os\nimport os.path as ops\nimport argparse\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nfrom skimage.measure import compare_ssim\nfrom skimage.measure import compare_psnr\nimport sys\nsys.path.append('../')\nfrom attentive_gan_model import denoising_net\nfrom config import global_config\nfrom IPython.core.debugger import Tracer\n\nCFG = global_config.cfg\n\n\ndef init_args():\n \"\"\"\n :return:\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--image_path', type=str, default='E:/datasets/denoising/processing_data/blur_cliped_test', help='The input image path')\n parser.add_argument('--save_path', type=str, default='E:/datasets/denoising/results/attentive-gan/5.6_10000_post', help='The input image path')\n parser.add_argument('--weights_path', type=str, default='../model/denoising_gan/denoising_gan_2019-05-06-13-02-45.ckpt-10000', help='The model weights path')\n parser.add_argument('--label_path', type=str, default=None, help='The label image path')\n\n return parser.parse_args()\n\n\ndef minmax_scale(input_arr):\n \"\"\"\n :param input_arr:\n :return:\n \"\"\"\n min_val = np.min(input_arr)\n max_val = np.max(input_arr)\n\n output_arr = (input_arr - min_val) * 255.0 / (max_val - min_val)\n\n return output_arr\n\n\ndef test_model(image_path, save_path, weights_path, label_path=None):\n \"\"\"\n :param image_path:\n :param weights_path:\n :param label_path:\n :return:\n \"\"\"\n #assert ops.exists(image_path)\n\n input_tensor = tf.placeholder(dtype=tf.float32,\n shape=[CFG.TEST.BATCH_SIZE, CFG.TEST.IMG_HEIGHT, CFG.TEST.IMG_WIDTH, 3],\n name='input_tensor'\n )\n\n phase = tf.constant('test', tf.string)\n net = denoising_net.DenoisingNet(phase=phase)\n output, attention_maps = net.inference(input_tensor=input_tensor, name='denoising_net')\n\n # Set sess configuration\n sess_config = tf.ConfigProto(allow_soft_placement=False)\n sess_config.gpu_options.per_process_gpu_memory_fraction = CFG.TEST.GPU_MEMORY_FRACTION\n sess_config.gpu_options.allow_growth = CFG.TEST.TF_ALLOW_GROWTH\n sess_config.gpu_options.allocator_type = 'BFC'\n\n sess = tf.Session(config=sess_config)\n\n saver = tf.train.Saver()\n\n if not ops.exists(save_path):\n os.makedirs(save_path)\n\n # test images list\n images = os.listdir(image_path)\n\n # add filter as post process\n kernel_sharpen = np.array([\n [-1, -1, -1, -1, -1],\n [-1, 2, 2, 2, -1],\n [-1, 2, 8, 2, -1],\n [-1, 2, 2, 2, -1],\n [-1, -1, -1, -1, -1]]) / 8.0\n\n\n for i, img in enumerate(images):\n image_dir = ops.join(image_path, img)\n image = cv2.imread(image_dir, cv2.IMREAD_COLOR)\n # if image is GRAY image\n # image = cv2.imread(image_dir, cv2.IMREAD_GRAYSCALE)\n\n image = cv2.resize(image, (CFG.TEST.IMG_WIDTH, CFG.TEST.IMG_HEIGHT), interpolation=cv2.INTER_LINEAR)\n image_vis = image\n\n # if image is GRAY image\n #image_vis = image[:, :, np.newaxis]\n image = np.divide(np.array(image_vis, np.float32), 127.5) - 1.0\n\n label_image_vis = None\n if label_path is not None:\n labels = os.listdir(label_path)\n for label in labels:\n label_dir = ops.join(label_path, label)\n label_image = cv2.imread(label_dir, cv2.IMREAD_COLOR)\n # label_image = cv2.imread(label_dir, cv2.IMREAD_GRAYSCALE)\n # label_image = label_image[:, :, np.newaxis] #(512, 512, 1)\n label_image_vis = cv2.resize(\n label_image, (CFG.TEST.IMG_WIDTH, CFG.TEST.IMG_HEIGHT), interpolation=cv2.INTER_LINEAR)\n\n with sess.as_default():\n saver.restore(sess=sess, save_path=weights_path)\n\n output_image, atte_maps = sess.run(\n [output, attention_maps],\n feed_dict={input_tensor: np.expand_dims(image, 0)})\n\n output_image = output_image[0]\n for i in range(output_image.shape[2]):\n output_image[:, :, i] = minmax_scale(output_image[:, :, i])\n\n output_image = np.array(output_image, np.uint8)\n\n if label_path is not None:\n label_image_vis_gray = cv2.cvtColor(label_image_vis, cv2.COLOR_BGR2YCR_CB)[:, :, 0]\n output_image_gray = cv2.cvtColor(output_image, cv2.COLOR_BGR2YCR_CB)[:, :, 0]\n psnr = compare_psnr(label_image_vis_gray, output_image_gray)\n ssim = compare_ssim(label_image_vis_gray, output_image_gray)\n\n print('SSIM: {:.5f}'.format(ssim))\n print('PSNR: {:.5f}'.format(psnr))\n\n # merge src image, denoising image and post process image\n out_image = np.zeros((CFG.TEST.IMG_HEIGHT, CFG.TEST.IMG_WIDTH * 3, 3), dtype=np.uint8)\n\n # if image is GRAY image\n #out_image[:, :CFG.TEST.IMG_WIDTH] = image_vis[:, :, 0]\n out_image[:, :CFG.TEST.IMG_WIDTH] = image_vis\n\n # Tracer()()\n output_image_resize = cv2.resize(output_image, (CFG.TEST.IMG_WIDTH, CFG.TEST.IMG_HEIGHT), interpolation=cv2.INTER_LINEAR)\n out_image[:, CFG.TEST.IMG_WIDTH:CFG.TEST.IMG_WIDTH * 2] = output_image_resize\n\n output_sharpen = cv2.filter2D(output_image, -1, kernel_sharpen)\n output_sharpen_resize = cv2.resize(output_sharpen, (CFG.TEST.IMG_WIDTH, CFG.TEST.IMG_HEIGHT), interpolation=cv2.INTER_LINEAR)\n out_image[:, CFG.TEST.IMG_WIDTH * 2:] = output_sharpen_resize\n\n # save results\n # cv2.imwrite(save_path + '/' + img[:-4] + '_src_img.jpg', image_vis)\n # cv2.imwrite(save_path + '/' + img[:-4] + '_denoising_img.jpg', output_image)\n # cv2.imwrite(save_path + '/' + img[:-4] + '_denoising_post_img.jpg', output_sharpen)\n cv2.imwrite(save_path + '/' + img[:-4] + '_out.jpg', out_image)\n\n print('**************{} have tested over!**************'.format(img))\n\n print('_' * 50)\n print('All test images have tested successfully!')\n\nif __name__ == '__main__':\n # init args\n args = init_args()\n\n # test model\n test_model(args.image_path, args.save_path, args.weights_path, args.label_path)","repo_name":"yanqiAI/attentive-gan-denoising","sub_path":"tools/test_denoising.py","file_name":"test_denoising.py","file_ext":"py","file_size_in_byte":6463,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"44"} +{"seq_id":"33188728677","text":"import read_speed as rspeed\nimport RPi.GPIO as GPIO\nimport time\n\n#pins used for motors, first uses pwm, second does not\nmotorl = [13, 5] #left motor pins\nmotorr = [12, 6] #right motor pins\n\ndef setup():\n\tGPIO.setmode(GPIO.BCM)\n\tGPIO.setwarnings(False)\n\n\t#Set all motor pins as output\n\tGPIO.setup(motorl[0], GPIO.OUT)\n\tGPIO.setup(motorl[1], GPIO.OUT)\n\tGPIO.setup(motorr[0], GPIO.OUT)\n\tGPIO.setup(motorr[1], GPIO.OUT)\n\n\t#PWM setup\n\tglobal pwml\n\tglobal pwmr\n\tpwml = GPIO.PWM(motorl[0], 1000)\n\tpwmr = GPIO.PWM(motorr[0], 1000)\n\t\n\t#PWM start\n\tpwml.start(0)\n\tpwmr.start(0)\n\n\t#setup distancesensor, making object ultrasonic\n\t#global ultrasonic\n\t#ultrasonic = DistanceSensor(echo=ec, trigger=trig, max_distance=2.0)\n\n\t#all motor pins = 0\n\tGPIO.output(motorl[0], False)\n\tGPIO.output(motorl[1], False)\n\tGPIO.output(motorr[0], False)\n\tGPIO.output(motorr[1], False)\n\ndef destroy():\n\tpwml.stop()\n\tpwmr.stop()\n\tGPIO.output(motorl[0], GPIO.LOW)\n\tGPIO.output(motorr[0], GPIO.LOW)\n\tGPIO.cleanup()\n\ndef loop():\n\tpacel, pacer = 50, 50\n\twhile True:\n\t\tprint(str(pacel))\n\t\tprint(str(pacer))\n\t\tpwml.ChangeDutyCycle(pacel)\n\t\tGPIO.output(motorl[1], False)\n\t\tprint(\"hej\")\n\t\tpwmr.ChangeDutyCycle(pacer)\n\t\tGPIO.output(motorr[1], False)\n\t\tprint(\"hej\")\n\t\t# set both to a certain speed\n\t\ttime.sleep(0.5)\n\t\tlms=rspeed.read_speed(values=1, motor=0)[0]\n\t\tprint(\"hej\")\n\t\trms=rspeed.read_speed(values=1, motor=1)[0] #funkar ej\n\t\tprint(\"hej\")\n\t\tprint(str(rms))\n\t\tprint(str(lms))\n\t\tif lms= above_seconds:\n if callback is None:\n print('{:s} function took {:.3f} ms'.format(function.__name__, delta_secs * 1000.0))\n else:\n callback(delta_secs, *args)\n return result\n\n return wrapper\n\n return decorator\n\n\ndef time_wrapper_old(f):\n def wrapper(*args, **kwargs):\n import time\n start = time.time()\n ret = f(*args, **kwargs)\n end = time.time()\n print('{:s} function took {:.3f} ms'.format(f.__name__, (end - start) * 1000.0))\n return ret\n\n return wrapper\n","repo_name":"pynanto/pynanto","sub_path":"app/common/time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"14752084775","text":"#coding=utf-8\nfrom .Defines import *\nfrom .layers.utils.MultiInput import *\nfrom .layers.utils.MultiOutput import *\nfrom .layers.utils.Saver import *\nfrom . import solvers\nfrom . import wrapper\nimport functools\nimport signal\nimport weakref\n\ntry:\n import queue\nexcept:\n import Queue as queue\n\nclass Net(object):\n def __init__(self):\n self.topo = []\n self.layers = dict()\n self.set_solver(solvers.SGD())\n self.phase = TRAIN\n # signal.signal(signal.SIGINT, self.signal_handler) \n def set_loss(self, lossLayers):\n if type(lossLayers) != list:\n lossLayers = [lossLayers]\n\n # Count\n q = queue.Queue()\n for l in lossLayers: \n q.put(l)\n vis = set()\n cs = dict() # in degree\n\n while not q.empty():\n l = q.get()\n if l in vis:\n continue\n vis.add(l)\n # if layer l has input\n # Data.model is None\n # l.model may be Layer or MultiInput\n if l.model is not None:\n for md in l.model.input_models():\n cs[md] = cs.get(md, 0) + 1\n q.put(md)\n # Find\n q = queue.Queue()\n for l in lossLayers: \n q.put(l)\n st = []\n while not q.empty():\n l = q.get()\n st.append(l)\n if l.model is not None:\n for md in l.model.input_models():\n cs[md] -= 1\n if cs[md] == 0:\n q.put(md)\n self.topo = st[::-1]\n\n self.layers = dict()\n for l in self.topo:\n self.layers[l.name] = l\n l.forward_time = 0.0\n l.backward_time = 0.0\n self.forward_times = 0\n self.backward_times = 0\n # Avoid bidirection reference\n l.net = weakref.proxy(self)\n\n self.reshape()\n for l in lossLayers: \n l.dY = np.ones(l.Y.shape)\n self.init_solver()\n\n def set_solver(self, solver):\n self.solver = solver\n self.init_solver()\n def reshape(self):\n for l in self.topo:\n l.reshape()\n def init_solver(self):\n if self.solver is not None:\n for l in self.topo:\n self.solver.init(l)\n def forward(self):\n self.forward_times += 1\n for l in self.topo:\n t = time.time()\n l.forward()\n l.forward_time += time.time() - t \n def backward(self):\n self.backward_times += 1\n\n self.solver.update_lr(self.backward_times)\n\n for l in self.topo[::-1]:\n t = time.time()\n num_next_layers = len(l.next_layers)\n if num_next_layers > 0:\n if num_next_layers == 1:\n l.dY = l.next_layers[0].dX\n else:\n l.dY = np.zeros(l.Y.shape) \n for e in l.next_layers:\n l.dY += e.dX\n l.dY = l.dY.reshape(l.Y.shape)\n # compute the gradient dX of layer l\n l.backward()\n # use the solver to update weights of layer l\n if l.lr > 0:\n self.solver.update(l)\n\n l.backward_time += time.time() - t \n def time(self):\n if self.forward_times == 0 or self.backward_times == 0:\n return\n print (\"name\\t|forward_time\\t|backward_time\\t|forward_mean\\t|backward_mean\\t|forward_times: %d, backward_times: %d\" % (self.forward_times, self.backward_times))\n for l in self.topo:\n print (\"%s\\t|%f\\t|%f\\t|%f\\t|%f\" % (l.name, l.forward_time, l.backward_time, l.forward_time / self.forward_times, l.backward_time / self.backward_times))\n\n def save(self, filename):\n # Save the learning parameters of network by name\n print (\"Saving the parameters of the network to %s:\" % filename)\n save_layers(filename, self.topo, info = True)\n print (\"Saving Finished :-)\")\n\n def load(self, filename):\n # Load the learning parameters of network by name\n print (\"Loading the parameters of the network from %s:\" % filename)\n load_layers(filename, self.topo, info = True)\n print (\"Loading Finished :-)\")\n\n def __getitem__(self, name):\n return wrapper.get_layer(name)\n @property\n def lr(self):\n return self.solver.lr\n @lr.setter\n def lr(self, value):\n self.solver.base_lr = value\n def signal_handler(self, signal, frame):\n # TODO: Exit to Save\n print (\"Exit\")\n pass\n\n# For compatibility\nNet.setLoss = Net.set_loss\n","repo_name":"wkcn/mobula","sub_path":"mobula/Net.py","file_name":"Net.py","file_ext":"py","file_size_in_byte":4632,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"44"} +{"seq_id":"12219568051","text":"#---------------------------------\n# preparing for bounding box regression for 3D region proposls network\n# created in 26/12/2017\n#----------------------------------\n\nimport os\nimport sys\nBASE_DIR = os.path.dirname(__file__)\nsys.path.append(BASE_DIR)\nsys.path.append(os.path.join(BASE_DIR, '../config'))\nimport numpy as np\nfrom config import cfg\n\n\ndef bbox_transform(anch_boxes, gt_boxes):\n # getting the l,w,h,alpha,x,y,z from anchors\n anch_lengths = anch_boxes[:, 0]\n anch_widths = anch_boxes[:, 1]\n anch_heights = anch_boxes[:, 2]\n anch_alpha = anch_boxes[:, 3]\n anch_ctr_x = anch_boxes[:, 4]\n anch_ctr_y = anch_boxes[:, 5]\n anch_ctr_z = anch_boxes[:, 6]\n # getting the l,w,h,alpha,x,y,z from ground truths\n gt_lengths = gt_boxes[:, 0]\n gt_widths = gt_boxes[:, 1]\n gt_heights = gt_boxes[:, 2]\n gt_alpha = gt_boxes[:, 3]\n gt_ctr_x = gt_boxes[:, 4]\n gt_ctr_y = gt_boxes[:, 5]\n gt_ctr_z = gt_boxes[:, 6]\n\n targets_dx = ( gt_ctr_x - anch_ctr_x ) / anch_lengths\n targets_dy = ( gt_ctr_y - anch_ctr_y ) / anch_widths\n targets_dz = ( gt_ctr_z - anch_ctr_z ) / anch_heights\n targets_dl = np.log( gt_lengths / anch_lengths )\n targets_dw = np.log( gt_widths / anch_widths )\n targets_dh = np.log( gt_heights / anch_heights )\n targets_alpha= ( gt_alpha - anch_alpha ) / (np.pi/4)\n\n targets = np.vstack(\n\t(targets_dl, targets_dw, targets_dh, targets_alpha, targets_dx, targets_dy, targets_dz)).transpose()\n\n return targets\n\n\n\ndef bbox_transform_inv(pred_box, xyz):\n ##\n num_class = cfg.TRAIN.NUM_CLASSES\n num_regression = cfg.TRAIN.NUM_REGRESSION\n num_anchors = cfg.TRAIN.NUM_ANCHORS\n anchor_length = cfg.TRAIN.Anchors[0]\n anchor_width = cfg.TRAIN.Anchors[1]\n anchor_height = cfg.TRAIN.Anchors[2]\n anchor_alpha = cfg.TRAIN.Alpha\n temp_pred_box_l = np.array([ np.exp( pred_box[:,(x*num_regression)])*anchor_length for x in range(num_anchors)]).transpose(1,0)\n temp_pred_box_l = temp_pred_box_l.reshape(-1,1)\n temp_pred_box_w = np.array([ np.exp( pred_box[:,(x*num_regression+1)])*anchor_width for x in range(num_anchors)]).transpose(1,0)\n temp_pred_box_w = temp_pred_box_w.reshape(-1,1)\n temp_pred_box_h = np.array([ np.exp( pred_box[:,(x*num_regression+2)])*anchor_height for x in range(num_anchors)]).transpose(1,0)\n temp_pred_box_h = temp_pred_box_h.reshape(-1,1)\n temp_pred_box_alpha = np.array([ pred_box[:,(x*num_regression+3)]*np.pi/4+anchor_alpha[x,0] for x in range(num_anchors)]).transpose(1,0)\n temp_pred_box_alpha = temp_pred_box_alpha.reshape(-1,1)\n temp_pred_box_x = np.array([ pred_box[:,(x*num_regression+4)]*anchor_length + xyz[:,0] for x in range(num_anchors) ]).transpose(1,0)\n temp_pred_box_x = temp_pred_box_x.reshape(-1,1)\n temp_pred_box_y = np.array([ pred_box[:,(x*num_regression+5)]*anchor_width + xyz[:,1] for x in range(num_anchors) ]).transpose(1,0)\n temp_pred_box_y = temp_pred_box_y.reshape(-1,1)\n temp_pred_box_z = np.array([ pred_box[:,(x*num_regression+6)]*anchor_height + xyz[:,2] for x in range(num_anchors) ]).transpose(1,0)\n temp_pred_box_z = temp_pred_box_z.reshape(-1,1)\n\n all_box = np.hstack((temp_pred_box_l, temp_pred_box_w, temp_pred_box_h, temp_pred_box_alpha, temp_pred_box_x, temp_pred_box_y, temp_pred_box_z))\n\n return all_box\n","repo_name":"xuyongzhi/dynamic_pointnet","sub_path":"utils_xyz/bbox_transform.py","file_name":"bbox_transform.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"12214640148","text":"import pickle\nimport pytest\nimport okta.models as models\n\n\ndef test_attribute_case():\n \"\"\"Verify UserProfile can handle different case for basic and custom attributes.\"\"\"\n first_name = 'TestFirstName'\n last_name = 'TestLastName'\n custom_attr = 'TestCustomAttr'\n config = {'firstName': first_name,\n 'lastName': last_name,\n 'CustomAttr': custom_attr}\n profile = models.UserProfile(config)\n assert profile.first_name == first_name\n assert profile.firstName == first_name\n assert profile.last_name == last_name\n assert profile.lastName == last_name\n assert profile.display_name is None\n assert profile.displayName is None\n assert profile.CustomAttr == custom_attr\n\n display_name = 'TestName'\n profile.displayName = display_name\n assert profile.display_name == display_name\n\n new_display_name = 'NewTestName'\n profile.display_name = new_display_name\n assert profile.displayName == new_display_name\n\n new_custom_attr = 'NewCustomAttr'\n profile.CustomAttr = new_custom_attr\n\n req_format = profile.request_format()\n assert req_format['CustomAttr'] == new_custom_attr\n assert req_format['firstName'] == first_name\n assert req_format['lastName'] == last_name\n assert req_format['displayName'] == new_display_name\n\n\ndef test_profile_serializing():\n \"\"\"Verify UserProfile can be serialized and deserialized with pickle library.\"\"\"\n first_name = 'TestFirstName'\n last_name = 'TestLastName'\n custom_attr = 'TestCustomAttr'\n config = {'firstName': first_name,\n 'lastName': last_name,\n 'CustomAttr': custom_attr}\n profile = models.UserProfile(config)\n pickled_profile = pickle.dumps(profile)\n unpickled_profile = pickle.loads(pickled_profile)\n assert isinstance(unpickled_profile, models.UserProfile)\n assert profile.as_dict() == unpickled_profile.as_dict()\n","repo_name":"okta/okta-sdk-python","sub_path":"tests/unit/test_user_profile.py","file_name":"test_user_profile.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","stars":219,"dataset":"github-code","pt":"44"} +{"seq_id":"43969850651","text":"def ft_map(fct, lst):\n\tresult = []\n\tfor i in lst:\n\t\tresult.append(fct(i))\n\treturn result\n\ndef add(n):\n\treturn (n + n)\n\nnumbers = [1, 2, 3, 4]\nprint (numbers)\nresult = ft_map(add, numbers)\nprint(result)\n","repo_name":"mcraipea/Bootcamp__python","sub_path":"Day_02/ex00/ft_map.py","file_name":"ft_map.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"7088406676","text":"from math import sqrt\n\ndef main():\n (n, k) = map(int, input().split(' '))\n if k > n:\n return -1\n s = set()\n a = []\n b = []\n for i in range(1, int(sqrt(n)) + 1):\n if n % i == 0:\n if i not in s:\n a.append(i)\n s.add(i)\n if n // i not in s:\n b.append(n // i)\n s.add(n // i)\n a = a + b[::-1]\n ret = -1\n try:\n ret = a[k - 1]\n except Exception as e:\n ret = -1\n return ret\n\nprint(main())\n","repo_name":"austinschwartz/Competitive-Programming","sub_path":"codeforces/0762A_-_k-th_Divisor/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"30335822277","text":"import numpy as np\nfrom graph import Graph\n\n\ndef whatToConnect(matrix, rows, cols):\n \"\"\"\n matrix : stores the id of each node representing each cell\n\n returns dictionary\n\n connections - dictionary\n rows : [all the ids in the rows]\n cols : [all the ids in the cols]\n blocks : [all the ids in the block]\n\n ** to be connected to the head.\n \"\"\"\n connections = dict()\n\n connections[\"rows\"] = [matrix[rows][c] for c in range(cols + 1, 9)] # ROWS\n connections[\"cols\"] = [matrix[r][cols] for r in range(rows + 1, 9)] # COLS\n connections[\"blocks\"] = [matrix[x][y] for x in range(3 * (rows // 3), 3 * (rows // 3) + 3)\n for y in range(3 * (cols // 3), 3 * (cols // 3) + 3) if matrix[x][y] not in\n matrix[rows, :] and matrix[x][y] not in matrix[:, cols]] # BLOCKS\n return connections\n\n\nclass SudokuConnections:\n def __init__(self):\n\n self.graph = Graph() # Graph Object\n\n self.rows = 9\n self.cols = 9\n self.total_blocks = self.rows * self.cols # 81\n\n self.__generateGraph() # Generates all the nodes\n self.connectEdges() # connects all the nodes according to sudoku constraints\n\n self.allIds = self.graph.getAllNodesIds() # storing all the ids in a list\n\n def __generateGraph(self):\n \"\"\"\n Generates nodes with id from 1 to 81.\n Both inclusive\n \"\"\"\n for idx in range(1, self.total_blocks + 1):\n self.graph.addNode(idx)\n\n def connectEdges(self):\n \"\"\"\n Connect nodes according to Sudoku Constraints :\n\n # ROWS\n from start of each id number connect all the successive numbers till you reach a multiple of 9\n\n\n # COLS (add 9 (+9))\n from start of id number. +9 for each connection till you reach a number >= 73 and <= 81\n\n # BLOCKS\n Connect all the elements in the block which do not come in the same column or row.\n 1 2 3\n 10 11 12\n 19 20 21\n\n 1 -> 11, 12, 20, 21\n 2 -> 10, 19, 12, 21\n 3 -> 10, 11, 19, 20\n Similarly for 10, 11, 12, 19, 20, 21.\n\n \"\"\"\n matrix = np.arange(1, self.total_blocks + 1).reshape((self.rows, self.cols))\n head_connections = dict() # head : connections\n for row in range(self.rows):\n for col in range(self.cols):\n head = matrix[row][col] # id of the node\n connections = whatToConnect(matrix, row, col)\n head_connections[head] = connections\n # connect all the edges\n self.__connectThose(head_connections=head_connections)\n\n def __connectThose(self, head_connections):\n for head in head_connections.keys(): # head is the start idx\n connections = head_connections[head]\n for key in connections: # get list of all the connections\n for v in connections[key]:\n self.graph.addEdge(src=head, dst=v)\n\n\ndef test_whatToConnect():\n\n a = b = 9\n matrix = np.arange(1, a * b + 1).reshape((a, b))\n rows = np.random.choice(a=np.arange(a), size=[])\n cols = np.random.choice(a=np.arange(b), size=[])\n\n assert type(whatToConnect(matrix, rows, cols)) == dict\n assert len(whatToConnect(matrix, rows, cols).keys()) == 3\n assert list(whatToConnect(matrix, rows, cols).keys()) == [\"rows\", \"cols\", \"blocks\"]\n\n\nif __name__ == \"__main__\":\n\n sudoku = SudokuConnections()\n\n for i in sudoku.graph.getAllNodesIds():\n print(i, \"Connected to->\", sudoku.graph.allNodes[i].getConnections())\n\n test_whatToConnect()\n","repo_name":"popryho/pattern-recogniton","sub_path":"lab4/sudoku_connections.py","file_name":"sudoku_connections.py","file_ext":"py","file_size_in_byte":3613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"32904871806","text":"import sys\ninput = sys.stdin.readline\nn = int(input())\nnum = -1\nstr = \"\"\nfor i in range (0,n) :\n arr = input().split(\" \")\n a = arr[0]\n b = int(arr[1])\n if num == b and str > a :\n str = a\n elif num < b :\n num = b\n str = a\nprint(str)\n","repo_name":"nahwasa/BOJ_BaekjoonOnlineJudge","sub_path":"20100/BOJ_20124.py","file_name":"BOJ_20124.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"44"} +{"seq_id":"43184636868","text":"movies = [\n (\"Eternal Sunshine of the Spotless Mind\", 20000000),\n (\"Memento\", 9000000),\n (\"Requiem for a Dream\", 4500000),\n (\"Pirates of the Caribbean: On Stranger Tides\", 379000000),\n (\"Avengers: Age of Ultron\", 365000000),\n (\"Avengers: Endgame\", 356000000),\n (\"Incredibles 2\", 200000000)\n]\n\n\nnumToAdd = int(input(\"How many more movies would you like to add? \"))\n\nfor i in range(numToAdd):\n title = input(\"Enter the title of the movie to add \")\n budget = int(input(\"Enter the budget of the movie to add \"))\n new_movie = (title, budget)\n movies.append(new_movie)\n\n\ntotal = 0\n\nfor movie in movies:\n total = total + movie[1]\n\naverage = total / len(movies)\nprint(average)\n\ncount = 0\nfor movie in movies:\n if movie[1] > average:\n diff = movie[1] - average\n print(f\"The amount {movie[0]} is above the average budget is ${diff}\")\n count += 1\n\n\nprint(f\"There were {count} movies above the average budget\")\n\n","repo_name":"mathias314/programmingPractice","sub_path":"personalProblems/pythonReview/movieBudgets/movieBudgets.py","file_name":"movieBudgets.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"40931385273","text":"def lookForMatch(array1, array2):\n arrayDict = {}\n \n for elem in array1:\n arrayDict[elem] = True\n \n\n for elem in array2:\n if arrayDict.get(elem):\n return True\n\n return False\n\nprint(lookForMatch([5], [7,6,8,11,9, 1]))\n\n# O (a + b)\n","repo_name":"gabriel-bishop/interview-practice","sub_path":"1. containsCommonItem.py","file_name":"1. containsCommonItem.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"26642420005","text":"#!/usr/bin/env python\r\n\"\"\"Process Huang's wireframe dataset for L-CNN network\r\nUsage:\r\n dataset/wireframe.py \r\n dataset/wireframe.py (-h | --help )\r\n\r\nExamples:\r\n python dataset/wireframe.py /datadir/wireframe Good/wireframe\r\n python dataset/wireframe_line.py /home/dxl/Data/wireframe_raw\r\n\r\nArguments:\r\n Original Good directory of Huang's wireframe dataset\r\n Directory of the output\r\n\r\nOptions:\r\n -h --help Show this screen.\r\n\"\"\"\r\n\r\nimport os\r\nimport sys\r\nimport json\r\nfrom itertools import combinations\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport skimage.draw\r\nimport matplotlib.pyplot as plt\r\nfrom docopt import docopt\r\nfrom scipy.ndimage import zoom\r\n\r\ntry:\r\n sys.path.append(\".\")\r\n sys.path.append(\"..\")\r\n from FClip.utils import parmap\r\nexcept Exception:\r\n raise\r\n\r\n\r\ndef inrange(v, shape):\r\n return 0 <= v[0] < shape[0] and 0 <= v[1] < shape[1]\r\n\r\n\r\ndef to_int(x):\r\n return tuple(map(int, x))\r\n\r\n\r\ndef save_heatmap(prefix, image, lines):\r\n im_rescale = (512, 512)\r\n heatmap_scale = (128, 128)\r\n\r\n fy, fx = heatmap_scale[1] / image.shape[0], heatmap_scale[0] / image.shape[1]\r\n\r\n lcmap = np.zeros(heatmap_scale, dtype=np.float32) # (128, 128)\r\n lcoff = np.zeros((2,) + heatmap_scale, dtype=np.float32) # (2, 128, 128)\r\n lleng = np.zeros(heatmap_scale, dtype=np.float32) # (128, 128)\r\n angle = np.zeros(heatmap_scale, dtype=np.float32) # (128, 128)\r\n\r\n # the coordinate of lines can not equal to 128 (less than 128).\r\n lines[:, :, 0] = np.clip(lines[:, :, 0] * fx, 0, heatmap_scale[0] - 1e-4)\r\n lines[:, :, 1] = np.clip(lines[:, :, 1] * fy, 0, heatmap_scale[1] - 1e-4)\r\n lines = lines[:, :, ::-1] # change position of x and y --> (r, c)\r\n\r\n for v0, v1 in lines:\r\n v = (v0 + v1) / 2\r\n vint = to_int(v)\r\n lcmap[vint] = 1\r\n lcoff[:, vint[0], vint[1]] = v - vint - 0.5\r\n lleng[vint] = np.sqrt(np.sum((v0 - v1) ** 2)) / 2 # L\r\n\r\n if v0[0] <= v[0]:\r\n vv = v0\r\n else:\r\n vv = v1\r\n\r\n # the angle under the image coordinate system (r, c)\r\n # theta means the component along the c direction on the unit vector\r\n if np.sqrt(np.sum((vv - v) ** 2)) <= 1e-4:\r\n continue\r\n angle[vint] = np.sum((vv - v) * np.array([0., 1.])) / np.sqrt(np.sum((vv - v) ** 2)) # theta\r\n\r\n # the junction coordinate(image coordinate system) of line can be recovered by follows:\r\n # direction = [-sqrt(1-theta^2), theta]\r\n # (-sqrt(1-theta^2) means the component along the r direction on the unit vector, it always negative.)\r\n # center = coordinate(lcmap) + offset + 0.5\r\n # J = center (+-) direction * lleng (+-) means two end points\r\n\r\n image = cv2.resize(image, im_rescale)\r\n\r\n # plt.figure()\r\n # plt.imshow(image)\r\n # for v0, v1 in lines:\r\n # plt.plot([v0[1] * 4, v1[1] * 4], [v0[0] * 4, v1[0] * 4])\r\n # plt.savefig(f\"dataset/{os.path.basename(prefix)}_line.png\", dpi=200), plt.close()\r\n # return\r\n\r\n # coor = np.argwhere(lcmap == 1)\r\n # for yx in coor:\r\n # offset = lcoff[:, int(yx[0]), int(yx[1])]\r\n # length = lleng[int(yx[0]), int(yx[1])]\r\n # theta = angle[int(yx[0]), int(yx[1])]\r\n #\r\n # center = yx + offset\r\n # d = np.array([-np.sqrt(1-theta**2), theta])\r\n # plt.scatter(center[1]*4, center[0]*4, c=\"b\")\r\n #\r\n # plt.arrow(center[1]*4, center[0]*4, d[1]*length*4, d[0]*length*4,\r\n # length_includes_head=True,\r\n # head_width=15, head_length=25, fc='r', ec='b')\r\n\r\n # plt.savefig(f\"{prefix}_line.png\", dpi=200), plt.close()\r\n\r\n # plt.subplot(122), \\\r\n # plt.imshow(image)\r\n # coor = np.argwhere(lcmap == 1)\r\n # for yx in coor:\r\n # offset = lcoff[:, int(yx[0]), int(yx[1])]\r\n # length = lleng[int(yx[0]), int(yx[1])]\r\n # theta = angle[int(yx[0]), int(yx[1])]\r\n #\r\n # center = yx + offset\r\n # d = np.array([-np.sqrt(1-theta**2), theta])\r\n #\r\n # n0 = center + d * length\r\n # n1 = center - d * length\r\n # plt.plot([n0[1] * 4, n1[1] * 4], [n0[0] * 4, n1[0] * 4])\r\n # plt.savefig(f\"{prefix}_line.png\", dpi=100), plt.close()\r\n\r\n np.savez_compressed(\r\n f\"{prefix}_line.npz\",\r\n # aspect_ratio=image.shape[1] / image.shape[0],\r\n lcmap=lcmap,\r\n lcoff=lcoff,\r\n lleng=lleng,\r\n angle=angle,\r\n )\r\n cv2.imwrite(f\"{prefix}.png\", image)\r\n\r\n\r\ndef coor_rot90(coordinates, center, k):\r\n\r\n # !!!rotate the coordinates 90 degree anticlockwise on image!!!!\r\n\r\n # (x, y) --> (p-q+y, p+q-x) means point (x,y) rotate 90 degree clockwise along center (p,q)\r\n # but, the y direction of coordinates is inverse, not up but down.\r\n # so it equals to rotate the coordinate anticlockwise.\r\n\r\n # coordinares: [n, 2]; center: (p, q) rotation center.\r\n # coordinates and center should follow the (x, y) order, not (h, w).\r\n new_coor = coordinates.copy()\r\n p, q = center\r\n for i in range(k):\r\n x = p - q + new_coor[:, 1:2]\r\n y = p + q - new_coor[:, 0:1]\r\n new_coor = np.concatenate([x, y], 1)\r\n return new_coor\r\n\r\n\r\ndef prepare_rotation(image, lines):\r\n heatmap_scale = (512, 512)\r\n\r\n fy, fx = heatmap_scale[1] / image.shape[0], heatmap_scale[0] / image.shape[1]\r\n\r\n # the coordinate of lines can not equal to 128 (less than 128).\r\n lines[:, :, 0] = np.clip(lines[:, :, 0] * fx, 0, heatmap_scale[0] - 1e-4)\r\n lines[:, :, 1] = np.clip(lines[:, :, 1] * fy, 0, heatmap_scale[1] - 1e-4)\r\n\r\n im = cv2.resize(image, heatmap_scale)\r\n\r\n return im, lines\r\n\r\n\r\ndef main():\r\n args = docopt(__doc__)\r\n data_root = args[\"\"]\r\n data_output = args[\"\"]\r\n\r\n os.makedirs(data_output, exist_ok=True)\r\n for batch in [\"train\", \"valid\"]: # \"train\", \"valid\"\r\n anno_file = os.path.join(data_root, f\"{batch}.json\")\r\n\r\n with open(anno_file, \"r\") as f:\r\n dataset = json.load(f)\r\n\r\n def handle(data):\r\n im = cv2.imread(os.path.join(data_root, \"images\", data[\"filename\"]))\r\n prefix = data[\"filename\"].split(\".\")[0]\r\n lines = np.array(data[\"lines\"]).reshape(-1, 2, 2)\r\n os.makedirs(os.path.join(data_output, batch), exist_ok=True)\r\n path = os.path.join(data_output, batch, prefix)\r\n\r\n lines0 = lines.copy()\r\n save_heatmap(f\"{path}_0\", im[::, ::], lines0)\r\n\r\n if batch != \"valid\":\r\n lines1 = lines.copy()\r\n lines1[:, :, 0] = im.shape[1] - lines1[:, :, 0]\r\n im1 = im[::, ::-1]\r\n save_heatmap(f\"{path}_1\", im1, lines1)\r\n\r\n lines2 = lines.copy()\r\n lines2[:, :, 1] = im.shape[0] - lines2[:, :, 1]\r\n im2 = im[::-1, ::]\r\n save_heatmap(f\"{path}_2\", im2, lines2)\r\n\r\n lines3 = lines.copy()\r\n lines3[:, :, 0] = im.shape[1] - lines3[:, :, 0]\r\n lines3[:, :, 1] = im.shape[0] - lines3[:, :, 1]\r\n im3 = im[::-1, ::-1]\r\n save_heatmap(f\"{path}_3\", im3, lines3)\r\n\r\n im4, lines4 = prepare_rotation(im, lines.copy())\r\n lines4 = coor_rot90(lines4.reshape((-1, 2)), (im4.shape[1] / 2, im4.shape[0] / 2), 1) # rot90 on anticlockwise\r\n im4 = np.rot90(im4, k=1) # rot90 on anticlockwise\r\n save_heatmap(f\"{path}_4\", im4, lines4.reshape((-1, 2, 2)))\r\n\r\n im5, lines5 = prepare_rotation(im, lines.copy())\r\n lines5 = coor_rot90(lines5.reshape((-1, 2)), (im5.shape[1] / 2, im5.shape[0] / 2), 3) # rot90 on clockwise\r\n im5 = np.rot90(im5, k=-1) # rot90 on clockwise\r\n save_heatmap(f\"{path}_5\", im5, lines5.reshape((-1, 2, 2)))\r\n\r\n # linesf = lines.copy()\r\n # linesf[:, :, 0] = im.shape[1] - linesf[:, :, 0]\r\n # im1 = im[::, ::-1]\r\n # im6, lines6 = prepare_rotation(im1, linesf.copy())\r\n # lines6 = coor_rot90(lines6.reshape((-1, 2)), (im6.shape[1] / 2, im6.shape[0] / 2), 1) # rot90 on anticlockwise\r\n # im6 = np.rot90(im6, k=1) # rot90 on anticlockwise\r\n # save_heatmap(f\"{path}_6\", im6, lines6.reshape((-1, 2, 2)))\r\n #\r\n # im7, lines7 = prepare_rotation(im1, linesf.copy())\r\n # lines7 = coor_rot90(lines7.reshape((-1, 2)), (im7.shape[1] / 2, im7.shape[0] / 2), 3) # rot90 on clockwise\r\n # im7 = np.rot90(im7, k=-1) # rot90 on clockwise\r\n # save_heatmap(f\"{path}_7\", im7, lines7.reshape((-1, 2, 2)))\r\n\r\n # exit()\r\n\r\n print(\"Finishing\", os.path.join(data_output, batch, prefix))\r\n\r\n # handle(dataset[0])\r\n # multiprocessing the function of handle with augment 'dataset'.\r\n parmap(handle, dataset, 16)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n main()\r\n\r\n","repo_name":"Delay-Xili/F-Clip","sub_path":"dataset/wireframe_line.py","file_name":"wireframe_line.py","file_ext":"py","file_size_in_byte":9036,"program_lang":"python","lang":"en","doc_type":"code","stars":138,"dataset":"github-code","pt":"44"} +{"seq_id":"9799227278","text":"from turtle import Turtle\n\n\nclass Brick(Turtle):\n def __init__(self, position, colors):\n super().__init__()\n self.shape('square')\n self.shapesize(stretch_len=2)\n self.color(colors)\n self.penup()\n self.goto(position)\n\n def collide(self):\n self.hideturtle()\n self.goto(0, -295)\n","repo_name":"rushikeshpabalkar90/Breakout_game","sub_path":"brick.py","file_name":"brick.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"9756935007","text":"import struct,os\ndef write_payload(offset=0):\n padding=b\"/bin/sh\"+b\"\\x00\"\n padding+=b\"A\"*(140-len(padding))\n addr_of_binsh=struct.pack(\"=2:\n return findfibo(n-1)+findfibo(n-2)\n\n\nx = int(input(\"Enter a fibonacci number = \"))\n\nprint(\"The fibo sum is = {}\".format(findfibo(x)))","repo_name":"DeletedAccountMarch/Compitative-Programming","sub_path":"Code Challenges/Challeges/nth_fibo.py","file_name":"nth_fibo.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"22620663043","text":"import speech_recognition\nimport pyttsx3\nimport os\nfrom gtts import gTTS\nimport webbrowser\nen = 'en'\n\nrecognizer = speech_recognition.Recognizer()\nengine = pyttsx3.init()\nvoices = engine.getProperty('voices') \nengine.setProperty('rate', 125)\nwhile True:\n try:\n\n with speech_recognition.Microphone() as mic:\n recognizer.adjust_for_ambient_noise(mic, duration=0.2)\n audio = recognizer.listen(mic)\n\n text = recognizer.recognize_google(audio)\n text = text.lower()\n \n if text == 'change language to polish':\n en = 'pl'\n engine.say(\"Język zmieniony\")\n engine.runAndWait()\n \n\n\n if text == \"open web\":\n engine.say(\"Opening\")\n engine.runAndWait()\n webbrowser.open(\"https://recrash.vercel.app/map\", new=2)\n \n\n print(f\"Regognized {text}\")\n except speech_recognition.UnknownValueError():\n recognizer - speech_recognition.Recognizer()\n continue ","repo_name":"KartoszBoza/voice-recognition","sub_path":"voice.py","file_name":"voice.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"44"} +{"seq_id":"21865076839","text":"import os\nos.environ[\"OPENBLAS_NUM_THREADS\"] = \"1\"\nimport numpy as np\n\ndef find_combination(choices, total):\n \"\"\"\n choices: a non-empty list of ints\n total: a positive int\n \n Returns result, a numpy.array of length len(choices) \n such that\n * each element of result is 0 or 1\n * sum(result*choices) == total\n * sum(result) is as small as possible\n In case of ties, returns any result that works.\n If there is no result that gives the exact total, \n pick the one that gives sum(result*choices) closest \n to total without going over.\n \"\"\"\n def comboProduct(choices, combo):\n return sum([choices[i] * combo[i] for i in range(len(choices))])\n\n def int2bin(num, choices):\n numBin = bin(num).replace('0b', '')\n numArr = np.array([int(numBin[i]) for i in range(len(numBin))])\n while len(numArr) < len(choices):\n numArr = np.insert(numArr, 0, 0)\n return numArr\n\n combo = np.array([0 for i in range(len(choices))])\n secondChoice = np.array([0 for i in range(len(choices))])\n validCombo = np.array([0 for i in range(len(choices))])\n maxVal = 2**len(choices)\n\n for i in range(maxVal):\n iArr = int2bin(i, choices)\n product = comboProduct(choices, iArr)\n\n if product == total:\n if comboProduct(choices, validCombo) != total or sum(iArr) < sum(validCombo):\n validCombo = iArr\n elif product < total:\n if product > comboProduct(choices, secondChoice):\n secondChoice = iArr\n \n if comboProduct(choices, validCombo) == total:\n return validCombo\n else:\n return secondChoice\n\nprint(find_combination([1,2,2,3], 4))\nprint(find_combination([1,1,3,5,3], 5))\nprint(find_combination([1,1,1,9], 4))","repo_name":"aaronjohnsabu1999/MITx_6.00.2x","sub_path":"Endterm/et_6.py","file_name":"et_6.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"44"} +{"seq_id":"4041133808","text":"ne_states = (\n 'Connecticut',\n 'Maine',\n 'Massachusetts',\n 'New Hampshire',\n 'New Jersey',\n 'New York',\n 'Pennsylvania'\n 'Rhode Island',\n 'Vermont',\n )\n \nmw_states = (\n 'Illinois',\n 'Indiana',\n 'Iowa',\n 'Kansas',\n 'Michigan',\n 'Minnesota',\n 'Missouri',\n 'Nebraska',\n 'North Dakota',\n 'Ohio',\n 'South Dakota'\n 'Wisconsin',\n ) \n\ns_states = (\n 'Alabama',\n 'Arkansas',\n 'Delaware',\n 'District of Columbia',\n 'Florida',\n 'Georgia',\n 'Kentucky',\n 'Louisiana',\n 'Maryland',\n 'Mississippi',\n 'North Carolina',\n 'Oklahoma',\n 'South Carolina',\n 'Tennessee',\n 'Texas'\n 'Virginia',\n 'West Virginia',\n )\n\nw_states = (\n 'Alaska',\n 'Arizona',\n 'California',\n 'Colorado',\n 'Hawaii',\n 'Idaho',\n 'Montana',\n 'Nevada',\n 'New Mexico',\n 'Oregon',\n 'Utah',\n 'Washington'\n 'Wyoming',\n )\n\nregions = {\n 'NE': ne_states,\n 'MW': mw_states,\n 'S': s_states,\n 'W': w_states}\n\ndef find_region(value, dict=regions):\n return next((k for k, v in dict.items() if value in v), None)\n \ndef google_map_address(self):\n base = 'https://www.google.ca/maps/place/'\n try:\n address = self.address.replace(\" \", \"+\")\n city = self.city.name\n state = self.state.name\n zip = self.zip.code\n return (base + address + \",+\" + city + \",+\" + state + \",+\" + zip)\n except AttributeError:\n return base","repo_name":"cpadiernos/triviacompany","sub_path":"locations/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"10655047567","text":"import random\nfrom time import sleep\nfrom catch_coins_env import CatchCoinsEnv\n\nenv = CatchCoinsEnv()\n\ninit_state = env.reset()\n# -1: left\n# 0: stay\n# +1: right\naction_space = [-1, 0, 1]\n\nfor _ in range(1000):\n env.render('ascii')\n print(\"push step: \")\n action = int(input())\n action -= 2\n state, reward, done, debug = env.step(action)\n sleep(.2)\n\nenv.close()\n","repo_name":"VolDonets/reinforcement_learining","sub_path":"chapter_3/custom_env_pygame/key_agent.py","file_name":"key_agent.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"74282381853","text":"# the top 10 most common words\n\nfhand=open('romeo.txt')\ncounts = dict()\n\nfor line in fhand:\n words = line.split()\n for word in words:\n counts[word]=counts.get(word,0)+1\n## complete dictinary called \"counts\"\n\n# Important: even shorter version to replace below:\n# print(sorted([(v,k) for k,v in c.items()]))\n# List comprehension: an expression as a list\n\n\n\n\nlist1=list()\nfor k, v in counts.items(): # dictionary >> tuples\n list1.append((v,k)) # reorder and add to a list\n\nlist1 = sorted(list1, reverse=True) # sort backward: highest to lowest value\n# print(list1)\n# [(3, 'the'), (3, 'is'), (3, 'and'), (2, 'sun'), (1, 'yonder'), (1, 'with'), (1, 'window'), (1, 'what'), (1, 'through'), (1, 'soft'), (1, 'sick'), (1, 'pale'), (1, 'moon'), (1, 'light'), (1, 'kill'), (1, 'grief'), (1, 'fair'), (1, 'envious'), (1, 'east'), (1, 'breaks'), (1, 'already'), (1, 'Who'), (1, 'Juliet'), (1, 'It'), (1, 'But'), (1, 'Arise')]\n\nfor val, key in list1[:10]:\n print(key, val)\n\n## breif version:\nprint(sorted([(v,k) for k,v in counts.items()], reverse=True))\n#the 3\n#is 3\n#and 3\n#sun 2\n#yonder 1\n#with 1\n#window 1\n#what 1\n#through 1\n#soft 1\n\n## breif version:\nprint(sorted([(v,k) for k,v in counts.items()], reverse=True))\n\n#>>[(3, 'the'), (3, 'is'), (3, 'and'), (2, 'sun'), (1, 'yonder'), (1, 'with'), (1, 'window'), (1, 'what'), (1, 'through'), (1, 'soft'), (1, 'sick'), (1, 'pale'), (1, 'moon'), (1, 'light'), (1, 'kill'), (1, 'grief'), (1, 'fair'), (1, 'envious'), (1, 'east'), (1, 'breaks'), (1, 'already'), (1, 'Who'), (1, 'Juliet'), (1, 'It'), (1, 'But'), (1, 'Arise')]\n","repo_name":"FeliciaCoding/Python_Coursera","sub_path":"10_most_common_words.py","file_name":"10_most_common_words.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"7158884336","text":"# Problem: Guess Number Higher or Lower\n# (https://leetcode.com/problems/guess-number-higher-or-lower/#/description)\n\n# The guess API is already defined for you.\n# @param num, your guess\n# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0\n# def guess(num):\n\nclass Solution(object):\n def guessNumber(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n inclusiveStart, exclusiveEnd, g, candidate = 1, n + 1, -1, -1\n while g != 0:\n candidate = (inclusiveStart + exclusiveEnd)/2\n g = guess(candidate)\n if g < 0:\n exclusiveEnd = candidate\n elif g > 0:\n inclusiveStart = candidate + 1\n return candidate\n","repo_name":"dqian96/coding-practice","sub_path":"guess_number_higher_or_lower.py","file_name":"guess_number_higher_or_lower.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"74645541853","text":"import json\nimport os\nfrom copy import deepcopy\n\nimport pytest\nfrom clients.factories.knowledge_base_factory import KnowledgeBaseFactory\nfrom shared.knowledge.kendra_knowledge_base import KendraKnowledgeBase\nfrom utils.constants import DEFAULT_HUGGINGFACE_PROMPT, KENDRA_INDEX_ID_ENV_VAR\n\n\n@pytest.mark.parametrize(\"prompt, is_streaming, rag_enabled\", [(DEFAULT_HUGGINGFACE_PROMPT, False, False)])\ndef test_get_kb_memory_success(llm_config, setup_environment):\n config = json.loads(llm_config[\"Parameter\"][\"Value\"])\n errors_list = []\n response = KnowledgeBaseFactory().get_knowledge_base(config, errors_list)\n assert type(response) == KendraKnowledgeBase\n assert response.kendra_index_id == \"fake-kendra-index-id\"\n assert response.number_of_docs == 2\n assert response.return_source_documents == False\n assert errors_list == []\n\n\n@pytest.mark.parametrize(\"prompt, is_streaming, rag_enabled\", [(DEFAULT_HUGGINGFACE_PROMPT, False, False)])\ndef test_unsupported_kb(llm_config):\n errors_list = []\n config = deepcopy(json.loads(llm_config[\"Parameter\"][\"Value\"]))\n config[\"KnowledgeBaseType\"] = \"OpenSearch\"\n response = KnowledgeBaseFactory().get_knowledge_base(config, errors_list)\n assert response is None\n assert errors_list == [\"Unsupported KnowledgeBase type: OpenSearch. Supported types are: ['Kendra']\"]\n\n\n@pytest.mark.parametrize(\"prompt, is_streaming, rag_enabled\", [(DEFAULT_HUGGINGFACE_PROMPT, False, False)])\ndef test_get_kb_missing_kendra_index(llm_config, setup_environment):\n errors_list = []\n config = deepcopy(json.loads(llm_config[\"Parameter\"][\"Value\"]))\n os.environ.pop(KENDRA_INDEX_ID_ENV_VAR, None)\n with pytest.raises(ValueError):\n response = KnowledgeBaseFactory().get_knowledge_base(config, errors_list)\n assert response is None\n assert errors_list == [\n f\"Missing required environment variable {KENDRA_INDEX_ID_ENV_VAR} for Kendra knowledge base.\"\n ]\n\n\n@pytest.mark.parametrize(\"prompt, is_streaming, rag_enabled\", [(DEFAULT_HUGGINGFACE_PROMPT, False, False)])\ndef test_get_kb_missing_config(llm_config):\n errors_list = []\n config = deepcopy(json.loads(llm_config[\"Parameter\"][\"Value\"]))\n del config[\"KnowledgeBaseParams\"]\n response = KnowledgeBaseFactory().get_knowledge_base(config, errors_list)\n assert response is None\n assert errors_list == [\n f\"Missing required field (KnowledgeBaseParams) in the configuration for the specified Knowledge Base {config['KnowledgeBaseType']}\"\n ]\n\n\n@pytest.mark.parametrize(\"prompt, is_streaming, rag_enabled\", [(DEFAULT_HUGGINGFACE_PROMPT, False, False)])\ndef test_get_kb_missing_type(llm_config):\n # When KnowledgeBaseType is not supplied, logs info and returns silently.\n errors_list = []\n config = deepcopy(json.loads(llm_config[\"Parameter\"][\"Value\"]))\n del config[\"KnowledgeBaseType\"]\n\n response = KnowledgeBaseFactory().get_knowledge_base(config, errors_list)\n assert response is None\n assert errors_list == [\"Missing required field (KnowledgeBaseType) in the configuration\"]\n","repo_name":"aws-solutions/generative-ai-application-builder-on-aws","sub_path":"source/lambda/chat/test/clients/factories/test_knowledge_base_factory.py","file_name":"test_knowledge_base_factory.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"33"} +{"seq_id":"19461131098","text":"import cv2\nimport os\n\n\nvideoroot = './level2_video'\nall_videos = sorted([os.path.join(videoroot,i) for i in os.listdir(videoroot) if i.find('.mp4') != -1])\nfor video in all_videos:\n vidcap = cv2.VideoCapture(video)\n succ, image = vidcap.read()\n dirname = './level2' + video.split('.')[1] + '/img1'\n if not os.path.isdir(dirname):\n os.mkdir(dirname)\n count = 1\n succ = True\n while succ:\n cv2.imwrite(os.path.join(dirname,'{:0>6d}.jpg'.format(count)), image, [int(cv2.IMWRITE_JPEG_QUALITY), 90]) # save frame as JPEG file\n succ, image = vidcap.read()\n print('save %6d in ' % count + dirname)\n count += 1\n","repo_name":"ecart18/zhijiang-tracker","sub_path":"data/zj_test/video2frames.py","file_name":"video2frames.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"74744365214","text":"import cx_Oracle\nimport datetime\nimport calendar\nfrom Transaction import Transaction\nimport MainMenu\ndb=cx_Oracle.connect('banking/bankingdb@localhost/xe')\ncur=db.cursor()\nclass Account:\n def create_new_account(self,account_number,account_type): #creates a new account\n cur.execute(\"insert into accounts values(\"+ str(account_number) + \",0,'\" + account_type.upper() + \"',systimestamp,'ACTIVE')\")\n db.commit()\n if account_type.upper()==\"CA\":#if the account type is Current Account ₹5000 is deposited to the account \n Transaction().deposit(account_number,5000)\n \n def deposit_money(self,account_number): #deposits money to the account\n try:\n amount=float(input(\"\\nEnter the amount to deposit \"))\n if amount>float(0):\n balance=Transaction().deposit(account_number,amount)\n print(\"Amount deposited successfully.\\nYour balance: ₹\" + str(balance))\n else:\n print(\"Invalid amount\")\n except ValueError:\n print(\"Invalid amount\")\n \n def get_withdrawl_count(self,account_number): #gets the numbers of withdrawals made in the current month\n now=datetime.datetime.now()\n current_month=now.strftime(\"%b\").upper()\n current_year =now.strftime(\"%y\")\n month_year=current_month + \"-\" + current_year\n cur.execute(\"select count(*) from transactions where accountnumber=\"\n + str(account_number) + \" and transactiondate like '%\" + month_year + \"' and description='Withdraw'\")\n count=int(cur.fetchone()[0])\n return count\n \n def withdraw_money(self,account_number): #withdraws money from the account \n try:\n cur.execute(\"select balance,accounttype from accounts where accountnumber=\" + str(account_number))\n row=cur.fetchone()\n if row[1].upper()==\"SB\" and self.get_withdrawl_count(account_number) >= 10: #if the account type is Saving Account and Withdrawal count exceeds 10 in the current month\n print(\"You have exceeded the maximum withdrawl limit this month (Maximum 10 withdrawls per month)\")\n else:\n amount=float(input(\"\\nEnter the amount to withdraw \"))\n if amount>float(0):\n balance=float(row[0])\n account_type=row[1]\n if amount>balance:\n print(\"Withdrawl failed. Insufficient balance. Your balance is ₹\" + str(balance))\n elif account_type.upper()==\"CA\" and balance-amount < 5000:\n print(\"Withdrawl failed. You should maintain a minimum balance of ₹5000 \\nYour balance is ₹\"\n + str(balance) + \"\\nYou can withdraw a maximum of ₹\" + str(balance - 5000) + \" as of now.\")\n else:\n balance=Transaction().withdraw(account_number,amount)\n print(\"Withdrawl success.\\nYour balance: ₹\" + str(balance))\n else:\n print(\"Invalid amount\")\n except ValueError:\n print(\"Invalid amount\")\n\n def transfer_money(self,account_number): #transfers money\n try:\n to_account_number=int(input(\"\\nEnter the account number to transfer \"))\n cur.execute(\"select * from accounts where accountnumber=\" + str(to_account_number))\n cur.fetchone()\n if cur.rowcount!=0:\n if account_number != to_account_number:\n amount=float(input(\"Enter the amount to transfer \"))\n if amount>float(0):\n cur.execute(\"select balance,accounttype from accounts where accountnumber=\" + str(account_number))\n row=cur.fetchone()\n balance=float(row[0])\n account_type=row[1]\n if amount>balance:\n print(\"Transfer failed. Insufficient balance. Your balance is ₹\" + str(balance))\n elif account_type.upper()==\"CA\" and balance-amount < float(5000):\n print(\"Transfer failed. You should maintain a minimum balance of ₹5000 \\nYour balance is ₹\"\n + str(balance) + \"\\nYou can Transfer/Withdraw a maximum of ₹\" + str(balance - float(5000)) + \" as of now.\")\n else:\n balance=Transaction().transfer(account_number,to_account_number,amount)\n print(\"Transfer success.\\nYour balance: ₹\" + str(balance))\n else:\n print(\"Invalid amount\")\n else:\n print(\"You cannot transfer to your own account\")\n else:\n print(\"Invalid account number\")\n except ValueError:\n print(\"Invalid value\")\n\n def print_statement(self,account_number): #Prints account statement\n while True:\n from_date=input(\"From date (DD/MM/YYYY): \")\n if(self.validate_date(from_date)):\n break\n else:\n print(\"Invalid date. Please enter a valid date\")\n while True:\n to_date=input(\"To date (DD/MM/YYYY): \")\n if(self.validate_date(to_date)):\n break\n else:\n print(\"Invalid date. Please enter a valid date\")\n if datetime.datetime.strptime(to_date,\"%d/%m/%Y\") > datetime.datetime.strptime(from_date,\"%d/%m/%Y\"):#If 'To date' is less than 'From date' \n to_date=datetime.datetime.strptime(to_date,\"%d/%m/%Y\")\n to_date+= datetime.timedelta(days=1)\n to_date=to_date.strftime(\"%d\") + \"/\" + to_date.strftime(\"%m\") + \"/\" + to_date.strftime(\"%Y\")\n \n transaction=Transaction().get_transactions(account_number,from_date,to_date)\n \n print(\"-\"*120)\n print(\"TRANSACTION ID\".center(14)+ \"DATE\".center(15) +\"DESCRIPTION\".center(45)\n + \"CREDIT\".rjust(15) + \"DEBIT\".rjust(15) + \"BALANCE\".rjust(15))\n print(\"-\"*120)\n row=transaction.fetchall()\n for i in range(0,transaction.rowcount):\n print(str(row[i][0]).center(14) + str(row[i][1].strftime(\"%d/%m/%Y\")).center(15)\n + str(row[i][3]).center(45) + (\"\".rjust(15) if row[i][4] is None else str(format(row[i][4],'.2f')).rjust(15))\n + (\"\".rjust(15) if row[i][5] is None else str(format(row[i][5],'.2f')).rjust(15)) + str(format(row[i][6],'.2f')).rjust(15))\n print(\"-\"*120)\n else:\n print(\"To date must be greater than from date.\")\n \n def validate_date(self,date): #validates the format of date entered by the user\n try:\n datetime.datetime.strptime(date,\"%d/%m/%Y\")\n except ValueError:\n return False\n return True\n def close_account(self,customer_id): #closes the account\n option=input(\"Are you sure to close the account? (y/n) : \")\n if option.upper()==\"Y\":\n cur.execute(\"update accounts set status='CLOSED' where accountnumber=\" + str(customer_id))\n cur.execute(\"select accounttype,balance from accounts where accountnumber=\" + str(customer_id))\n result=cur.fetchone()\n account_type=result[0]\n balance=result[1]\n cur.execute(\"insert into closedaccounts values(\"+str(customer_id)+\",systimestamp,'\" + account_type + \"')\")\n cur.execute(\"update logincredentials set status='CLOSED' where customerid=\" +str(customer_id))\n print(\"Account closed successfully. Your balance amount ₹\" + str(balance) + \" will be sent to your address soon\")\n db.commit()\n MainMenu.MainMenu().show_menu()\n def display_closed_accounts_history(self): #displays the details of closed accounts\n cur.execute(\"select * from closedaccounts\")\n result=cur.fetchall()\n print(\"-\"*51)\n print(\"ACCOUNT NUMBER\".center(16) + \"ACCOUNT TYPE\".center(20) + \"CLOSE DATE\".center(15))\n print(\"-\"*51)\n for i in range(0,cur.rowcount):\n print(str(result[i][0]).center(16) + (\"Savings Account\".center(20) if result[i][2]==\"SB\" else \"Current Account\".center(20))\n + str(result[i][1].strftime(\"%d/%m/%Y\")).center(15))\n print(\"-\"*51)\n \n \n \n","repo_name":"harideepan/Banking","sub_path":"Account.py","file_name":"Account.py","file_ext":"py","file_size_in_byte":8479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"34198511388","text":"import urllib.parse\nimport requests\nfrom geopy.geocoders import Nominatim\nimport streamlit as st\nfrom googleplaces import GooglePlaces, types, lang\nst.set_page_config(page_title=\"Hospital Finder\", page_icon=\"🏥\")\nst.markdown(\"# Locate the Nearest Hospital\")\nst.write(\n \"\"\"Enter your current address as well the city/state. The algorithm uses geomapping to first find your latitude and longtitude, finds nearest hospitals, then converts them into addresses.\"\"\")\nAPI_KEY = 'AIzaSyAiegc8hmrCGr2ip_hubPicHCaTHpjjrSE'\ngoogle_places = GooglePlaces(API_KEY)\naddress = st.text_input(\"Enter your address:\")\nif st.button('Find Hospital'):\n url = 'https://nominatim.openstreetmap.org/search/' + urllib.parse.quote(address) + '?format=json'\n response = requests.get(url).json()\n lat = response[0][\"lat\"]\n long = response[0][\"lon\"]\n query_result = google_places.nearby_search(\n lat_lng={'lat':lat,'lng':long},\n radius = 5000,\n types = [types.TYPE_HOSPITAL]\n )\n if query_result.has_attributions:\n print(query_result.html_attributions)\n if len(query_result.places)==0:\n st.write(\"There are no hospitals in a 5 KM proximity.\")\n for place in query_result.places:\n st.subheader(place.name)\n lat = place.geo_location['lat']\n long = place.geo_location['lng']\n locator = Nominatim(user_agent=\"myGeocoder\")\n coordinates = str(lat) + \", \" + str(long)\n location = locator.reverse(coordinates)\n st.write(location.address)\n","repo_name":"bionostics/uber4","sub_path":"pages/🏥_Hospital_Finder.py","file_name":"🏥_Hospital_Finder.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"38088751636","text":"import random\n\nprint(\"Guess a number between 1 and 1000\")\n\nTheNumber = random.randint(1, 1000)\n\nwhile True:\n guess = int(input(\"Enter your guess: \"))\n if guess == TheNumber:\n print(\"You guessed it right!\")\n break\n elif guess > TheNumber:\n print(\"Your guess is too high\")\n else:\n print(\"Your guess is too low\")","repo_name":"kunwu/Rachel","sub_path":"Python/GuessNumber.py","file_name":"GuessNumber.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"38232559134","text":"import os\nimport unittest\nfrom prospector.suppression import get_noqa_suppressions\n\n\nclass SuppressionTest(unittest.TestCase):\n\n def _get_file_contents(self, name):\n path = os.path.join(os.path.dirname(__file__), 'testdata', name)\n with open(path) as testfile:\n return testfile.readlines()\n\n def test_ignore_file(self):\n file_contents = self._get_file_contents('test_ignore_file/test.py')\n whole_file, _ = get_noqa_suppressions(file_contents)\n self.assertTrue(whole_file)\n\n def test_ignore_lines(self):\n file_contents = self._get_file_contents('test_ignore_lines/test.py')\n _, lines = get_noqa_suppressions(file_contents)\n self.assertSetEqual(set((2, 3)), lines)","repo_name":"tetrafolium/prospector","sub_path":"tests/suppression/test_suppression.py","file_name":"test_suppression.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"40829235045","text":"class PriorityNode:\r\n\tvalue=None\r\n\tnextNode=None\r\n\tpriority=None\r\n\r\nclass PriorityQueue:\r\n head=None\r\n tail=None\r\n\r\n def enqueue(self,element,priority):\r\n NewNode = PriorityNode()\r\n NewNode.value = element\r\n NewNode.priority = priority\r\n if self.head != None:\r\n if NewNode.priority >= self.tail.priority:\r\n self.tail.nextNode = NewNode\r\n self.tail = NewNode\r\n else:\r\n node = self.head\r\n while node.priority < NewNode.priority and node.nextNode != None:\r\n node = node.nextNode\r\n\r\n NewNode.nextNode = node.nextNode\r\n node.nextNode = NewNode\r\n\r\n else:\r\n self.head = NewNode\r\n self.tail = NewNode\r\n\r\n def dequeue(self):\r\n if self.head != None:\r\n nodo = self.head\r\n self.head = nodo.nextNode\r\n return nodo.value\r\n else:\r\n return None","repo_name":"EduardoPerez12/ia-uncuyo-2021","sub_path":"tp3-busquedas-no-informadas/code/priorityqueue.py","file_name":"priorityqueue.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"73544910814","text":"\"\"\"\nWörter verteilen\n\"\"\"\n\nsize(300, 300)\nlieblingsfilme = [\"Titanic\", \"Wild Tales\"]\n\nfor film in lieblingsfilme:\n text(film, (100, 200))\n\n \n \n\n\"\"\"\nAufgabe: \n - Ergänze die Liste Lieblingsfilme mit Filmen, die du gerne magst. \n \nWarum werden alle Titel übereinander platziert? \nKannst du sie zufällig auf der Fläche verteilen? \n\"\"\"","repo_name":"cas-c4ta/drawbot-selbststudium","sub_path":"4_loop/3_Wörter-verteilen.py","file_name":"3_Wörter-verteilen.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"22355337161","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 1 00:23:39 2022\n\n@author: reekm\n\"\"\"\n\nCSV = \".csv\"\n\nfile_name1 = 'initial_dataset\\\\part1_1.xlsx'\nfile_name2 = 'initial_dataset\\\\part2.xlsx'\n\nfull_dataset = [file_name1,file_name2]\n\nRUS_dataset_name = \"full_data_rus.csv\"\n\n\n\nsave_path_classify = 'AutoML_classify_v2_29July_rus3'\nsave_path_reg = 'AutoML_reg_v2_29July_rus_sc3'\nTrain = True\n\nflag_rus = 1 # 1 for RandomUnderSampling 0 for RandomOversampling\ntest_size =0.2\n","repo_name":"reek129/Autogluon-classification-regression","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"20396648711","text":"\"\"\"Adding days_of_week and available time\n\nRevision ID: 54e36a8844c3\nRevises: 444665008725\nCreate Date: 2020-02-23 00:46:53.239285\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '54e36a8844c3'\ndown_revision = '444665008725'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('dic_available_time',\n sa.Column('time_key', sa.String(length=10), nullable=False),\n sa.Column('rus_name', sa.String(length=100), nullable=True),\n sa.PrimaryKeyConstraint('time_key')\n )\n op.create_table('dic_days_of_week',\n sa.Column('weekday_key', sa.String(length=3), nullable=False),\n sa.Column('rus_name', sa.String(length=50), nullable=True),\n sa.Column('rus_short_name', sa.String(length=2), nullable=True),\n sa.PrimaryKeyConstraint('weekday_key')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('dic_days_of_week')\n op.drop_table('dic_available_time')\n # ### end Alembic commands ###\n","repo_name":"eugene-kg/StepikTinySteps","sub_path":"migrations/versions/54e36a8844c3_adding_days_of_week_and_available_time.py","file_name":"54e36a8844c3_adding_days_of_week_and_available_time.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"15013143464","text":"import os\nimport sys\nimport glob\nimport json\nimport errno\nimport shutil\nimport zipfile\nimport StringIO\nimport tempfile\nimport platform\nimport traceback\nfrom datetime import datetime\nfrom os import path, makedirs\nfrom base64 import urlsafe_b64encode\n\nimport wagon\nfrom flask import g\nfrom flask import request\nfrom flask_restful import abort\nfrom werkzeug.local import LocalProxy\nfrom flask_security import current_user\n\nfrom dsl_parser.constants import HOST_AGENT_PLUGINS_TO_INSTALL\n\nfrom cloudify import logs\nfrom cloudify.constants import BROKER_PORT_SSL\nfrom cloudify.models_states import VisibilityState\nfrom cloudify.amqp_client import create_events_publisher\n\nfrom manager_rest import constants, config, manager_exceptions\n\n\ndef check_allowed_endpoint(allowed_endpoints):\n for endpoint in allowed_endpoints:\n if endpoint in request.endpoint:\n return True\n return False\n\n\ndef is_sanity_mode():\n return os.path.isfile(constants.SANITY_MODE_FILE_PATH)\n\n\ndef is_internal_request():\n remote_addr = _get_remote_addr()\n http_hosts = [_get_host(), constants.LOCAL_ADDRESS]\n return all([remote_addr, http_hosts, remote_addr in http_hosts])\n\n\ndef _get_host():\n return request.host\n\n\ndef _get_remote_addr():\n return request.remote_addr\n\n\ndef copy_resources(file_server_root, resources_path=None):\n if resources_path is None:\n resources_path = path.abspath(__file__)\n for i in range(3):\n resources_path = path.dirname(resources_path)\n resources_path = path.join(resources_path, 'resources')\n cloudify_resources = path.join(resources_path,\n 'rest-service',\n 'cloudify')\n shutil.copytree(cloudify_resources, path.join(file_server_root,\n 'cloudify'))\n\n\ndef abort_error(error, logger, hide_server_message=False):\n logger.info('{0}: {1}'.format(type(error).__name__, str(error)))\n s_traceback = StringIO.StringIO()\n if hide_server_message:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n traceback.print_tb(exc_traceback, file=s_traceback)\n else:\n traceback.print_exc(file=s_traceback)\n\n abort(error.status_code,\n message=str(error),\n error_code=error.error_code,\n server_traceback=s_traceback.getvalue())\n\n\ndef mkdirs(folder_path):\n try:\n makedirs(folder_path)\n except OSError as exc:\n if exc.errno == errno.EEXIST and path.isdir(folder_path):\n pass\n else:\n raise\n\n\ndef create_filter_params_list_description(parameters, list_type):\n return [{'name': filter_val,\n 'description': 'List {type} matching the \\'{filter}\\' '\n 'filter value'.format(type=list_type,\n filter=filter_val),\n 'required': False,\n 'allowMultiple': False,\n 'dataType': 'string',\n 'defaultValue': None,\n 'paramType': 'query'} for filter_val in parameters]\n\n\ndef read_json_file(file_path):\n with open(file_path) as f:\n return json.load(f)\n\n\ndef write_dict_to_json_file(file_path, dictionary):\n with open(file_path, 'w') as f:\n json.dump(dictionary, f)\n\n\ndef is_bypass_maintenance_mode(request):\n bypass_maintenance_header = 'X-BYPASS-MAINTENANCE'\n return request.headers.get(bypass_maintenance_header)\n\n\ndef get_plugin_archive_path(plugin_id, archive_name):\n return os.path.join(\n config.instance.file_server_root,\n constants.FILE_SERVER_PLUGINS_FOLDER,\n plugin_id,\n archive_name\n )\n\n\ndef plugin_installable_on_current_platform(plugin):\n dist, _, release = platform.linux_distribution(\n full_distribution_name=False)\n dist, release = dist.lower(), release.lower()\n\n # Mac OSX is a special case, in which plugin.distribution and\n # plugin.release will be None instead of ''\n if 'macosx' in plugin.supported_platform:\n dist = dist or None\n release = release or None\n\n return (plugin.supported_platform in ('any', 'manylinux1_x86_64') or all([\n plugin.supported_platform == wagon.get_platform(),\n plugin.distribution == dist,\n plugin.distribution_release == release\n ]))\n\n\ndef get_formatted_timestamp():\n # Adding 'Z' to match ISO format\n return '{0}Z'.format(datetime.utcnow().isoformat()[:-3])\n\n\nclass classproperty(object): # NOQA # class CapWords\n \"\"\"A class that acts a a decorator for class-level properties\n\n class A(object):\n _prop1 = 1\n _prop2 = 2\n\n @classproperty\n def foo(cls):\n return cls._prop1 + cls._prop2\n\n And use it like this:\n print A.foo # 3\n\n \"\"\"\n def __init__(self, get_func):\n self.get_func = get_func\n\n def __get__(self, _, owner_cls):\n return self.get_func(owner_cls)\n\n\ndef create_auth_header(username=None, password=None, token=None, tenant=None):\n \"\"\"Create a valid authentication header either from username/password or\n a token if any were provided; return an empty dict otherwise\n \"\"\"\n headers = {}\n if username and password:\n credentials = '{0}:{1}'.format(username, password)\n headers = {constants.CLOUDIFY_AUTH_HEADER:\n constants.BASIC_AUTH_PREFIX + urlsafe_b64encode(credentials)\n }\n elif token:\n headers = {constants.CLOUDIFY_AUTH_TOKEN_HEADER: token}\n if tenant:\n headers[constants.CLOUDIFY_TENANT_HEADER] = tenant\n return headers\n\n\ndef all_tenants_authorization():\n return (\n current_user.id == constants.BOOTSTRAP_ADMIN_ID or\n any(r in current_user.system_roles\n for r in config.instance.authorization_permissions['all_tenants'])\n )\n\n\ndef tenant_specific_authorization(tenant, resource_name, action='list'):\n \"\"\"\n Return true if the user is permitted to perform a certain action in a\n in a given tenant on a given resource (for filtering purpose).\n \"\"\"\n resource_name = constants.MODELS_TO_PERMISSIONS.get(resource_name,\n resource_name.lower())\n try:\n permission_name = '{0}_{1}'.format(resource_name, action)\n permission_roles = \\\n config.instance.authorization_permissions[permission_name]\n except KeyError:\n permission_roles = \\\n config.instance.authorization_permissions[resource_name.lower()]\n return current_user.has_role_in(tenant, permission_roles)\n\n\ndef is_administrator(tenant):\n administrators_roles = \\\n config.instance.authorization_permissions['administrators']\n return (\n current_user.id == constants.BOOTSTRAP_ADMIN_ID or\n current_user.has_role_in(tenant, administrators_roles)\n )\n\n\ndef is_create_global_permitted(tenant):\n create_global_roles = \\\n config.instance.authorization_permissions['create_global_resource']\n return (\n current_user.id == constants.BOOTSTRAP_ADMIN_ID or\n current_user.has_role_in(tenant, create_global_roles)\n )\n\n\ndef can_execute_global_workflow(tenant):\n execute_global_roles = \\\n config.instance.authorization_permissions['execute_global_workflow']\n return (\n current_user.id == constants.BOOTSTRAP_ADMIN_ID or\n current_user.has_role_in(tenant, execute_global_roles)\n )\n\n\ndef validate_global_modification(resource):\n # A global resource can't be modify from outside its tenant\n if resource.visibility == VisibilityState.GLOBAL and \\\n resource.tenant_name != current_tenant.name:\n raise manager_exceptions.IllegalActionError(\n \"Can't modify the global resource `{0}` from outside its \"\n \"tenant `{1}`\".format(resource.id, resource.tenant_name))\n\n\n@LocalProxy\ndef current_tenant():\n tenant = getattr(g, 'current_tenant', None)\n if not tenant:\n raise manager_exceptions.TenantNotProvided(\n 'Authorization failed: tenant not provided')\n return tenant\n\n\ndef set_current_tenant(tenant):\n g.current_tenant = tenant\n\n\ndef unzip(archive, destination=None, logger=None):\n if not destination:\n destination = tempfile.mkdtemp()\n if logger:\n logger.debug('Extracting zip {0} to {1}...'.\n format(archive, destination))\n with zipfile.ZipFile(archive, 'r') as zip_file:\n zip_file.extractall(destination)\n return destination\n\n\ndef files_in_folder(folder, name_pattern='*'):\n files = []\n for item in glob.glob(os.path.join(folder, name_pattern)):\n if os.path.isfile(item):\n files.append(os.path.join(folder, item))\n return files\n\n\ndef remove(path):\n if os.path.exists(path):\n if os.path.isfile(path):\n os.remove(path)\n else:\n shutil.rmtree(path)\n\n\ndef send_event(event, message_type):\n logs.populate_base_item(event, 'cloudify_event')\n events_publisher = create_events_publisher(\n amqp_host=config.instance.amqp_host,\n amqp_user=config.instance.amqp_username,\n amqp_pass=config.instance.amqp_password,\n amqp_port=BROKER_PORT_SSL,\n amqp_vhost='/',\n ssl_enabled=True,\n ssl_cert_path=config.instance.amqp_ca_path\n )\n\n events_publisher.publish_message(event, message_type)\n events_publisher.close()\n\n\ndef is_visibility_wider(first, second):\n states = VisibilityState.STATES\n return states.index(first) > states.index(second)\n\n\ndef validate_deployment_and_site_visibility(deployment, site):\n if is_visibility_wider(deployment.visibility, site.visibility):\n raise manager_exceptions.IllegalActionError(\n \"The visibility of deployment `{0}`: `{1}` can't be wider than \"\n \"the visibility of it's site `{2}`: `{3}`\"\n .format(deployment.id, deployment.visibility, site.name,\n site.visibility)\n )\n\n\ndef extract_host_agent_plugins_from_plan(plan):\n host_agent_plugins_to_install = plan.get(\n HOST_AGENT_PLUGINS_TO_INSTALL, [])\n\n if not host_agent_plugins_to_install:\n for node in plan.get('nodes', []):\n for plugin in node.get('plugins_to_install', []):\n host_agent_plugins_to_install.append(plugin)\n return host_agent_plugins_to_install\n","repo_name":"qijia-git/cloudify-manager","sub_path":"rest-service/manager_rest/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"33"} +{"seq_id":"29810015884","text":"import matplotlib.pyplot as plt\nfrom matplotlib.pyplot import MultipleLocator\nfrom matplotlib import rcParams\nconfig = {\n \"font.family\":'Times New Roman', # 设置字体类型\n # \"font.size\": 80,\n# \"mathtext.fontset\":'stix',\n}\nrcParams.update(config)\nfrom matplotlib.gridspec import GridSpec\nfrom matplotlib.gridspec import GridSpecFromSubplotSpec\nfrom matplotlib.gridspec import SubplotSpec\n\nimport pandas as pd\nimport numpy as np\n\ndef get_data(path,col):\n data=pd.read_csv(path,usecols=[col])\n data_np=np.array(data)\n return data_np[:,0]\n\n\nif __name__=='__main__':\n yolo_presicion=100*get_data(r'E:\\Yangdingming\\Downloads\\wandb_export_2021-04-01T09_20_21.721+08_00.csv','exp2 - metrics/precision')\n yolo_presicion=yolo_presicion[:224]\n faster_presicion=100*get_data(r'E:\\Yangdingming\\vs-code-projects\\faster-rcnn-tf2\\tensorboard\\run-.-tag-mean_detection_acc.csv','Value')\n yolo_loss=get_data(r'E:\\Yangdingming\\Downloads\\wandb_export_2021-04-01T09_22_02.817+08_00.csv','exp2 - train/box_loss')+get_data(r'E:\\Yangdingming\\Downloads\\wandb_export_2021-04-01T09_21_52.882+08_00.csv','exp2 - train/obj_loss')+get_data(r'E:\\Yangdingming\\Downloads\\wandb_export_2021-04-01T09_21_34.538+08_00.csv','exp2 - train/cls_loss')\n yolo_loss=yolo_loss[:224]\n faster_loss=get_data(r'E:\\Yangdingming\\vs-code-projects\\faster-rcnn-tf2\\tensorboard\\run-.-tag-total_loss.csv','Value')\n x=np.arange(0,len(yolo_presicion),1)\n x2=np.arange(0,len(faster_presicion),1)\n # plt.subplot(1,2,1)\n # plt.title('a:compare persicion')\n # plt.xlim(0,len(yolo_presicion))\n # plt.ylim(0,100)\n # plt.xlabel('epoch')\n # plt.ylabel('persicion')\n # # plt.plot(x,yolo_presicion,linewidth=2,color='g',label='yolov5')\n # plt.plot(x2,faster_presicion,linewidth=2,color='r',label='faster r-cnn')\n # plt.legend(loc='best')\n\n # plt.subplot(1,2,2)\n # plt.title('b:compare total loss')\n # plt.xlim(0,len(yolo_presicion))\n # plt.xlabel('epoch')\n # plt.ylabel('total loss')\n # plt.plot(x,yolo_loss,linewidth=1,color='g',label='yolov5')\n # # plt.plot(x2,faster_loss,linewidth=1,color='r',label='faster r-cnn')\n # plt.legend(loc='best')\n\n # plt.show()\n\n fig = plt.figure()\n ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4],xticklabels=[],ylim=(np.min(faster_presicion), np.max(faster_presicion)))\n ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4],ylim=(np.min(yolo_presicion), np.max(yolo_presicion)))\n ax1.set_title('a: compare precision')\n plt.xlabel('epoch')\n plt.ylabel('precision')\n ax1.plot(x,faster_presicion,linewidth=1,color='r',label='faster r-cnn')\n ax2.plot(x2,yolo_presicion,linewidth=1,color='g',label='yolov5')\n # ax2.yaxis.set_major_locator(MultipleLocator(20))\n ax1.legend(loc='best')\n ax2.legend(loc='best')\n plt.show()\n","repo_name":"huangyebiaoke/steel-pipe-weld-defect-detection","sub_path":"steel-tube-dataset-processing-and-analysis/test16.py","file_name":"test16.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"33"} +{"seq_id":"7777691755","text":"from typing import Dict, Tuple\nimport numpy as np\n\n\ndef find_solution_direct(meth_array: np.ndarray, states: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Fit linear model at each site of interest\"\"\"\n rates: np.ndarray = (np.sum((meth_array - np.mean(meth_array, axis=0)) * (states - np.mean(states)), axis=1)\n / np.sum((states - np.mean(states))**2))\n intercepts: np.ndarray = np.mean(meth_array, axis=1) - rates * np.mean(states)\n return rates, intercepts\n\n\ndef update_states(meth_array: np.ndarray = None,\n rates: np.ndarray = None, intercepts: np.ndarray = None) -> np.ndarray:\n \"\"\"Update state given by S = (m_hat_{i,j} - m_0) / r_i. For numerical simplicity actually calculate\n S = (r_i*\\\\hat{m}_{i,j} - m^{0}r_i)/(r_i^2))\"\"\"\n assert (rates.shape[0] == meth_array.shape[0]), f'Not a rate for every site, {rates.shape[0]} ' \\\n f'!= number of sites, {meth_array.shape[0]})'\n assert (intercepts.shape[0] == meth_array.shape[0]), f'Not an intercept for every site, {intercepts.shape[0]} ' \\\n f'!= number of sites, {meth_array.shape[0]})'\n return (np.dot(rates, meth_array) - np.sum(rates * intercepts)) / np.sum(rates ** 2)\n\n\ndef epm_expectation_maximization(meth_array: np.ndarray = None, states: np.ndarray = None,\n iter_limit: int = 100, error_tolerance: float = .00001) -> Dict[str, np.ndarray]:\n states = np.copy(np.asarray(states))\n em_iter = 0\n\n init_err, init_rates, init_intercepts = None, None, None\n\n while True:\n\n rates, intercepts = find_solution_direct(meth_array=meth_array, states=states)\n\n prev_err: float = calc_error(meth_array=meth_array, states=states, rates=rates, intercepts=intercepts)\n\n if not em_iter:\n init_err, init_rates, init_intercepts = prev_err, rates, intercepts\n\n em_iter += 1\n\n states_updated = update_states(meth_array=meth_array, rates=rates, intercepts=intercepts)\n\n new_err = calc_error(meth_array, states=states_updated, rates=rates, intercepts=intercepts)\n\n # calculate model improvement\n imp = prev_err - new_err\n\n assert (new_err < prev_err), f'new_err > prev_err: {new_err} vs {prev_err}'\n\n states = states_updated\n\n if em_iter == iter_limit:\n break\n elif imp < error_tolerance:\n break\n\n model_params = {'MC_error': init_err,\n 'MC_rates': init_rates,\n 'MC_intercepts': init_intercepts,\n 'EPM_error': new_err,\n 'EPM_rates': rates,\n 'EPM_intercepts': intercepts,\n 'EPM_iter': em_iter}\n\n return model_params\n\n\ndef calc_error(meth_array: np.array = None, states: np.array = None,\n rates: np.array = None, intercepts: np.array = None) -> float:\n total_error = 0.0\n number_sites, number_states = meth_array.shape\n for count, site in enumerate(meth_array):\n total_error += sum((site - states * rates[count] - intercepts[count]) ** 2)\n return np.sqrt(total_error / (number_sites * number_states))\n\n\ndef predict_epm_states(meth_array: np.ndarray = None,\n rates: np.ndarray = None, intercepts: np.ndarray = None) -> Dict[str, np.ndarray]:\n\n states_updated = update_states(meth_array=meth_array, rates=rates, intercepts=intercepts)\n\n new_err = calc_error(meth_array=meth_array, states=states_updated, rates=rates, intercepts=intercepts)\n\n return {'EPM_error': new_err, 'EPM_states': states_updated}\n\n","repo_name":"NuttyLogic/EpigeneticPacemaker","sub_path":"EpigeneticPacemaker/EPMCompute.py","file_name":"EPMCompute.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"32922179016","text":"from typing import Any\n\nimport pytest\n\nfrom src.board import Board, BoardTypeError\n\n\n@pytest.mark.parametrize(\"x,y\", [\n (1.1, 2),\n (2, True),\n (\"string\", 3)\n])\ndef test_non_int_arguments_raise_BoardTypeError(x: Any, y: Any):\n with pytest.raises(BoardTypeError):\n Board(x, y)\n","repo_name":"nibudd/pyzzle_calendar_solver","sub_path":"test/unit/board/test_init.py","file_name":"test_init.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"31571632243","text":"import os\nimport sys\nimport unittest\nimport mock\nfrom StringIO import StringIO\nimport json\nimport test_util as util\nsys.path.append('../')\nfrom lib.mm_connection import MavensMatePluginConnection\nimport lib.mm_util as mm_util\nimport mm\n\nclass MavensMateTest(unittest.TestCase):\n def get_plugin_client_settings(self):\n settings = {}\n settings['default'] = mm_util.parse_json_from_file(os.path.join(os.path.dirname(__file__),\"default_client_settings.json\"))\n settings['user'] = mm_util.parse_json_from_file(os.path.join(os.path.dirname(__file__),\"user_client_settings.json\"))\n return settings\n\n def redirectStdOut(self):\n new_target = StringIO()\n sys.stdout = new_target\n return new_target\n\n def setUp(self):\n self.output = StringIO()\n self.saved_stdout = sys.stdout\n sys.stdout = self.output\n self.settings = self.get_plugin_client_settings()\n MavensMatePluginConnection.get_plugin_client_settings = mock.Mock(return_value=self.settings)\n\n def tearDown(self):\n self.output.close()\n sys.stdout = self.saved_stdout\n\n def dict_to_string(self, dict):\n return json.dumps(dict)\n\n def set_stdin(self, dict):\n sys.stdin = StringIO(self.dict_to_string(dict))\n\ndef create_project(name=\"unit test project\", package=None):\n if package is None:\n package = { \"ApexClass\" : \"*\" } \n stdin = {\n \"project_name\" : name,\n \"username\" : \"mm@force.com\",\n \"password\" : \"force\",\n \"org_type\" : \"developer\",\n \"action\" : \"new\",\n \"package\" : package\n }\n mm_util.get_request_payload = mock.Mock(return_value=stdin)\n sys.argv = ['mm.py', '-o', 'new_project']\n mm.main()\n\n# if __name__ == '__main__':\n# unittest.main()\n\n","repo_name":"akshayas/mm","sub_path":"test/test_helper.py","file_name":"test_helper.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"2112737461","text":"encrypted = input()\nwhile True:\n command = input().split(\"|\")\n if command[0] == \"Decode\":\n break\n if command[0] == \"Move\":\n n = int(command[1])\n encrypted = encrypted[n:] + encrypted[:n]\n # beginning = list()\n # end = list()\n # for i in range(len(encrypted)):\n # if n > i:\n # beginning.append(encrypted[i])\n # else:\n # end.append(encrypted[i])\n # encrypted = \"\".join(end + beginning)\n elif command[0] == \"Insert\":\n index = int(command[1])\n value = command[2]\n encrypted = encrypted[:index] + value + encrypted[index:]\n elif command[0] == \"ChangeAll\":\n encrypted = encrypted.replace(command[1], command[2])\nprint(f\"The decrypted message is: {encrypted}\")","repo_name":"nikovmartin/SoftUni-Course","sub_path":"Python - Fundamentals/33_exam_prep/the_imitation_game.py","file_name":"the_imitation_game.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"37320638453","text":"import pygame\nimport settings\nfrom pygame.sprite import Sprite\nclass Platform(Sprite):\n def __init__(self,sim,x,y,width,height,colour):\n super().__init__()\n self.screen = sim.screen\n self.colour = colour\n self.width = width\n self.height = height\n self.x = x\n self.y = y\n self.rect = pygame.Rect(self.x,self.y,self.width,self.height)\n\n def draw_platform(self):\n pygame.draw.rect(self.screen,self.colour,self.rect)","repo_name":"kaito1121/Physics_sim","sub_path":"platform.py","file_name":"platform.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"71708407775","text":"from external_strings_utils import strtobool, InvalidStringValueException\nfrom shared_utils.account_helpers.diff_utils import synchronizeDicts\nfrom constants import SPA_ATTRS\n\nclass SPAFlags(object):\n\n def __init__(self, syncData):\n super(SPAFlags, self).__init__()\n self.__account = None\n self.__syncData = syncData\n self.__cache = {}\n self.__ignore = True\n return\n\n def onAccountBecomePlayer(self):\n self.__ignore = False\n\n def onAccountBecomeNonPlayer(self):\n self.__ignore = True\n\n def setAccount(self, account):\n self.__account = account\n\n def synchronize(self, diff):\n cacheDiff = diff.get('cache', None)\n spaCache = cacheDiff.get('SPA', None) if cacheDiff else None\n itemDiff = {}\n if spaCache:\n for key in SPA_ATTRS.toClientAttrs():\n value = spaCache.get(key, None)\n if value:\n try:\n itemDiff[key] = strtobool(value)\n except InvalidStringValueException:\n itemDiff[key] = value\n\n synchronizeDicts(itemDiff, self.__cache.setdefault('spaFlags', {}))\n return\n\n def getFlag(self, flagName):\n if self.__cache and 'spaFlags' in self.__cache:\n return self.__cache['spaFlags'].get(flagName, None)\n else:\n return","repo_name":"IzeBerg/wot-src","sub_path":"sources/res/scripts/client/account_helpers/spa_flags.py","file_name":"spa_flags.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"33"} +{"seq_id":"37693474966","text":"import pygame\n\nclass Scoring_System:\n \"\"\"Contains everything for keeping track of score, and drawing score\n \"\"\" \n \n def __init__(self, screen_size, text_factor_location, text_color, font_size, font_type):\n \"\"\"Scoring_System constructor\n\n Args:\n screen_size ((integer)tuple): should contain width and height of screen\n text_factor_location ((float)list): gets divided by screen_size to determine score drawing location EX: for center location [2,2]\n text_color ((integer)tuple): should contain r, g, b values, each ranges from 0-255\n font_size (integer): font size\n font_type (string): string of supported pygame fonts, EX: freesansbold.ttf\n \"\"\" \n self.screen_size = screen_size\n self.text_factor_location = text_factor_location\n self.text_color = text_color\n self.font_size = font_size\n self.font_type = font_type\n \n # these initialized variables are used to store required pygame objects for creating text\n self.text = ''\n self.font = ''\n self.text_container = ''\n \n # keeps track of current score of game\n self.score = 0;\n self.string_score = ''.join(['Score: ', str(self.score)])\n \n # flags for checking when score jumps a tens place\n self.double_flag = False\n self.triple_flag = False\n self.quad_flag = False\n \n # initializes text, font and drawing surface\n self.init_text()\n \n def init_text(self):\n \"\"\"initializes text, font and drawing surface\n \"\"\" \n # create font\n self.font = pygame.font.Font(self.font_type, self.font_size)\n \n # use font to render score and set color\n self.text = self.font.render(self.string_score, True, self.text_color)\n \n # gets the surface of the rendered text\n self.text_container = self.text.get_rect()\n \n # set location of rendered text\n self.text_container.center = (self.screen_size[0]//self.text_factor_location[0], self.screen_size[1]//self.text_factor_location[1])\n \n def draw(self, win):\n \"\"\"Handles the score drawing on screen\n\n Args:\n win (pygame.Surface): main window for displaying graphics\n \"\"\" \n # updates spacing on screen for new tenths place in score\n if self.score == 10 and not self.double_flag:\n self.text_factor_location[0] += .12\n self.text_container = self.text.get_rect()\n self.text_container.center = (self.screen_size[0] // self.text_factor_location[0], self.screen_size[1] // self.text_factor_location[1])\n self.double_flag = True\n elif self.score == 100 and not self.triple_flag:\n self.text_factor_location[0] += .12\n self.text_container = self.text.get_rect()\n self.text_container.center = (self.screen_size[0] // self.text_factor_location[0], self.screen_size[1] // self.text_factor_location[1])\n self.triple_flag = True\n elif self.score == 1000 and not self.quad_flag:\n self.text_factor_location[0] += .12\n self.text_container = self.text.get_rect()\n self.text_container.center = (self.screen_size[0] // self.text_factor_location[0], self.screen_size[1] // self.text_factor_location[1])\n self.quad_flag = True\n\n # updates rendered text each frame\n self.text = self.font.render(self.string_score, True, self.text_color)\n\n # draws text onto screen each frame\n win.blit(self.text ,self.text_container) \n \n def update_score(self):\n \"\"\"Increments score and updates string for rendering\n \"\"\" \n self.score += 1\n self.string_score = ''.join(['Score: ', str(self.score)])","repo_name":"SergioHPassos/Flappy-Bird-NEAT","sub_path":"score_system.py","file_name":"score_system.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"29112792006","text":"import torch\nfrom mol_predict.data_util import QM9qed_dataset,QM9U0_dataset\nfrom mol_predict.Train import Trainer\nfrom mol_predict.rGCN import RGCN as GCN_QED\nfrom config import Config\n\n\ntorch.set_default_tensor_type(torch.cuda.FloatTensor)\ndconfig = Config()\n\nload_model = True\n# file_path = dconfig.DATASET_PATH+'/gdb9_qed.pkl'\n# file_path = dconfig.DATASET_PATH+'/gdb9_U0.pkl'\nfile_path = ''\n# load_path = '/home/jeffzhu/MCTs/dataset/models_/0527_22_54.pkl'\nload_path = None\n\ntrain_dataset,valid_dataset,test_dataset = QM9qed_dataset(file_path,valid=True).Get_data()\n\nGCN_qed = GCN_QED(dconfig)\nprint(GCN_qed)\nif load_model:\n GCN_qed.load_state_dict(torch.load(load_path))\n\ntrainer = Trainer(model=GCN_qed,opt=dconfig)\n\ntrainer.train(train_dataset,valid_dataset)\n\n_,tloss = trainer.test(test_dataset,val=False)\n\nprint('test loss:',tloss)\nGCN_qed.save()\nprint('save success!')\n","repo_name":"HaoZhongkai/molgen","sub_path":"mol_predict/main_predict.py","file_name":"main_predict.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"33"} +{"seq_id":"22897404344","text":"\"\"\"\" Main connection to the postgres database \"\"\"\nimport json\nimport psycopg2\nfrom app.v2.models.database.maindb import set_up_tables, drop_tables\nfrom app.v2.models.usersmodel import Users\nfrom app.v2.views.mainview import response\nfrom flask import abort\n\nfrom flask import current_app as app\n\n\ndef initdb():\n \"\"\" initialize the class instance to take a database url as a\n parameter\"\"\"\n \n try:\n db_url = app.config[\"DATABASE_URL\"]\n conn = psycopg2.connect(db_url)\n cur = conn.cursor()\n tables = set_up_tables()\n for query in tables:\n cur.execute(query)\n print(query)\n conn.commit()\n conn.close()\n \n except Exception as error:\n return error\n\n\ndef db_conn():\n try:\n db_url = app.config[\"DATABASE_URL\"]\n conn = psycopg2.connect(db_url)\n cur = conn.cursor()\n return cur, conn\n\n except Exception as error:\n return error\n\n\ndef dropdb():\n try:\n db_url = app.config[\"DATABASE_URL\"]\n conn = psycopg2.connect(db_url)\n cur = conn.cursor()\n tables = drop_tables()\n for query in tables:\n cur.execute(query)\n conn.commit()\n conn.close()\n except Exception as error:\n return error\n\n\ndef query_db(query):\n try:\n cur, conn = db_conn()\n cur.execute(query)\n conn.commit()\n conn.close()\n except Exception as error:\n return error\n\n","repo_name":"rainbowcores/politico2","sub_path":"app/v2/models/database/database_config.py","file_name":"database_config.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"31909259430","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 19 16:59:29 2019\n\n@author: robert\n\"\"\"\n\nimport sys\n\nXYN = sys.stdin.readline().split()\n\nX = int(XYN[0])\nY = int(XYN[1])\nN = int(XYN[2])\n\nfor i in range(1, N + 1):\n if i % X == 0:\n if i % Y == 0:\n print(\"FizzBuzz\")\n else:\n print(\"Fizz\")\n elif i % Y == 0:\n print(\"Buzz\")\n else:\n print(i)\n \n ","repo_name":"rwboucher/kattis","sub_path":"fizzbuzz.py","file_name":"fizzbuzz.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"72920454175","text":"from os import path\nimport os\nfrom aip import AipOcr\nfrom wand.image import Image as wandImage\nimport re\nimport time\n\ndef baiduOCR(picfile,file):\n filename = path.basename(picfile)\n\n APP_ID = '15158569' # 刚才获取的 ID,下同\n API_KEY = 'ZoiSvOeob2XXilhrxOTquDx2'\n SECRECT_KEY = 'CjxZPDfzNXIaUFX21tTKhdCYQNxC48cE'\n client = AipOcr(APP_ID, API_KEY, SECRECT_KEY)\n\n i = open(picfile, 'rb')\n img = i.read()\n print(\"正在识别图片: \" + filename)\n message = client.basicGeneral(img) # 通用文字识别,每天 50 000 次免费\n #message = client.basicAccurate(img) # 通用文字高精度识别,每天 800 次免费\n if message:\n print(\"识别成功!\")\n i.close()\n print(message.get('words_result'))\n for text in message.get('words_result'):\n if re.search('请号:(\\d{5,15})',text['words']):\n rename_name = re.search('请号:(\\d{5,15})',text['words']).group(1)\n rename_name = rename_name +'.pdf'\n print(rename_name)\n os.rename(file,rename_name)\n\ndef get_img(filename):\n jpeg_name = file.split('.')[0]+'.png'\n with wandImage(filename=filename) as img:\n with img.convert('png') as converted:\n converted.save(filename=jpeg_name)\n return jpeg_name\n\nif __name__ == \"__main__\":\n files = os.listdir('./')\n\n for file in files: # 遍历文件夹\n if not os.path.isdir(file): # 判断是否是文件夹,不是文件夹才打开\n if file.split('.')[-1] == 'pdf':\n print('正在处理'+file)\n try:\n img_name = get_img(file)\n baiduOCR(img_name,file)\n except:\n print('处理失败')\n print('30秒后关闭。。。')\n time.sleep(30)","repo_name":"Geek-007/spiders","sub_path":"office/pdfOcr.py","file_name":"pdfOcr.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"33910743165","text":"from os import path, getenv\n\nfrom flask import Flask, redirect, request, render_template, session, flash\nfrom flask_babelex import Babel\nfrom flask_bootstrap import Bootstrap\nfrom flask_login import LoginManager\nfrom flask_migrate import Migrate\nfrom flask_qrcode import QRcode as QRCode\n\n\ndef create_app(config=None):\n \"\"\"\n Project app factory\n \"\"\"\n\n configs = {\"development\": \".development\", \"production\": \".production\", \"default\": \".default\"}\n\n if config not in configs:\n config = getenv(\"FLASK_ENVIRONMENT\", \"development\")\n\n config = \"app.config\" + configs[config]\n\n app = Flask(__name__)\n app.config.from_object(config)\n\n # import sentry_sdk\n # from sentry_sdk.integrations.flask import FlaskIntegration\n\n # sentry_sdk.init(dsn=app.config[\"SENTRY_DSN\"], integrations=[FlaskIntegration()])\n\n Bootstrap(app)\n QRCode(app)\n\n from app.models.models import db, Usuario\n from app.models.commands import populate\n\n app.app_context().push()\n db.init_app(app)\n\n # from app.controllers.forms.forms import LoginForm\n\n # @app.errorhandler(400)\n # def bad_request(error):\n # form_login = LoginForm(request.form)\n # return render_template(\"400.html\", form_login=form_login), 400\n\n # @app.errorhandler(404)\n # def page_not_found(error):\n # form_login = LoginForm(request.form)\n # return render_template(\"404.html\", form_login=form_login), 404\n\n # @app.errorhandler(500)\n # def internal_server_error(error):\n # form_login = LoginForm(request.form)\n # return render_template(\"500.html\", form_login=form_login), 500\n\n migrate = Migrate(app, db)\n\n @app.cli.command()\n def create():\n \"\"\"\n Creates database tables from sqlalchemy models\n \"\"\"\n db.create_all()\n populate()\n db.session.commit()\n\n @app.cli.command()\n def drop():\n \"\"\"\n Drops database tables\n \"\"\"\n prompt = input(\"Erase current database? [y/n]\")\n if prompt == \"y\":\n db.session.close_all()\n db.drop_all()\n db.session.commit()\n\n # from app.controllers.functions.email import mail\n\n # mail.init_app(app)\n\n from app.controllers.routes import admin#, gerenciar, participantes, views, conteudo, api\n\n # app.register_blueprint(gerenciar.gerenciar)\n # app.register_blueprint(participantes.participantes)\n # app.register_blueprint(views.views)\n # app.register_blueprint(conteudo.conteudo)\n # app.register_blueprint(api.api)\n\n upload_path = path.join(path.dirname(__file__), \"static\")\n adm = admin.init_app(app, upload_path)\n\n login_manager = LoginManager()\n login_manager.init_app(app)\n\n @login_manager.user_loader\n def user_loader(user_id):\n return db.session.query(Usuario).filter_by(id=user_id).first()\n\n @login_manager.unauthorized_handler\n def unauthorized_callback():\n return redirect(\"/login\")\n\n @login_manager.needs_refresh_handler\n def refresh_callback():\n flash(u\"Para proteção da sua conta, faça login novamente para poder acessar esta página.\")\n return redirect(\"/confirm-login\")\n\n babel = Babel(app)\n\n @babel.localeselector\n def get_locale():\n if request.args.get(\"lang\"):\n session[\"lang\"] = request.args.get(\"lang\")\n return \"pt\"\n\n return app\n","repo_name":"secompufscar/site-secomp","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"33"} +{"seq_id":"25625314607","text":"def solution(gems):\n cntMapper = {gems[0] : 1}\n lenKind = len(set(gems));\n lenGems = len(gems);\n\n answer = [0, 1000001]\n countedKind = 1;\n start = 0; end = 0;\n while True :\n if countedKind < lenKind :\n end += 1;\n if end == lenGems :\n break;\n if cntMapper.get(gems[end], 0) == 0 :\n cntMapper[gems[end]] = 1;\n countedKind += 1;\n else :\n cntMapper[gems[end]] += 1;\n else :\n if end - start < answer[1] - answer[0] :\n answer[0] = start + 1;\n answer[1] = end + 1;\n cntMapper[gems[start]] -= 1;\n if cntMapper.get(gems[start]) == 0 :\n countedKind -= 1;\n start += 1;\n return answer\n\ngems = [\"DIA\", \"RUBY\", \"RUBY\", \"DIA\", \"DIA\", \"EMERALD\", \"SAPPHIRE\", \"DIA\"];\nprint(solution(gems));","repo_name":"lss9209/CodingTest","sub_path":"2020 KAKAO INTERNSHIP/boseok_Shopping.py","file_name":"boseok_Shopping.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"22444077655","text":"#\n# basicGeneInfo.py\n#\n# Script to dump basic gene information from MGI in the AGR standard JSON format.\n# The format is described here:\n# https://github.com/alliance-genome/agr_schemas\n#\n# Usage:\n# To dump all genes and pseudogenes:\n# % python basicGeneInfo.py > FILE\n# \n# Author: Joel Richardson\n#\nimport sys\nfrom subprocess import Popen\nimport argparse\nimport json\nimport heapq\nimport itertools\nimport re\nimport os\nfrom AGRlib import stripNulls, buildMetaObject, sql\nfrom AGRqlib import qMcvTerms, qGenes, qGeneHasPhenotype, qGeneHasImpc, qGeneSynonyms, qGeneHasExpression, qGeneHasExpressionImage, qGeneLocations, qGeneProteinIds, qGeneXrefs, qGeneSecondaryIds\n\n#-----------------------------------\nMCV2SO_AUX = {\n #\"complex/cluster/region\"\n 6238175 : \"SO:0000110\",\n #\"cytogenetic marker\"\n 6238176 : \"SO:0000110\",\n #\"BAC/YAC end\"\n 6238177 : \"SO:0000110\",\n #\"other genome feature\"\n 6238178 : \"SO:0000110\",\n #\"DNA segment\"\n 6238179 : \"SO:0000110\",\n #\"unclassified gene\"\n 6238184 : \"SO:0000704\",\n #\"other feature type\"\n 6238185 : \"SO:0000110\",\n #\"unclassified non-coding RNA gene\"\n 6238186 : \"SO:0000704\",\n #\"unclassified cytogenetic marker\"\n 7222413 : \"SO:0000110\",\n #\"unclassified other genome feature\"\n 7648969 : \"SO:0000110\",\n #\"mutation defined region\"\n 11928467 : \"SO:0000110\",\n}\n\n#----------------------------------\nXREF_DBS = {\n \"Entrez Gene\": \"NCBI_Gene\",\n \"Ensembl Gene Model\": \"ENSEMBL\"\n}\n\n#-----------------------------------\n# Goes to PantherDB to get the download file, then parses the file to generate a mapping from MGI ids to Panther IDs.\n# Returns the map.\nPANTHERURL=\"ftp://ftp.pantherdb.org/ortholog/current_release/RefGenomeOrthologs.tar.gz\"\ndef getPantherIds () :\n def parseMouseId (s) :\n idPart = s.split(\"|\")[1]\n return \"MGI:\" + idPart.split(\"=\")[-1]\n\n def parseLine(line):\n parts = line.split()\n pthrId = parts[-1]\n if parts[0].startswith('MOUSE'):\n return (parseMouseId(parts[0]), pthrId)\n elif parts[1].startswith('MOUSE'):\n return (parseMouseId(parts[1]), pthrId)\n\n cmd = 'curl -o \"RefGenomeOrthologs.tar.gz\" -z \"RefGenomeOrthologs.tar.gz\" \"%s\"' % PANTHERURL\n sp = Popen(cmd, shell=True)\n rc = sp.wait()\n # tar outputs file names to stdout. Redirect to /dev/null so these don't end up\n # in the json file.\n cmd = 'tar -xvf RefGenomeOrthologs.tar.gz > /dev/null'\n sp = Popen(cmd, shell=True)\n rc = sp.wait()\n mgi2panther = {}\n with open('RefGenomeOrthologs','r') as fd:\n for line in fd:\n res = parseLine(line[:-1])\n if res:\n mgi2panther[res[0]] = res[1]\n return mgi2panther\n\n#-----------------------------------\n\nGLOBALTAXONID = os.environ[\"GLOBALTAXONID\"]\nMGD_OLD_PREFIX= os.environ[\"MGD_OLD_PREFIX\"]\n\n# For AGR, old style MGD ids must be given a distinct global prefix (we're using 'MGD_old:') and have \n# a stanza describing that kind of ID in the resourceDescriptors.yaml file. This routine adds the \n# prefix, if appropriate,\ndef formatSecondary(identifier):\n return (MGD_OLD_PREFIX if identifier.startswith(\"MGD-\") else \"\") + identifier\n\n# In the MGI fewi, mouse genes link to a MyGenes wiki page which is a human readable description.\n# The MyGenes page is for the HUMAN ortholog of the mouse gene.\n# In the database, human genes have a cross reference to MyGenes, where the \"id\" is the part needed\n# to fill out the complete URL (the base part if constant). \n# The link is only displayed if the mouse/human gene have a 1:1 orthology relationship.\n# Here we use the same logic to construct a link (or not) for the given mouse gene (obj).\n#\ndef formatMyGeneLink(obj):\n mgl = obj.get(\"myGeneLink\", [None])[0]\n if not mgl:\n return None\n symbol = mgl['homologues.homologue.crossReferences.identifier']\n # FIXME: Currently, the agr schema for global id's doesn't allow \":\" in the suffix part.\n # A few of these wiki links do, so we'll filter them out for now.\n # TODO: Ask DQMs to change the globalId pattern. Then remove this filter.\n return None if \":\" in symbol else {\"id\": \"WIKIP:\"+symbol}\n\n# Selects the xrefs to be exported for the object and formats them according to the spec.\n# - restricts which xrefs are exported\n# - translates provider name\n# - packs provider name and id into a object\n# - ensures uniqueness \n# Returns a list of cross reference objects.\n#\ndef formatXrefs(obj):\n xrefs = set()\n for x in obj.get(\"xrefs\",[]):\n dp = XREF_DBS.get(x[\"ldbName\"], None)\n if dp:\n xrefs.add((dp, x[\"accid\"]))\n for x in obj.get('proteinIds', []):\n p = x.get('proteinId','')\n if p:\n xrefs.add((\"UniProtKB\", p))\n pid = obj['pantherId']\n if pid:\n xrefs.add(('PANTHER', pid))\n xrefs = list(xrefs)\n xrefs.sort()\n # new xref format for 1.0.0.0. Includes 2 parts: the id, and a list of \n # page-tags (see resourceDescriptors.yaml)\n xrs = [{\"id\": x[0]+\":\"+x[1]} for x in xrefs]\n # add xrefs to MGI pages for this gene\n pgs = [\"gene\",\"gene/references\"]\n if obj.get('expressed', None):\n pgs.append(\"gene/expression\")\n if obj.get('expressedImages', None):\n pgs.append(\"gene/expression_images\")\n if obj.get('hasPheno', False):\n pgs.append('gene/phenotype')\n if obj.get('hasImpc', False):\n pgs.append('gene/phenotypes_impc')\n xrs.append({\"id\": obj[\"markerId\"], \"pages\":pgs })\n # add xref to MyGene page (if applicable)\n mgl = formatMyGeneLink(obj)\n if mgl: xrs.append(mgl)\n #\n return xrs\n\n\n# Format the genome location for the obj. The agr standard is to allow multiple\n# locations per object, but we will only have one. Even so, we have to return a list.\n# \ndef formatGenomeLocation(obj):\n\n loc = obj[\"location\"][0]\n if loc[\"genomicchromosome\"]:\n return [{\n \"assembly\" : loc['assembly'],\n \"chromosome\" : loc[\"genomicchromosome\"],\n \"startPosition\" : int(loc['startcoordinate']),\n \"endPosition\" : int(loc['endcoordinate']),\n \"strand\" : loc['strand']\n }]\n else:\n if loc[\"chromosome\"] and loc[\"chromosome\"] != 'UN':\n return [{\n \"assembly\" : '',\n \"chromosome\" : loc[\"chromosome\"]\n }]\n\ndef formatDescription (obj) :\n d = obj[\"description\"]\n if not d:\n return None\n return \"PHENOTYPE: %s [provided by MGI curators]\" % d\n\ndef getJsonObj(obj):\n #try:\n synonyms = []\n if 'synonyms' in obj:\n synonyms = [ r['synonym'] for r in obj['synonyms'] ]\n #\n secondaryIds = []\n if 'secondaryIds' in obj:\n secondaryIds = [ formatSecondary(r['accid']) for r in obj['secondaryIds'] ]\n #\n basicGeneticEntity = stripNulls({\n \"primaryId\" : obj[\"markerId\"],\n \"taxonId\" : GLOBALTAXONID,\n \"secondaryIds\" : secondaryIds,\n \"synonyms\" : [ s for s in synonyms if s != obj[\"symbol\"] and s != obj[\"name\"] ],\n \"crossReferences\" : formatXrefs(obj),\n \"genomeLocations\" : formatGenomeLocation(obj),\n })\n return stripNulls({\n \"basicGeneticEntity\": basicGeneticEntity,\n \"symbol\" : obj[\"symbol\"],\n \"name\" : obj[\"name\"],\n \"geneSynopsis\" : formatDescription(obj),\n \"soTermId\" : obj[\"soTermId\"],\n })\n\n#\ndef main():\n ##\n qs = [\n ('gene', qGenes),\n ('synonyms', qGeneSynonyms),\n ('secondaryIds', qGeneSecondaryIds),\n ('expressed', qGeneHasExpression),\n ('expressedImages', qGeneHasExpressionImage),\n ('location', qGeneLocations),\n ('proteinIds', qGeneProteinIds),\n ('xrefs', qGeneXrefs),\n ]\n\n mgi2panther = getPantherIds()\n\n # set of markers with phenotype annotations\n hasPheno = set()\n for r in sql(qGeneHasPhenotype):\n hasPheno.add(r['_marker_key'])\n\n # set of markers with alleles in the IMPC collection\n hasImpc = set()\n for r in sql(qGeneHasImpc):\n hasImpc.add(r['_marker_key'])\n\n # Mapping from MCV term key to SO id.\n # Initialize from the hard coded mappings\n # then load what's in the db (which is incomplete).\n mcv2so = MCV2SO_AUX.copy()\n so_re = re.compile(r'SO:[0-9]+')\n for r in sql(qMcvTerms):\n m = so_re.search(r['note'])\n if m:\n mcv2so[r['_term_key']] = m.group(0)\n\n id2gene = {}\n for label, q in qs:\n if label == 'gene':\n for r in sql(q):\n r['soTermId'] = mcv2so[r['_mcv_term_key']]\n r['pantherId'] = mgi2panther.get(r['markerId'], None)\n id2gene[r['_marker_key']] = r\n else:\n for r in sql(q):\n obj = id2gene.get(r['_marker_key'], None)\n if obj:\n obj.setdefault(label,[]).append(r)\n print('{\\n \"metaData\": %s,\\n \"data\": [' % json.dumps(buildMetaObject(), indent=2))\n first=True\n for i in id2gene:\n obj = id2gene[i]\n if not first: print(',', end='')\n obj[\"hasPheno\"] = obj[\"_marker_key\"] in hasPheno\n obj[\"hasImpc\"] = obj[\"_marker_key\"] in hasImpc\n print(json.dumps(getJsonObj(obj), indent=2))\n first = False\n print(']\\n}')\n\nmain()\n","repo_name":"mgijax/AGRdatafeed","sub_path":"bin/basicGeneInfo.py","file_name":"basicGeneInfo.py","file_ext":"py","file_size_in_byte":9537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"19787492832","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom src.linearRegressionGD import LinearRegressionGD\n\nfrom src.utils import *\n\n# https://towardsdatascience.com/linear-regression-using-python-b136c91bf0a2\n\n\nnp.random.seed(0)\nx = np.random.rand(100,1)\nx_train = np.c_[np.ones((x.shape[0], 1)), x]\ny = 2 + 3 * x + np.random.rand(100,1)\n\nmodel = LinearRegressionGD()\nmodel.fit(x_train, y)\n\ny_pred = model.predict(x_train)\nrmse = calculate_rmse(y, y_pred)\nr_squared = calculate_r_squared(y_pred, y)\n\nprint(f'Slope is: {model.coef_}')\nprint(f'Intercept is: {model.intercept_}')\nprint(f'RMSE is: {rmse}')\nprint(f'R**2 is: {r_squared}')\n\n\nabline(model.coef_, model.intercept_)\nplt.scatter(x, y_pred, s=10, color='g')\nplt.scatter(x, y, s=10)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.show()\n","repo_name":"boisbb/ml-self-study","sub_path":"Linear_Regression/p1_LRGD.py","file_name":"p1_LRGD.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"35616343138","text":"from typing import List\nimport argparse\nimport sys\nimport subprocess\nfrom p_tqdm import p_map\nfrom glob import glob\nfrom pathlib import Path\nfrom functools import partial\n\n\ndef parse_args(args: List[str]) -> argparse.Namespace:\n \"\"\"\n Utility argument parser function for batch audio conversion.\n\n Args:\n args (List[str]):\n List of arguments.\n\n Returns:\n argparse.Namespace:\n Objects with arguments values as attributes.\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"python scripts/aac_to_wav.py\",\n description=\"Batch-convert aac audios in a folder to wav format with ffmpeg.\",\n )\n\n parser.add_argument(\n \"-i\",\n \"--input_dir\",\n type=str,\n required=True,\n help=\"Directory of input audios to convert.\",\n )\n parser.add_argument(\n \"-c\",\n \"--channel\",\n type=int,\n default=1,\n help=\"Number of audio channels in output.\",\n )\n parser.add_argument(\n \"-r\", \"--rate\", type=int, default=16_000, help=\"Sample rate of audio output.\"\n )\n return parser.parse_args(args)\n\n\ndef convert_to_wav(\n input_audio_path: str, num_channels: int = 1, sampling_rate: int = 16_000\n) -> subprocess.CompletedProcess:\n \"\"\"\n Convert aac audio file to wav at same directory.\n\n Args:\n input_audio_path (str):\n Path to aac file.\n num_channels (int, optional):\n Number of output audio channels. Defaults to `1`.\n sampling_rate (int, optional):\n Output audio sampling rate. Defaults to `16_000`.\n\n Returns:\n subprocess.CompletedProcess:\n Finished subprocess.\n \"\"\"\n # replace input file's extension to wav as output file path\n output_audio_path = Path(input_audio_path).with_suffix(\".wav\")\n\n # equivalent to:\n # ffmpeg -i {input_audio_path} -acodec pcm_s16le -ac {num_channels} \\\n # -ar {sampling_rate} {output_audio_path}\n job = subprocess.run(\n [\n \"ffmpeg\",\n \"-loglevel\",\n \"quiet\",\n \"-hide_banner\",\n \"-y\",\n \"-i\",\n input_audio_path,\n \"-acodec\",\n \"pcm_s16le\",\n \"-ac\",\n str(num_channels),\n \"-ar\",\n str(sampling_rate),\n str(output_audio_path),\n ],\n stderr=subprocess.DEVNULL,\n stdout=subprocess.DEVNULL,\n stdin=subprocess.PIPE,\n )\n\n return job\n\n\nif __name__ == \"__main__\":\n args = parse_args(sys.argv[1:])\n audios = glob(f\"{args.input_dir}/**/*.aac\", recursive=True)\n fn = partial(convert_to_wav, num_channels=args.channel, sampling_rate=args.rate)\n _ = p_map(fn, audios)\n","repo_name":"bookbot-kids/speechline","sub_path":"scripts/aac_to_wav.py","file_name":"aac_to_wav.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"35548041346","text":"from configparser import ConfigParser\nimport discord\nfrom discord.ext import commands\nfrom scripts import *\nimport sentry_sdk\nimport asyncio\nimport sys\nimport os\nimport re\n\n\nevent_loop = asyncio.get_event_loop()\n\n\nclass Bot(commands.Bot):\n def __init__(self, conf):\n super().__init__(command_prefix='$', description='PM2 from discord', loop=event_loop)\n self.conf = conf\n self.shell = None\n\n self.load_extension('cogs.admin')\n self.load_extension('cogs.squad')\n\n @staticmethod\n async def on_ready():\n sentry_sdk.capture_message(\"Logged in!\")\n\n async def on_message(self, message):\n if message.author.id not in list(on_message_users.keys()):\n for user_id, regex in on_message_users.items():\n if re.match(regex, str(message.content).lower()):\n await self.send_notification(message, user_id)\n\n await Bot.process_commands(self, message=message)\n\n async def send_notification(self, message, user_discord_id):\n message_url = f'https://discordapp.com/channels/{message.guild.id}/{message.channel.id}/{message.id}'\n embed = discord.Embed(title=f'{message.author} said')\n\n embed.add_field(name='Server:', value=message.guild.name, inline=True)\n embed.add_field(name='Channel:', value=message.channel.mention, inline=True)\n embed.add_field(name='Author:', value=message.author, inline=True)\n embed.add_field(name='Time (UTC):', value=message.created_at.strftime('%B %d, %Y at %I:%M:%S %p %Z'), inline=True)\n embed.add_field(name='Message Link:', value=message_url)\n embed.add_field(name='Message:', value=message.clean_content, inline=False)\n\n await Bot.get_user(self, id=user_discord_id).send(embed=embed)\n\n def run(self):\n super().run(self.conf.get('global', 'discord_id'))\n\n\nclass Config:\n conf = None\n\n @staticmethod\n def initiate_config():\n try:\n Config.conf = ConfigParser()\n os.chdir(sys.path[0])\n if os.path.exists('conf.ini'):\n Config.conf.read('conf.ini')\n else:\n sentry_sdk.capture_message('Config file, conf.ini, was not found.')\n return False\n\n return True\n\n except Exception as e:\n sentry_sdk.capture_message(\"Could not initiate conf.\")\n sentry_sdk.capture_exception(e)\n return False\n\n\ndef main():\n if Config.initiate_config():\n sentry_sdk.init(Config.conf.get('global', 'sentry_init'))\n bot = Bot(Config.conf)\n bot.run()\n else:\n sys.exit()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"mandjevant/pm2_from_discord","sub_path":"pm2_main.py","file_name":"pm2_main.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"30810975463","text":"from turtle import left\nimport pygame\n\npygame.init()\npygame.mixer.init()\n\nfps = 60\nlogo = pygame.image.load('source\\logo.png')\nimg_bg = pygame.image.load('source\\\\bg.png')\ntitle = 'Hauzan The Adventurer'\n\nfullScreen = pygame.display.get_desktop_sizes()\ndisplay = pygame.display.set_mode(fullScreen[1])\nclock = pygame.time.Clock()\n\npygame.display.set_icon(logo)\npygame.display.set_caption(title)\n\nclass obj_world:\n def __init__(self) -> None:\n self.pos_x = 0\n\n def CreateWorld(self, world_pos_x):\n self.pos_x -= world_pos_x\n display.fill((109, 237, 165))\n display.blit(img_bg, (self.pos_x,0))\n\nclass obj_player:\n def __init__(self, pos_x, pos_y):\n super().__init__()\n self.state_player = []\n self.state_stand = []\n self.state_walk = []\n self.state_jump = []\n self.state_lose = []\n\n self.state_player.append(self.state_stand)\n self.state_player.append(self.state_walk)\n self.state_player.append(self.state_jump)\n self.state_player.append(self.state_lose)\n\n #0\n self.state_stand.append(pygame.image.load('source\\Stand\\pixil-frame-0 (2).png').convert_alpha())\n self.state_stand.append(pygame.image.load('source\\Stand\\pixil-frame-1.png').convert_alpha())\n self.state_stand.append(pygame.image.load('source\\Stand\\pixil-frame-2.png').convert_alpha())\n\n #1\n self.state_walk.append(pygame.image.load('source\\Walk\\pixil-frame-0 (2).png').convert_alpha())\n self.state_walk.append(pygame.image.load('source\\Walk\\pixil-frame-1.png').convert_alpha())\n self.state_walk.append(pygame.image.load('source\\Walk\\pixil-frame-2.png').convert_alpha())\n self.state_walk.append(pygame.image.load('source\\Walk\\pixil-frame-3.png').convert_alpha())\n self.state_walk.append(pygame.image.load('source\\Walk\\pixil-frame-4.png').convert_alpha())\n self.state_walk.append(pygame.transform.flip(pygame.image.load('source\\Walk\\pixil-frame-0 (2).png').convert_alpha(), True, False))\n self.state_walk.append(pygame.transform.flip(pygame.image.load('source\\Walk\\pixil-frame-1.png').convert_alpha(), True, False))\n self.state_walk.append(pygame.transform.flip(pygame.image.load('source\\Walk\\pixil-frame-2.png').convert_alpha(), True, False))\n self.state_walk.append(pygame.transform.flip(pygame.image.load('source\\Walk\\pixil-frame-3.png').convert_alpha(), True, False))\n self.state_walk.append(pygame.transform.flip(pygame.image.load('source\\Walk\\pixil-frame-4.png').convert_alpha(), True, False))\n \n #2\n self.state_jump.append(pygame.image.load('source\\Jump\\pixil-frame-0 (2).png').convert_alpha())\n self.state_jump.append(pygame.image.load('source\\Jump\\pixil-frame-1.png').convert_alpha())\n self.state_jump.append(pygame.image.load('source\\Jump\\pixil-frame-2.png').convert_alpha())\n self.state_jump.append(pygame.image.load('source\\Jump\\pixil-frame-3.png').convert_alpha())\n self.state_jump.append(pygame.transform.flip(pygame.image.load('source\\Jump\\pixil-frame-0 (2).png').convert_alpha(), True, False))\n self.state_jump.append(pygame.transform.flip(pygame.image.load('source\\Jump\\pixil-frame-1.png').convert_alpha(), True, False))\n self.state_jump.append(pygame.transform.flip(pygame.image.load('source\\Jump\\pixil-frame-2.png').convert_alpha(), True, False))\n self.state_jump.append(pygame.transform.flip(pygame.image.load('source\\Jump\\pixil-frame-3.png').convert_alpha(), True, False))\n\n #3\n self.state_lose.append(pygame.image.load('source\\lose\\pixil-frame-0 (2).png').convert_alpha())\n self.state_lose.append(pygame.image.load('source\\lose\\pixil-frame-1.png').convert_alpha())\n self.state_lose.append(pygame.image.load('source\\lose\\pixil-frame-2.png').convert_alpha())\n\n self.num_state = 0\n self.state = 0\n self.pos_x = pos_x\n self.pos_y = pos_y\n self.fly = True\n self.comd_lose = False\n \n self.border_back = False\n self.border_front = False\n self.border_world_x = [0,1440]\n self.world_pos_x = 0\n\n self.font = pygame.font.SysFont('impact', 60)\n self.text_lose = self.font.render('You Loser :p', True, (255, 51, 51))\n self.text_win = self.font.render('You Won:D', True, (82, 255, 79))\n\n self.transparant_screen = pygame.Surface((1440, 900))\n self.transparant_screen.set_alpha(150)\n self.transparant_screen.fill((64, 64, 64))\n self.show_screen_lose = False\n self.show_screen_win = False\n\n #Sound Effect\n self.jump_sound = pygame.mixer.Sound('source\\sound\\jump_sf.mp3')\n self.run_sound = pygame.mixer.Sound(\"source\\sound\\\\run_sf_cut.wav\")\n self.won_sound = pygame.mixer.Sound('source\\sound\\won_notif.mp3')\n self.lose_sound = pygame.mixer.Sound('source\\sound\\lose_notif.wav')\n self.replay_sound = False\n\n def move(self, left_key, right_key, up_key):\n self.player_rect = pygame.Rect(self.pos_x, self.pos_y, 180, 240)\n #pygame.draw.rect(display,(255, 117, 107), (0,0,450,770))\n #pygame.draw.rect(display,(107, 235, 255), (990,0,450,770))\n self.rect_back = pygame.Rect(0,0,450,770)\n self.rect_front = pygame.Rect(990,0,450,770)\n\n # Fungsi ketika kalah\n if self.comd_lose == True:\n self.state = 3\n left_key == False\n right_key == False\n if self.fly == False:\n self.pos_y -= 10\n if self.pos_y <= 400:\n self.num_state = 3\n self.fly = True\n elif self.pos_y <= 450:\n self.num_state = 2\n elif self.pos_y <= 500:\n self.num_state = 1\n elif self.pos_y <= 520:\n self.num_state = 0\n if self.fly == True:\n self.pos_y += 10\n if self.pos_y <= 400:\n self.num_state = 3\n elif self.pos_y <= 450:\n self.num_state = 2\n elif self.pos_y <= 500:\n self.num_state = 1\n elif self.pos_y <= 540:\n self.num_state = 0\n self.show_screen_lose = True\n\n print(right_key)\n #print(self.state)\n #print(float(self.num_state))\n\n # Fungsi ketika menang \n elif self.comd_lose == False:\n\n #Gerakan ketika menang\n if self.show_screen_win == True:\n left_key = False\n right_key = False\n up_key = True\n if self.replay_sound == False:\n self.won_sound.play()\n self.replay_sound = True\n elif self.replay_sound == True:\n pass\n\n # Pendeteksi player menyentuh tanah\n if ground.colliderect(self.player_rect):\n self.fly = False\n self.state = 0\n \n # Gerakan ketika terbang/ tidak ditanah\n else:\n self.fly = True\n self.pos_y += 10\n self.state = 2\n if left_key == False and right_key == False:\n if self.pos_y <= 400:\n self.num_state = 3\n elif self.pos_y <= 450:\n self.num_state = 2\n elif self.pos_y <= 500:\n self.num_state = 1\n elif self.pos_y <= 540:\n self.num_state = 0\n elif left_key == True:\n if self.border_back == True:\n pass\n else:\n if self.pos_x > 0:\n self.pos_x -= 5\n if self.pos_y <= 400:\n self.num_state = 7\n elif self.pos_y <= 450:\n self.num_state = 6\n elif self.pos_y <= 500:\n self.num_state = 5\n elif self.pos_y <= 520:\n self.num_state = 4\n elif right_key == True:\n if self.border_front == True:\n pass\n else:\n if self.pos_x < 1240:\n if self.comd_lose == False:\n self.pos_x += 5\n else:\n self.show_screen_win = True\n if self.pos_y <= 400:\n self.num_state = 3\n elif self.pos_y <= 450:\n self.num_state = 2\n elif self.pos_y <= 500:\n self.num_state = 1\n elif self.pos_y <= 520:\n self.num_state = 0\n\n # Pendeteksi Border\n if self.rect_back.colliderect(self.player_rect):\n if self.world_pos_x <= 0:\n pass\n else:\n self.border_back = True\n elif self.rect_front.colliderect(self.player_rect):\n if self.world_pos_x >= 960:\n pass\n else:\n self.border_front = True\n else:\n self.border_back = False\n self.border_front = False\n\n # Gerakan ketika ditanah\n if self.fly == False:\n if left_key == False and right_key == False and up_key == False:\n self.num_state += 0.4\n if self.num_state >= len(self.state_stand):\n self.num_state = 0\n self.border_back = False\n self.border_front = False\n self.run_sound.stop()\n if left_key == True:\n self.state = 1\n self.num_state += 0.5\n self.run_sound.play()\n pygame.mixer.set_num_channels(1)\n if self.num_state >= len(self.state_walk)/2:\n self.num_state = 0\n\n if self.border_back == True:\n pass\n else:\n if self.pos_x >0:\n self.pos_x -= 10\n if right_key == True:\n self.state = 1\n self.num_state += 0.5\n self.run_sound.play()\n pygame.mixer.set_num_channels(1)\n if self.num_state <= len(self.state_walk)/2:\n self.num_state = len(self.state_walk)/2\n elif self.num_state >= len(self.state_walk):\n self.num_state = len(self.state_walk)/2\n\n if self.border_front == True:\n pass\n else:\n if self.pos_x < 1240:\n if self.comd_lose == False:\n self.pos_x += 10\n else:\n self.show_screen_win = True\n if up_key == True:\n self.pos_y -= 160\n self.run_sound.stop()\n if self.show_screen_win == False:\n self.jump_sound.play()\n\n if self.state == 3:\n if self.num_state > 3:\n self.num_state = 3\n if self.num_state < 0:\n self.num_state = 0\n\n # Tampilan dilayar\n \n print(self.state)\n print(float(self.num_state))\n try:\n display.blit(self.state_player[self.state][int(self.num_state)], (self.pos_x,self.pos_y))\n except IndexError as e:\n print('error cok')\n print(self.state)\n print(float(self.num_state))\n self.lose_sound.play()\n\n\n def make_rect(self):\n if self.comd_lose == True:\n player_rect = pygame.Rect(self.pos_x, self.pos_y, 0, 0)\n else:\n player_rect = pygame.Rect(self.pos_x, self.pos_y, 180, 240)\n return player_rect\n\n def BorderMove(self):\n if self.border_back == False and self.border_front == False:\n pass\n elif self.border_back == True:\n if self.world_pos_x <= 0:\n pass\n else:\n self.world_pos_x -= 10\n elif self.border_front == True:\n if self.world_pos_x >= 960:\n pass\n else:\n self.world_pos_x += 10\n \n return self.world_pos_x\n \n def lose(self):\n self.lose_sound.play()\n self.comd_lose = True\n\n def LoseScreen(self):\n if self.show_screen_lose == True:\n display.blit(self.transparant_screen, (0,0))\n display.blit(self.text_lose, (450, 300))\n\n def WinScreen(self):\n if self.show_screen_win == True:\n display.blit(self.transparant_screen, (0,0))\n display.blit(self.text_win, (450, 300))\n\nclass obj_mobs:\n def __init__(self, pos_x, pos_y) -> None:\n self.state_mobs = []\n self.state_mobs.append(pygame.transform.scale(pygame.image.load('source\\Mobs\\pixil-frame-0 (3).png').convert_alpha(), (140, 140)))\n self.state_mobs.append(pygame.transform.scale(pygame.image.load('source\\Mobs\\pixil-frame-1.png').convert_alpha(), (140, 140)))\n self.state_mobs.append(pygame.transform.scale(pygame.image.load('source\\Mobs\\pixil-frame-2.png').convert_alpha(), (140, 140)))\n self.state_mobs.append(pygame.transform.scale(pygame.transform.flip(pygame.image.load('source\\Mobs\\pixil-frame-0 (3).png').convert_alpha(), True, False), (140, 140)))\n self.state_mobs.append(pygame.transform.scale(pygame.transform.flip(pygame.image.load('source\\Mobs\\pixil-frame-1.png').convert_alpha(), True, False), (140, 140)))\n self.state_mobs.append(pygame.transform.scale(pygame.transform.flip(pygame.image.load('source\\Mobs\\pixil-frame-2.png').convert_alpha(), True, False), (140, 140)))\n\n self.pos_x = pos_x\n self.pos_y = pos_y\n \n self.state = 0\n self.num_step = 3\n self.loop = True\n self.comd_lose = False\n\n def move(self, world_pos_x):\n display.blit(self.state_mobs[int(self.state)], (self.pos_x - world_pos_x, self.pos_y))\n\n if self.comd_lose == True:\n if self.num_step >= 0 and self.num_step <= 2.8:\n self.num_step = 0\n if self.loop == False:\n self.pos_y -= 10\n self.loop = True\n else:\n self.pos_y += 10\n else:\n self.num_step = 3\n if self.loop == False:\n self.pos_y -= 10\n self.loop = True\n else:\n self.pos_y += 10\n\n else:\n if self.num_step >= 0:\n if self.state <= 0.2:\n self.state += 0.04\n elif self.state < 1: \n self.pos_x += 5\n self.state += 0.2\n elif self.state < 2:\n self.pos_x += 5\n self.state += 0.2\n elif self.state < 2.8:\n self.pos_x += 5\n self.state += 0.2\n elif self.state >= 2.8: \n self.state = 0\n self.num_step -= 1\n else:\n if self.state <= 2:\n self.state = 3\n elif self.state <= 3.2:\n self.state += 0.04\n elif self.state < 4: \n self.pos_x -= 5\n self.state += 0.2\n elif self.state < 5:\n self.pos_x -= 5\n self.state += 0.2\n elif self.state < 5.8:\n self.pos_x -= 5\n self.state += 0.2\n elif self.state >= 5.8: \n self.state = 3\n self.num_step -= 1\n\n if self.num_step == -5:\n self.num_step = 4\n\n def make_rect(self, world_pos_x):\n mobs_rect = []\n if self.comd_lose == False:\n top = pygame.Rect(self.pos_x+25 - world_pos_x, self.pos_y+53, 80, 25)\n bottom = pygame.Rect(self.pos_x+10 - world_pos_x, self.pos_y+75, 115, 40)\n mobs_rect.append(top)\n mobs_rect.append(bottom)\n #pygame.draw.rect(display, (77, 227, 224), (self.pos_x+10, self.pos_y+75, 115, 40))\n #pygame.draw.rect(display, (247, 64, 116), (self.pos_x+25, self.pos_y+53, 80, 25))\n elif self.comd_lose == True:\n mobs_none = pygame.Rect(0, 0, 0, 0)\n mobs_rect.append(mobs_none)\n mobs_rect.append(mobs_none)\n return mobs_rect\n\n def lose(self):\n self.comd_lose = True\n self.loop = False\n \n\ndef BuildSurface(left_key, right_key, up_key):\n global world_pos_x\n world1 = obj_world()\n world_pos_x = player.BorderMove()\n\n world1.CreateWorld(world_pos_x)\n mobs1.move(world_pos_x)\n player.move(left_key, right_key, up_key)\n \n\ndef Main():\n global player, mobs1, ground, left_key, right_key, up_key\n player = obj_player(600, 300)\n mobs1 = obj_mobs(900, 660)\n ground = pygame.Rect(0,770, 2400,300)\n \n\n clock.tick(fps)\n run = True\n while run:\n for event in pygame.event.get():\n if event.type == pygame.QUIT or pygame.key.get_pressed()[pygame.K_ESCAPE]:\n run = False\n \n keys = pygame.key.get_pressed()\n left_key = False\n right_key = False\n up_key = False\n if keys[pygame.K_LEFT]:\n left_key = True\n if keys[pygame.K_UP]:\n up_key = True\n if keys[pygame.K_RIGHT]:\n right_key = True\n\n\n BuildSurface(left_key, right_key, up_key)\n\n mobs_rect = mobs1.make_rect(world_pos_x)\n player_rect = player.make_rect()\n\n if player_rect.colliderect(mobs_rect[0]):\n mobs1.lose()\n elif player_rect.colliderect(mobs_rect[1]):\n player.lose()\n else:\n pass\n\n player.LoseScreen()\n player.WinScreen()\n\n pygame.display.update()\n pygame.quit()\n\nif __name__ == \"__main__\":\n Main()","repo_name":"HauzanTsaaqif/Super-Hauzan-Bros","sub_path":"SuperHauzanBros.py","file_name":"SuperHauzanBros.py","file_ext":"py","file_size_in_byte":18532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"19290184286","text":"import numpy as np\nimport math \nimport time\nimport numba as nb\nfrom numba import jit, typed\nimport sys\n\n@nb.njit(parallel=True)\ndef isin(a, b):\n out=np.empty(a.shape[0], dtype=nb.boolean)\n b = set(b)\n for i in nb.prange(a.shape[0]):\n if a[i] in b:\n out[i]=True\n else:\n out[i]=False\n return out\n\ndef read_batches(args,train_data,neighbor_finder,num_embeddings):\n BATCH_SIZE = args.bs\n n_degree=args.n_degree\n num_instance = len(train_data.sources)\n num_batch = math.ceil(num_instance/BATCH_SIZE)\n\n total_n_in=0\n total_n_unique_in=0\n total_n_out=0\n total_n_unique_out=0\n\n target_list = typed.List()\n ngh_list = typed.List()\n occur_list = typed.List()\n \n for _ in range(num_embeddings):\n empty_list=typed.List()\n empty_list.append((0,0))\n occur_list.append(empty_list)\n\n for batch_idx in range(0, num_batch):\n start_idx = batch_idx * BATCH_SIZE\n end_idx = min(num_instance, start_idx + BATCH_SIZE)\n sample_inds=np.array(list(range(start_idx,end_idx)))\n\n sources_batch, destinations_batch = train_data.sources[sample_inds],train_data.destinations[sample_inds]\n timestamps_batch = train_data.timestamps[sample_inds]\n\n source_nodes = np.concatenate([sources_batch, destinations_batch])\n timestamps = np.concatenate([timestamps_batch, timestamps_batch])\n\n neighbors, _, _ = neighbor_finder.get_temporal_neighbor(source_nodes,timestamps,n_degree)\n neighbors=neighbors[neighbors!=0] #[400,10] => 1 dimensional array\n\n unique_target=np.unique(source_nodes)\n unique_neighbors=np.unique(neighbors)\n\n\n # unique in-batch nerighbors\n unique_in = np.intersect1d(unique_target, unique_neighbors)\n in_index = np.isin(neighbors,unique_in)\n \n n_in = np.count_nonzero(in_index)\n n_unique_in = len(unique_in)\n total_n_in += n_in\n total_n_unique_in+=n_unique_in\n\n # index of those in-batch neighbors\n out_index = ~in_index\n out = neighbors[out_index]\n unique_out=np.unique(out)\n\n n_out= len(out)\n n_unique_out = len(unique_out) \n total_n_out += n_out\n total_n_unique_out+=n_unique_out\n\n target_list.append(unique_target) # unique target nodes\n ngh_list.append(out) # not unique out-of-batch neighbors\n \n # * update occur list\n for target in unique_target:\n occur_list[target].append((batch_idx,0)) # * 0 means target node\n\n for ngh in unique_out:\n occur_list[ngh].append((batch_idx,1)) # * 1 means neighbor node\n\n for i in range(num_embeddings): # * 2 means end-of-the batch\n occur_list[i].append((num_batch,2))\n\n return num_batch,target_list,ngh_list,occur_list,total_n_in,total_n_unique_in,total_n_out,total_n_unique_out\n\n\n@jit(nopython=True)\ndef MRD_numba(num_embeddings,num_batch,budget,target_list,ngh_list,occur_list):\n \n MAX_DISTANCE=100000000\n n_reuse=0\n n_recompute=0\n total_reuse_distance = 0\n\n cache_plan_list=[]\n cache_flag=np.zeros(num_embeddings)\n time_flag=np.zeros(num_embeddings)\n\n # index starts from 1 because of the we have padded dummpy nodes in the occur_list\n index_list= np.ones(num_embeddings,np.int32) \n\n for batch_idx in range(num_batch):\n\n target=target_list[batch_idx]\n ngh=ngh_list[batch_idx] # not unique because we want to compute n_recompute and n_reuse\n \n cache_=cache_flag[ngh]\n index=np.where(cache_==0)[0]\n uncached_ngh=ngh[index] \n n_recompute+=len(uncached_ngh)\n \n index=np.where(cache_==1)[0]\n cached_ngh=ngh[index]\n n_reuse+=len(cached_ngh)\n\n # reuse distance of cache neighbors\n total_reuse_distance+= np.sum(batch_idx - time_flag[cached_ngh])\n cached=np.where(cache_flag==1)[0] # * unique newly computed nodes\n new_computed = np.concatenate((uncached_ngh,target))\n new_computed = np.unique(new_computed)\n candidates=np.concatenate((uncached_ngh,cached,target)) # * unique candidates nodes\n candidates=np.unique(candidates)\n\n reuse_distance_list=[]\n for node in candidates: \n occur_index=index_list[node]\n occurs=occur_list[node]\n while occurs[occur_index][0]<=batch_idx: \n occur_index+=1\n\n state=occurs[occur_index]\n id = state[0]\n value = state[1]\n index_list[node]=occur_index\n \n if value == 0: # target node\n reuse_distance_list.append(MAX_DISTANCE+1)\n elif value ==2: # not appear anymore\n reuse_distance_list.append(MAX_DISTANCE+1)\n else: # neighbor node\n reuse_distance_list.append(id-batch_idx)\n\n\n # sort by the next reuse time\n reuse_distance_list=np.array(reuse_distance_list)\n sorted_inds=np.argsort(reuse_distance_list)\n sorted_nodes=candidates[sorted_inds]\n\n to_cache=sorted_nodes[:budget]\n cache_flag=np.zeros(num_embeddings)\n cache_flag[to_cache]=1\n cache_plan_list.append(to_cache)\n\n # update the time flag, which is used for computing reuse distance\n new_index = isin(to_cache,new_computed) \n new_nodes = to_cache[new_index]\n time_flag[new_nodes]=batch_idx\n\n \n average_reuse_distance = total_reuse_distance/n_reuse\n return cache_plan_list, n_reuse, n_recompute, average_reuse_distance\n\n\n\n\n\n\n\n############################################# 2Q #############################################\n@jit(nopython=True)\ndef TwoQ_numba(num_embeddings,num_batch,budget,target_list,ngh_list):\n\n half_budget = budget//2\n\n n_FIF_cached=0\n n_LRU_cached=0\n n_reuse=0\n n_recompute=0\n total_reuse_distance = 0\n \n cache_plan_list=[]\n LRU_cache_flag=np.zeros(num_embeddings)\n LRU_time_flag=np.zeros(num_embeddings)\n LRU_arrive_time=np.zeros(num_embeddings)\n\n FIF_cache_flag=np.zeros(num_embeddings)\n FIF_time_flag=np.zeros(num_embeddings)\n FIF_arrive_time=np.zeros(num_embeddings)\n\n\n for batch_idx in range(num_batch):\n ngh=ngh_list[batch_idx] \n\n ######### FIF part #########\n FIF_cache_=FIF_cache_flag[ngh]\n\n # FIF cached neighbors => move to LRU # not unique\n index=np.where(FIF_cache_==1)[0]\n FIF_cached_nghs=ngh[index]\n n_reuse+=len(FIF_cached_nghs) # increment counter\n total_reuse_distance+= np.sum(batch_idx - FIF_arrive_time[FIF_cached_nghs])\n\n\n nodes_FIF_to_LRU = np.unique(FIF_cached_nghs) # unique FIF cached neighbors\n n_FIF_to_LRU=len(nodes_FIF_to_LRU)\n\n # FIF uncached neighbors\n index=np.where(FIF_cache_==0)[0] # not unique\n FIF_uncached_nghs=ngh[index] \n \n\n ######### LRU part #########\n LRU_cache_=LRU_cache_flag[FIF_uncached_nghs]\n\n # LRU uncached neighbors => added to FIF\n index=np.where(LRU_cache_==0)[0] # not unique\n LRU_uncached_nghs=FIF_uncached_nghs[index] \n n_recompute+=len(LRU_uncached_nghs) # increment counter\n\n nodes_new_to_FIF=np.unique(LRU_uncached_nghs) # unique new to FIF neighbors\n n_new_to_FIF = len(nodes_new_to_FIF)\n \n\n # LRU cached neighbors => update time flag\n index=np.where(LRU_cache_==1)[0]\n LRU_cached_nghs=FIF_uncached_nghs[index]\n n_reuse+=len(LRU_cached_nghs) # increment counter\n total_reuse_distance+= np.sum(batch_idx - LRU_arrive_time[LRU_cached_nghs])\n\n nodes_LRU_to_LRU=np.unique(LRU_cached_nghs) # unique LRU to LRU neighbors\n n_LRU_to_LRU=len(nodes_LRU_to_LRU)\n\n ########### update FIF ###########\n n_FIF_used = n_FIF_cached-n_FIF_to_LRU\n n_FIF_available = half_budget -n_FIF_used\n\n\n FIF_cache_flag[nodes_FIF_to_LRU]=0\n if n_new_to_FIF<=n_FIF_available: # no need to evict from FIF\n FIF_cache_flag[nodes_new_to_FIF]=1\n FIF_time_flag[nodes_new_to_FIF]=batch_idx\n FIF_arrive_time[nodes_new_to_FIF]=batch_idx\n n_FIF_cached=n_FIF_used+n_new_to_FIF\n\n elif n_new_to_FIF>=half_budget: # evict all and selective cache\n nodes_new_selected_to_FIF=np.random.choice(nodes_new_to_FIF,half_budget,replace=False)\n FIF_cache_flag=np.zeros(num_embeddings)\n FIF_time_flag=np.zeros(num_embeddings)\n FIF_arrive_time=np.zeros(num_embeddings)\n\n FIF_cache_flag[nodes_new_selected_to_FIF]=1\n FIF_time_flag[nodes_new_selected_to_FIF]=batch_idx\n FIF_arrive_time[nodes_new_selected_to_FIF]=batch_idx\n n_FIF_cached=half_budget\n\n else: # selective eviction\n n_FIF_evict = n_new_to_FIF-n_FIF_available\n nodes_FIF_remained=np.where(FIF_cache_flag==1)[0]\n\n # selective evict\n nodes_FIF_evict=np.random.choice(nodes_FIF_remained,n_FIF_evict,replace=False) \n FIF_cache_flag[nodes_FIF_evict]=0\n\n # cache all the new\n FIF_cache_flag[nodes_new_to_FIF]=1\n FIF_time_flag[nodes_new_to_FIF]=batch_idx\n FIF_arrive_time[nodes_new_to_FIF]=batch_idx\n n_FIF_cached=half_budget\n\n\n ########### update LRU ###########\n LRU_time_flag[nodes_LRU_to_LRU]=batch_idx\n n_LRU_available = half_budget - n_LRU_cached\n n_LRU_may_evict = n_LRU_cached - n_LRU_to_LRU\n\n if n_FIF_to_LRU<=n_LRU_available: # no evict\n\n LRU_cache_flag[nodes_FIF_to_LRU]=1\n LRU_time_flag[nodes_FIF_to_LRU]=batch_idx\n LRU_arrive_time[nodes_FIF_to_LRU]=FIF_arrive_time[nodes_FIF_to_LRU]\n n_LRU_cached=n_LRU_cached+n_FIF_to_LRU\n\n elif n_FIF_to_LRU<=(n_LRU_available+n_LRU_may_evict): # selective evict\n n_LRU_evict = n_FIF_to_LRU - n_LRU_available\n\n # selective eviction\n LRU_cached = np.where(LRU_cache_flag==1)[0]\n last_time=LRU_time_flag[LRU_cached]\n evicted_inds=np.argsort(last_time)[:n_LRU_evict]\n evicted_nodes = LRU_cached[evicted_inds]\n LRU_cache_flag[evicted_nodes]=0\n\n # cache all the new\n LRU_cache_flag[nodes_FIF_to_LRU]=1\n LRU_time_flag[nodes_FIF_to_LRU]=batch_idx\n LRU_arrive_time[nodes_FIF_to_LRU]=FIF_arrive_time[nodes_FIF_to_LRU]\n n_LRU_cached=half_budget\n\n else: # evict all and selective push\n \n # evict all\n LRU_cached = np.where(LRU_cache_flag==1)[0]\n last_time=LRU_time_flag[LRU_cached]\n evicted_inds = np.where(last_time=candidate_size else min(candidate_size-available_size,n_cached)\n to_cache_size = candidate_size if (evict_size+available_size)>=candidate_size else budget\n\n\n # evict some items here\n if evict_size!=0:\n last_time=time_flag[cached_nodes]\n sorted_inds=np.argsort(last_time)[:evict_size]\n evicted_nodes = cached_nodes[sorted_inds]\n cache_flag[evicted_nodes]=0\n \n # cache some new items here\n to_cache=np.random.choice(candidates,to_cache_size,replace=False)\n cache_flag[to_cache]=1\n time_flag[to_cache]=batch_idx\n arrive_time[to_cache]=batch_idx\n\n # update the cache_plan_list\n cache_plan_list.append(np.where(cache_flag==1)[0])\n \n average_reuse_distance = total_reuse_distance/n_reuse\n return cache_plan_list, n_reuse, n_recompute, average_reuse_distance\n\n\n\ndef get_cache_plan(args,train_data,neighbor_finder,num_embeddings,strategy):\n \n budget=args.budget\n prepare_start=time.time()\n\n num_batch,target_list,ngh_list,occur_list,total_n_in,total_n_unique_in,total_n_out,total_n_unique_out=read_batches(args,train_data,neighbor_finder,num_embeddings)\n t_prepare=time.time()-prepare_start\n\n start=time.time()\n if strategy=='MRD':\n plan,n_reuse,n_recompute,average_reuse_distance=MRD_numba(num_embeddings,num_batch,budget,target_list,ngh_list,occur_list)\n elif strategy=='LRU':\n plan,n_reuse,n_recompute,average_reuse_distance=LRU_numba(num_embeddings,num_batch,budget,target_list,ngh_list)\n elif strategy=='2Q':\n plan,n_reuse,n_recompute,average_reuse_distance=TwoQ_numba(num_embeddings,num_batch,budget,target_list,ngh_list)\n else:\n print(f'unsupported cache strategy {strategy}')\n sys.exit(1)\n t_cache=time.time()-start\n\n print(f'prepare {t_prepare}, cache {t_cache}, n_reuse {n_reuse}, n_recompute {n_recompute}, average_reuse_distance {average_reuse_distance}')\n return plan\n","repo_name":"LuckyLYM/Orca","sub_path":"utils/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":14111,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"33"} +{"seq_id":"11124603204","text":"from flask import current_app, render_template, request, redirect, url_for, session, g, flash, abort, make_response\n\nfrom ode import config_get, session_box, login_required\nfrom ode.model import User, Group, MailingList, Alias\nfrom . import blueprint, forms, mail, tasks, mailman_integration\n\nfrom flask_babel import _\n\nimport datetime\nfrom birthday_functions import create_ical\n\n@blueprint.app_template_filter()\ndef force_str(s):\n\treturn unicode(s)\n\ndef mail_user_password(user, form):\n\tif form.send_password.data:\n\t\ttry:\n\t\t\tmail.send_user_mail(\"%s <%s>\" % (user.name, user.mail), user=user, form=form)\n\t\t\tflash(_(\"User confirmation mail sent\"))\n\t\texcept Exception:\n\t\t\tcurrent_app.logger.debug(\"Exception while sending mail\", exc_info=True)\n\t\t\tflash(_(\"Couldn't send mail to user\"), category=\"danger\")\n\n\n\n@blueprint.route(\"/\")\n@login_required(False)\ndef root():\n\tif session[\"is_admin\"]:\n\t\treturn redirect(url_for('.users'))\n\telse:\n\t\treturn redirect(url_for('.self'))\n\n@blueprint.route(\"/self\", methods=['GET','POST'])\n@login_required(False)\ndef self():\n\tform = forms.EditSelfForm(obj=g.ldap_user)\n\n\tif request.method == 'POST' and form.validate_on_submit():\n\t\tif form.update.data:\n\t\t\tchanged = save_ldap_attributes(form, g.ldap_user)\n\n\t\t\tif not changed or g.ldap_user.save():\n\t\t\t\tflash(_(\"Successfully saved\"), category=\"success\")\n\t\t\t\tmail_user_password(g.ldap_user, form)\n\n\t\t\t\tif form.password.data:\n\t\t\t\t\t# Need to update the session\n\t\t\t\t\tsession_box.store_boxed(\"password\", form.password.data)\n\t\t\t\t\tsession.modified = True\n\n\t\t\t\treturn redirect(url_for('.self'))\n\t\t\telse:\n\t\t\t\tflash(_(\"Saving was unsuccessful\"), category=\"danger\")\n\n\tform.password.data = '' # Must manually delete this, since the password is not returned\n\treturn render_template(\"amu/self.html\", form=form)\n\n@blueprint.route(\"/user/\")\n@login_required\ndef users():\n\tusers = User.query.all()\n\tgroups = Group.query.all()\n\treturn render_template('amu/users.html', users=users, groups=groups)\n\ndef save_ldap_attributes(form, obj):\n\t\"\"\"Only stores existing LDAP attributes.\n\tDoes not store empty attributes named 'password'.\n\tDoes not change existing attributes named 'userid'.\n\tSets new attributes named 'userid' to a lower-case version.\n\tDoes not change attributes named 'groups'.\n\tDoes not change attributes named 'members'.\n\tFor the following attributes a set_* method is called: aliases, list_members\"\"\"\n\n\tfrom ldap3 import LDAPEntryError\n\n\tchanged = False\n\n\tfor name, field in form._fields.items():\n\t\tif name == \"password\" and not field.data: continue\n\t\tif name == \"userid\" and getattr(obj, \"userid\", None): continue\n\t\tif name == \"groups\": continue\n\t\tif name == \"members\": continue\n\n\t\ttry:\n\t\t\tvalue = field.data\n\t\t\told_value = getattr(getattr(obj, name), 'value', getattr(obj, name))\n\n\t\t\tif name == \"userid\":\n\t\t\t\tvalue = value.lower()\n\n\t\t\tif old_value != value:\n\n\t\t\t\tcurrent_app.logger.debug(\"Setting %s because it was %r and should be %r\", name, \n\t\t\t\t\told_value, value)\n\n\t\t\t\tsetter = None\n\t\t\t\tif name in [\"aliases\", \"list_members\"]:\n\t\t\t\t\tsetter = getattr(obj, \"set_%s\" % name, None)\n\t\t\t\tif setter:\n\t\t\t\t\tsetter(value)\n\t\t\t\telse:\n\t\t\t\t\tsetattr(obj, name, value)\n\t\t\t\tchanged = True\n\n\t\texcept LDAPEntryError as e:\n\t\t\tcontinue\n\n\tcurrent_app.logger.debug(\"Change status is %s\", changed)\n\treturn changed\n\n@blueprint.route(\"/user/\", methods=['GET','POST'])\n@login_required\ndef user(uid):\n\tuser = User.query.filter(\"userid: %s\" % uid).first()\n\tif not user:\n\t\tabort(404)\n\tgroup_list = Group.query.all()\n\tform = forms.get_EditUserForm(group_list)(obj=user)\n\tif request.method == 'POST' and form.validate_on_submit():\n\t\tif form.userid.data != uid:\n\t\t\tabort(400)\n\n\t\tif form.update.data:\n\t\t\tchanged = save_ldap_attributes(form, user)\n\n\t\t\tif not changed or user.save():\n\t\t\t\tflash(_(\"Successfully saved\"), category=\"success\")\n\t\t\t\tif not user.save_groups(form.groups.data, group_list):\n\t\t\t\t\tflash(_(\"Some or all of the group changes were not successful\"), category=\"danger\")\n\n\t\t\t\tmail_user_password(user, form)\n\n\t\t\t\treturn redirect(url_for('.user', uid=user.userid))\n\t\t\telse:\n\t\t\t\tflash(_(\"Saving was unsuccessful\"), category=\"danger\")\n\t\telif form.delete.data:\n\t\t\tif form.delete_confirm.data:\n\t\t\t\t## Warning: flask_ldapconn doesn't give any status, so we implement this from scratch here\n\t\t\t\tif user.connection.connection.delete(user.dn):\n\t\t\t\t\tflash(_(\"User deleted\"), category=\"success\")\n\t\t\t\t\treturn redirect(url_for('.users'))\n\t\t\t\telse:\n\t\t\t\t\tflash(_(\"Deletion was unsuccessful\"), category=\"danger\")\n\t\t\telse:\n\t\t\t\tflash(_(\"Please confirm user deletion\"), category=\"danger\")\n\n\tform.password.data = '' # Must manually delete this, since the password is not returned\n\tform.delete_confirm.data = False # Always reset this\n\treturn render_template('amu/user.html', user=user, form=form)\n\n@blueprint.route(\"/user/_new\", methods=['GET','POST'])\n@login_required\ndef new_user():\n\tgroup_list = Group.query.all()\n\tform = forms.get_NewUserForm(group_list)()\n\tif request.method == 'POST' and form.validate_on_submit():\n\t\tif form.submit.data:\n\t\t\tuser = User()\n\t\t\tsave_ldap_attributes(form, user)\n\n\t\t\tif user.save():\n\t\t\t\tflash(_(\"User created\"), category=\"success\")\n\t\t\t\tif not user.save_groups(form.groups.data, group_list):\n\t\t\t\t\tflash(_(\"Some or all of the groups could not be assigned\"), category=\"danger\")\n\n\t\t\t\tmail_user_password(user, form)\n\n\t\t\t\treturn redirect(url_for('.user', uid=user.userid))\n\t\t\telse:\n\t\t\t\tflash(_(\"Error while creating user\"), category=\"danger\")\n\treturn render_template('amu/new_user.html', form=form)\n\n\n@blueprint.route(\"/group/\")\n@login_required\ndef groups():\n\tusers = User.query.all()\n\tgroups = Group.query.all()\n\treturn render_template('amu/groups.html', users=users, groups=groups)\n\n@blueprint.route(\"/group/\", methods=['GET','POST'])\n@login_required\ndef group(cn):\n\tgroup = Group.query.filter(\"name: %s\" % cn).first()\n\tif not group:\n\t\tabort(404)\n\tuser_list = User.query.all()\n\tform = forms.get_EditGroupForm(user_list)(obj=group)\n\tif request.method == 'POST' and form.validate_on_submit():\n\t\t\n\t\tif form.update.data:\n\t\t\tchanged = save_ldap_attributes(form, group)\n\t\t\tchanged_members = group.set_members(form.members.data)\n\t\t\tif not changed or group.save() or changed_members:\n\t\t\t\tflash(_(\"Successfully saved\"), category=\"success\")\n\t\t\t\treturn redirect(url_for('.group', cn=group.name))\n\t\t\telse:\n\t\t\t\tflash(_(\"Saving was unsuccessful\"), category=\"danger\")\n\n\t\telif form.delete.data:\n\t\t\tif form.delete_confirm.data:\n\t\t\t\t## Warning: flask_ldapconn doesn't give any status, so we implement this from scratch here\n\t\t\t\tif group.connection.connection.delete(group.dn):\n\t\t\t\t\tflash(_(\"Group deleted\"), category=\"success\")\n\t\t\t\t\treturn redirect(url_for('.groups'))\n\t\t\t\telse:\n\t\t\t\t\tflash(_(\"Deletion was unsuccessful\"), category=\"danger\")\n\t\t\telse:\n\t\t\t\tflash(_(\"Please confirm group deletion\"), category=\"danger\")\n\n\tform.delete_confirm.data = False # Always reset this\n\treturn render_template('amu/group.html', group=group, form=form)\n\n@blueprint.route(\"/group/_new\", methods=['GET','POST'])\n@login_required\ndef new_group():\n\tuser_list = User.query.all()\n\tform = forms.get_NewGroupForm(user_list)()\n\tif request.method == 'POST' and form.validate_on_submit():\n\t\tif form.submit.data:\n\t\t\tgroup = Group()\n\t\t\tsave_ldap_attributes(form, group)\n\t\t\tgroup.members = form.members.data\n\n\t\t\tif group.save():\n\t\t\t\tflash(_(\"Group created\"), category=\"success\")\n\t\t\t\treturn redirect(url_for('.group', cn=group.name))\n\t\t\telse:\n\t\t\t\tflash(_(\"Error while creating group\"), category=\"danger\")\n\treturn render_template('amu/new_group.html', form=form)\n\n\n@blueprint.route(\"/mailing_list/\")\n@login_required\ndef mailing_lists():\n\tlists = MailingList.query.all()\n\n\ttry:\n\t\tsync_problems = []\n\t\twith mailman_integration.sync_state() as state:\n\t\t\tfor ln, problems in state[\"sync_problems\"].items():\n\t\t\t\tfor problem in problems:\n\t\t\t\t\tif problem is mailman_integration.SyncMessage.CONFLICT:\n\t\t\t\t\t\tflash( _(\"Conflict while syncing mailing list '%s', please resolve manually\") % ln, category='danger' )\n\t\t\t\t\telif problem is mailman_integration.SyncMessage.ON_LDAP_NOT_ON_MM:\n\t\t\t\t\t\tflash( _(\"Mailing list '%s' exists in LDAP, but not in Mailman. Please create in Mailman.\" % ln), category='warning' )\n\n\t\treturn render_template('amu/mailing_lists.html', lists=lists)\n\n\texcept KeyError as ex:\n\t\tmessage = _(\"Mailing lists are currently not activated.\")\n\t\texception = _(\"Exception: {}.\".format(type(ex).__name__))\n\t\targs = _(\"Arguments: {}.\".format(ex.args))\n\t\treturn render_template('amu/error.html', message=message, exception=exception, args=args)\n\n\n@blueprint.route(\"/mailing_list/\", methods=['GET','POST'])\n@login_required\ndef mailing_list(cn):\n\tmlist = MailingList.query.filter(\"name: %s\" % cn).first()\n\tif not mlist:\n\t\tabort(404)\n\tgroup_list = Group.query.all()\n\tuser_list = User.query.all()\n\tform = forms.get_EditMailingListForm(user_list, group_list)(obj=mlist)\n\n\tif request.method == 'POST' and form.validate_on_submit():\n\t\tif form.update.data:\n\t\t\tmlist.set_list_members(form.list_members.data)\n\t\t\tif form.import_file.data:\n\t\t\t\timport_existing, import_errors = mlist.import_list_members(form.import_file.data.readlines())\n\n\t\t\t\tfor a in import_errors:\n\t\t\t\t\tflash(_(\"Invalid format, did not import: %s\") % a, category=\"danger\")\n\n\t\t\t\tfor a in import_existing:\n\t\t\t\t\tflash(_(\"Already existing, did not import: %s\") % a, category=\"warning\")\n\n\t\t\tif mlist.save():\n\t\t\t\tflash(_(\"Successfully saved\"), category=\"success\")\n\t\t\t\ttasks.sync_mailing_lists.apply_async() # Immediately schedule a mailing list update\n\t\t\t\treturn redirect(url_for('.mailing_list', cn=mlist.name))\n\t\t\telse:\n\t\t\t\tflash(_(\"Saving was unsuccessful\"), category=\"danger\")\n\n\t\telif form.delete.data:\n\t\t\tif form.delete_confirm.data:\n\t\t\t\t## Warning: flask_ldapconn doesn't give any status, so we implement this from scratch here\n\t\t\t\tif mlist.connection.connection.delete(mlist.dn):\n\t\t\t\t\tflash(_(\"Mailing list deleted\"), category=\"success\")\n\t\t\t\t\treturn redirect(url_for('.mailing_lists'))\n\t\t\t\telse:\n\t\t\t\t\tflash(_(\"Deletion was unsuccessful\"), category=\"danger\")\n\t\t\telse:\n\t\t\t\tflash(_(\"Please confirm mailing list deletion\"), category=\"danger\")\n\n\tform.delete_confirm.data = False # Always reset this\n\treturn render_template('amu/mailing_list.html', list=mlist, group_list=group_list, user_list=user_list, form=form)\n\n@blueprint.route(\"/mailing_list/_new\", methods=['GET','POST'])\n@login_required\ndef new_mailing_list():\n\tgroup_list = Group.query.all()\n\tuser_list = User.query.all()\n\tform = forms.get_NewMailingListForm(user_list, group_list)()\n\tif request.method == 'POST' and form.validate_on_submit():\n\t\tif form.submit.data:\n\t\t\tmlist = MailingList()\n\t\t\tsave_ldap_attributes(form, mlist)\n\t\t\tif form.import_file.data:\n\t\t\t\timport_existing, import_errors = mlist.import_list_members(form.import_file.data.readlines())\n\n\t\t\t\tfor a in import_errors:\n\t\t\t\t\tflash(_(\"Invalid format, did not import: %s\") % a, category=\"danger\")\n\n\t\t\t\tfor a in import_existing:\n\t\t\t\t\tflash(_(\"Already existing, did not import: %s\") % a, category=\"warning\")\n\n\t\t\tif mlist.save():\n\t\t\t\tflash(_(\"Mailing list created\"), category=\"success\")\n\t\t\t\treturn redirect(url_for('.mailing_list', cn=mlist.name))\n\t\t\telse:\n\t\t\t\tflash(_(\"Error while creating mailing list\"), category=\"danger\")\n\treturn render_template('amu/new_mailing_list.html', group_list=group_list, user_list=user_list, form=form)\n\n@blueprint.route(\"/alias/\")\n@login_required\ndef aliases():\n\taliases = Alias.query.all()\n\treturn render_template('amu/aliases.html', aliases=aliases)\n\n@blueprint.route(\"/alias/\", methods=['GET','POST'])\n@login_required\ndef alias(cn):\n\talias = Alias.query.filter(\"name: %s\" % cn).first()\n\tif not alias:\n\t\tabort(404)\n\n\tuser_list = User.query.all()\n\tgroup_list = Group.query.all()\n\talias_list = Alias.query.all()\n\tform = forms.get_EditAliasForm(user_list, group_list, alias_list)(obj=alias)\n\n\tif request.method == 'POST' and form.validate_on_submit():\n\t\tif form.update.data:\n\t\t\talias.set_members(form.members.data)\n\n\t\t\tif alias.save():\n\t\t\t\tflash(_(\"Successfully saved\"), category=\"success\")\n\t\t\t\treturn redirect(url_for('.alias', cn=alias.name))\n\t\t\telse:\n\t\t\t\tflash(_(\"Saving was unsuccessful\"), category=\"danger\")\n\n\t\telif form.delete.data:\n\t\t\tif form.delete_confirm.data:\n\t\t\t\t## Warning: flask_ldapconn doesn't give any status, so we implement this from scratch here\n\t\t\t\tif alias.connection.connection.delete(alias.dn):\n\t\t\t\t\tflash(_(\"Alias deleted\"), category=\"success\")\n\t\t\t\t\treturn redirect(url_for('.aliases'))\n\t\t\t\telse:\n\t\t\t\t\tflash(_(\"Deletion was unsuccessful\"), category=\"danger\")\n\t\t\telse:\n\t\t\t\tflash(_(\"Please confirm alias deletion\"), category=\"danger\")\n\n\tform.delete_confirm.data = False # Always reset this\n\treturn render_template('amu/alias.html', alias=alias, group_list=group_list, user_list=user_list, alias_list=alias_list, form=form)\n\n@blueprint.route(\"/alias/_new\", methods=['GET','POST'])\n@login_required\ndef new_alias():\n\tuser_list = User.query.all()\n\tgroup_list = Group.query.all()\n\talias_list = Alias.query.all()\n\tform = forms.get_NewAliasForm(user_list, group_list, alias_list)()\n\n\tif request.method == 'POST' and form.validate_on_submit():\n\t\tif form.submit.data:\n\t\t\talias = Alias()\n\t\t\talias.name = form.name.data\n\t\t\talias.members = form.members.data\n\n\t\t\tif alias.save():\n\t\t\t\tflash(_(\"Alias created\"), category=\"success\")\n\t\t\t\treturn redirect(url_for('.alias', cn=alias.name))\n\t\t\telse:\n\t\t\t\tflash(_(\"Error while creating Alias\"), category=\"danger\")\n\treturn render_template('amu/new_alias.html', group_list=group_list, user_list=user_list, alias_list=alias_list, form=form)\n\n@blueprint.route(\"/birthdays/\")\n@login_required\ndef birthdays():\n\tuser_list = User.query.all()\n\n\tuser_dict = {}\n\tfor user in user_list:\n\t\tubd = user.birthdate\n\t\tuser_dict.update( {user : ubd.strftime(\"%m\")} )\n\n\tuser_list = sorted(user_dict, key=user_dict.get)\n\n\ttoday = datetime.datetime.today().strftime('%Y-%m-%d')\n\n\tgname = request.args.get('gname')\n\tgroup_list = Group.query.all()\n\n\ts_group = None\n\tif gname:\n\t\ts_group = Group.query.filter(\"name: %s\" % gname).first()\n\t\n\treturn render_template('amu/birthdays.html', user_list=user_list, group_list=group_list, s_group=s_group, today=today)\n\n@blueprint.route(\"/birthdays.ics/\")\n@login_required\ndef birthdays_file():\n\tuser_list = User.query.all()\n\tgroup_list = Group.query.all()\n\tical_str = create_ical(user_list, group_list)\n\n\tresponse = make_response(ical_str, 200)\n\tresponse.headers['Content-type'] = 'text/calender'\n\tresponse.headers['Content-Disposition'] = 'attachment; filename=ode_birthdays.ics'\n\n\treturn response\n\t","repo_name":"henryk/ode","sub_path":"ode/blueprints/amu/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14428,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"18203639483","text":"\"\"\"\nhttps://leetcode.com/explore/featured/card/april-leetcoding-challenge-2021/593/week-1-april-1st-april-7th/3697/\nhttps://leetcode.com/problems/global-and-local-inversions/\n\nWe have some permutation A of [0, 1, ..., N - 1], where N is the length of A.\n\nThe number of (global) inversions is the number of i < j with 0 <= i < j < N and A[i] > A[j].\n\nThe number of local inversions is the number of i with 0 <= i < N and A[i] > A[i+1].\n\nReturn true if and only if the number of global inversions is equal to the number of local inversions.\n\nExample 1:\n\nInput: A = [1,0,2]\nOutput: true\nExplanation: There is 1 global inversion, and 1 local inversion.\nExample 2:\n\nInput: A = [1,2,0]\nOutput: false\nExplanation: There are 2 global inversions, and 1 local inversion.\nNote:\n\nA will be a permutation of [0, 1, ..., A.length - 1].\nA will have length in range [1, 5000].\nThe time limit for this problem has been reduced.\n\"\"\"\nfrom typing import List\n\nfrom Common.ObjectTestingUtils import run_functional_tests\n\n\n# Runtime: 328 ms, faster than 78.93% of Python3 online submissions for Global and Local Inversions.\n# Memory Usage: 15.1 MB, less than 44.06% of Python3 online submissions for Global and Local Inversions.\nclass Solution:\n def isIdealPermutation(self, A: List[int]) -> bool:\n for i, a in enumerate(A):\n if abs(a - i) > 1:\n return False\n return True\n\n\ntests = [\n ([1,0,2], True),\n ([1,2,0], False)\n]\n\nrun_functional_tests(Solution().isIdealPermutation, tests)","repo_name":"wtain/LeetCodePython","sub_path":"DataStructures/Basic/Arrays/Algorithms/Sort/GlobalAndLocalInversions.py","file_name":"GlobalAndLocalInversions.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"33"} +{"seq_id":"15901943771","text":"from collections import defaultdict\nimport hashlib\nimport re\nfrom lxml import etree\nfrom corehq.apps.domain.models import Domain\nfrom corehq.apps.users.models import CouchUser\nfrom corehq.util.quickcache import quickcache\nfrom custom.openclinica.const import (\n AUDIT_LOGS,\n CC_DOB,\n CC_ENROLLMENT_DATE,\n CC_SEX,\n CC_STUDY_SUBJECT_ID,\n CC_SUBJECT_KEY,\n)\nfrom custom.openclinica.utils import (\n OpenClinicaIntegrationError,\n get_item_measurement_unit,\n get_question_item,\n get_oc_user,\n get_study_event_name,\n is_study_event_repeating,\n oc_format_date,\n oc_format_time,\n originals_first,\n)\nfrom dimagi.ext.couchdbkit import (\n Document,\n DocumentSchema,\n StringProperty,\n SchemaProperty,\n BooleanProperty,\n)\nfrom dimagi.utils.couch.cache import cache_core\nfrom suds.client import Client\nfrom suds.plugin import MessagePlugin\nfrom suds.wsse import Security, UsernameToken\n\n\n_reserved_keys = ('@uiVersion', '@xmlns', '@name', '#type', 'case', 'meta', '@version')\n\n\nclass OpenClinicaAPI(object):\n \"\"\"\n We use OpenClinica's SOAP API. because their REST API is limited.\n\n CommCare subject cases are iterated, and data built up from form\n submissions. Subjects and their data are then compared with OpenClinica.\n Missing subjects are created using `StudySubject.create` and missing\n events are scheduled with `Event.schedule`. Data is then ready to import\n using `Data.import`.\n\n This automates a process that would otherwise need to be done manually.\n\n One manual aspect still remains. The OpenClinica administrator still needs\n to create users on OpenClinica for all CommCare mobile workers for the\n study, in order for AuditLog data exported from CommCare to match\n OpenClinica users.\n\n +============+==============================+====================+==========================================+\n | Web | Method | Description | WSDL Location (Input Value) |\n | Service | | | |\n +============+==============================+====================+==========================================+\n | Create | StudySubject.create | Creates a new | http://${your instance}/OpenClinica-ws/ |\n | Study | | Study Subject | ws/studySubject/v1/studySubjectWsdl.wsdl |\n | Subject | | | |\n +------------+------------------------------+--------------------+------------------------------------------+\n | List all | StudySubject | Lists the Subjects | http://${your instance}/OpenClinica-ws/ |\n | Study | .listAllByStudy | in a study | ws/studySubject/v1/studySubjectWsdl.wsdl |\n | Subjects | | | |\n +------------+------------------------------+--------------------+------------------------------------------+\n | Find if | StudySubject.isStudySubject | Find if Study | http://${your instance}/OpenClinica-ws/ |\n | Study | | Subject exists | ws/studySubject/v1/studySubjectWsdl.wsdl |\n | Subject | | | |\n | exists | | | |\n +------------+------------------------------+--------------------+------------------------------------------+\n | Schedule | Event.schedule | Schedules an | http://${your instance}/OpenClinica-ws/ |\n | Event | | Event for an | ws/event/v1/eventWsdl.wsdl |\n | | | enrolled Study | |\n | | | Subject | |\n +------------+------------------------------+--------------------+------------------------------------------+\n | Import | Data.import | Imports Data onto | http://${your instance}/OpenClinica-ws/ |\n | Data | | an OpenClincia | ws/data/v1/dataWsdl.wsdl |\n | | | CRF for an already | |\n | | | scheduled study | |\n | | | event | |\n +------------+------------------------------+--------------------+------------------------------------------+\n | Get Study | Study.getMetadata | Returns study | http://${your instance}/OpenClinica-ws/ |\n | Metadata | | definition | ws/study/v1/studyWsdl.wsdl |\n | | | metadata in | |\n | | | CDISC ODM XML | |\n | | | format (with | |\n | | | OpenClinica | |\n | | | extensions) | |\n +------------+------------------------------+--------------------+------------------------------------------+\n | List Study | Study.listAll | Returns a lists of | http://${your instance}/OpenClinica-ws/ |\n | | | studies and sites | ws/study/v1/studyWsdl.wsdl |\n +------------+------------------------------+--------------------+------------------------------------------+\n | Study | StudyEventDefinition.listAll | Lists study event | http://${your instance}/OpenClinica-ws/ |\n | Event | | definitions in | ws/studyEventDefinition/v1/ |\n | Definition | | study | studyEventDefinitionWsdl.wsdl |\n +------------+------------------------------+--------------------+------------------------------------------+\n\n \"\"\"\n\n def __init__(self, base_url, username, password, study_id, prefetch=False):\n \"\"\"\n Initialise OpenClinicaAPI\n\n :param base_url: Protocol, address (and port) of the server, e.g. \"https://openclinica.example.com:8080/\"\n :param username: Username enabled for API authentication\n :param password: Password\n :param study_id: Study identifier\n :param prefetch: Fetch WSDLs on init?\n \"\"\"\n self._base_url = base_url if base_url[-1] == '/' else base_url + '/'\n self._username = username\n self._password = password\n self._study_id = study_id\n self._clients = {\n 'data': None,\n 'event': None,\n 'study': None,\n 'studyEventDefinition': None,\n 'studySubject': None\n }\n if prefetch:\n for endpoint in self._clients:\n self.get_client(endpoint)\n\n def get_client(self, endpoint):\n\n class FixMimeMultipart(MessagePlugin):\n \"\"\"\n StudySubject.listAllByStudy replies with what looks like part of a multipart MIME message(!?) Fix this.\n \"\"\"\n def received(self, context):\n reply = context.reply\n if reply.startswith('------='):\n matches = re.search(r'()', reply)\n context.reply = matches.group(1)\n\n if endpoint not in self._clients:\n raise ValueError('Unknown OpenClinica API endpoint')\n if self._clients[endpoint] is None:\n client = Client(\n '{url}OpenClinica-ws/ws/{endpoint}/v1/{endpoint}Wsdl.wsdl'.format(\n url=self._base_url,\n endpoint=endpoint\n ),\n plugins=[FixMimeMultipart()]\n )\n security = Security()\n password = hashlib.sha1(self._password).hexdigest() # SHA1, not AES as documentation says\n token = UsernameToken(self._username, password)\n security.tokens.append(token)\n client.set_options(wsse=security)\n self._clients[endpoint] = client\n return self._clients[endpoint]\n\n def get_study_metadata_string(self):\n \"\"\"\n Returns study metadata as an XML string\n \"\"\"\n study_client = self.get_client('study')\n study_client.set_options(retxml=True) # Don't parse the study metadata; just give us the raw XML\n resp = study_client.service.getMetadata({'identifier': self._study_id})\n soap_env = etree.fromstring(resp)\n nsmap = {\n 'SOAP-ENV': \"http://schemas.xmlsoap.org/soap/envelope/\",\n 'OC': \"http://openclinica.org/ws/study/v1\"\n }\n odm = soap_env.xpath('./SOAP-ENV:Body/OC:createResponse/OC:odm', namespaces=nsmap)[0]\n return odm.text\n\n def get_subject_keys(self):\n subject_client = self.get_client('studySubject')\n resp = subject_client.service.listAllByStudy({'identifier': self._study_id})\n return [s.subject.uniqueIdentifier for s in resp.studySubjects.studySubject] if resp.studySubjects else []\n\n def create_subject(self, subject):\n subject_client = self.get_client('studySubject')\n subject_data = {\n 'label': subject['study_subject_id'],\n 'enrollmentDate': str(subject['enrollment_date']),\n 'subject': {\n 'uniqueIdentifier': subject['subject_key'][3:], # Drop the initial 'SS_'\n 'gender': {'1': 'm', '2': 'f'}[subject['sex']],\n 'dateOfBirth': str(subject['dob']),\n },\n 'studyRef': {\n 'identifier': self._study_id,\n },\n }\n resp = subject_client.service.create(subject_data)\n if resp.result != 'Success':\n raise OpenClinicaIntegrationError(\n 'Unable to register subject \"{}\" via OpenClinica webservice'.format(subject['subject_key'])\n )\n\n def schedule_event(self, subject, event):\n event_client = self.get_client('event')\n event_data = {\n 'studySubjectRef': {\n 'label': subject['study_subject_id'],\n },\n 'studyRef': {\n 'identifier': self._study_id,\n },\n 'eventDefinitionOID': event['study_event_oid'],\n 'startDate': event['start_long'].split()[0], # e.g. 1999-12-31\n 'startTime': event['start_short'].split()[1], # e.g. 23:59\n 'endDate': event['end_long'].split()[0],\n 'endTime': event['end_short'].split()[1],\n }\n resp = event_client.service.schedule(event_data)\n if resp.result != 'Success':\n raise OpenClinicaIntegrationError(\n 'Unable to schedule event \"{}\" via OpenClinica webservice'.format(event['study_event_oid'])\n )\n\n\nclass StudySettings(DocumentSchema):\n is_ws_enabled = BooleanProperty()\n url = StringProperty()\n username = StringProperty()\n password = StringProperty()\n protocol_id = StringProperty()\n metadata = StringProperty() # Required when web service is not enabled\n\n\nclass OpenClinicaSettings(Document):\n domain = StringProperty()\n study = SchemaProperty(StudySettings) # One study per domain prevents cases from getting mixed up\n\n @classmethod\n def for_domain(cls, domain):\n res = cache_core.cached_view(\n cls.get_db(),\n \"by_domain_doc_type_date/view\",\n key=[domain, 'OpenClinicaSettings', None],\n reduce=False,\n include_docs=True,\n wrapper=cls.wrap)\n return res[0] if len(res) > 0 else None\n\n\nclass ItemGroup(object):\n \"\"\"\n Corresponds to a question group in CommCare.\n\n ItemGroups can repeat. To reproduce this behaviour in CommCare we use\n repeat groups.\n \"\"\"\n\n def __init__(self, domain, oid):\n self.oid = oid\n self.completed_cc_forms = set([])\n self.items = defaultdict(dict)\n\n\nclass StudyEvent(object):\n \"\"\"\n Like item groups, study events can also be repeating.\n \"\"\"\n def __init__(self, domain, oid, case_id):\n self.oid = oid\n self.case_id = case_id\n self.is_repeating = is_study_event_repeating(domain, oid)\n self.forms = defaultdict(lambda: defaultdict(list)) # a dict of forms containing a dict of item groups\n self.name = get_study_event_name(domain, oid)\n self.start_datetime = None\n self.end_datetime = None\n\n @property\n def start_short(self):\n \"\"\"\n Format the start date and time for the UI.\n\n Format the date and time so that the user to copy and paste into OpenClinica\n \"\"\"\n return self.start_datetime.strftime('%d-%b-%Y %H:%M') # e.g. 01-Jan-1970 00:00\n\n @property\n def end_short(self):\n return self.end_datetime.strftime('%d-%b-%Y %H:%M')\n\n @property\n def start_long(self):\n \"\"\"\n Format the start date and time for the ODM export.\n\n OpenClinica UI doesn't allow the user to set seconds, so theirs is always \"%H:%M:00.0\". Make ours match:\n \"\"\"\n return self.start_datetime.strftime('%Y-%m-%d %H:%M:00.0')\n\n @property\n def end_long(self):\n return self.end_datetime.strftime('%Y-%m-%d %H:%M:00.0')\n\n\nclass Subject(object):\n \"\"\"\n Manages data for a subject case\n \"\"\"\n\n def __init__(self, subject_key, study_subject_id, domain):\n self.subject_key = subject_key\n self.study_subject_id = study_subject_id\n self.enrollment_date = None\n self.sex = None\n self.dob = None\n\n # We need the domain to get study metadata for study events and item groups\n self._domain = Domain.get_by_name(domain)\n self._domain_name = domain\n\n # This subject's data. Stored as subject[study_event_oid][i][form_oid][item_group_oid][j][item_oid]\n # (Study events and item groups are lists because they can repeat.)\n self.data = defaultdict(list)\n\n # Tracks items in self.data by reference using form ID and question. We need this so that we can\n # update an item if its form has been edited on HQ, by looking it up with new_form.orig_id.\n self.question_items = defaultdict(dict)\n\n # The mobile workers who entered this subject's data. Used for audit logs. The number of mobile workers\n # entering data for any single subject should be small, even in large studies with thousands of users.\n # Because we are fetching the user for every question, use a dictionary for speed.\n self.mobile_workers = {}\n\n def get_study_event(self, item, form, case_id):\n \"\"\"\n Return the current study event. Opens a new study event if necessary.\n \"\"\"\n if len(self.data[item.study_event_oid]):\n study_event = self.data[item.study_event_oid][-1]\n if study_event.is_repeating and study_event.case_id != case_id:\n study_event = StudyEvent(self._domain_name, item.study_event_oid, case_id)\n self.data[item.study_event_oid].append(study_event)\n else:\n study_event = StudyEvent(self._domain_name, item.study_event_oid, case_id)\n self.data[item.study_event_oid].append(study_event)\n return study_event\n\n def get_item_group(self, item, form, case_id):\n \"\"\"\n Return the current item group and study event. Opens a new item group if necessary.\n\n Item groups are analogous to CommCare question groups. Like question groups, they can repeat.\n \"\"\"\n study_event = self.get_study_event(item, form, case_id)\n oc_form = study_event.forms[item.form_oid]\n if not oc_form[item.item_group_oid]:\n oc_form[item.item_group_oid].append(ItemGroup(self._domain_name, item.item_group_oid))\n item_group = oc_form[item.item_group_oid][-1]\n return item_group, study_event\n\n def get_item_dict(self, item, form, case_id, question):\n \"\"\"\n Return a dict for storing item data, and current study event.\n\n Return both because both the item dict and study event may be updated by a form or question.\n \"\"\"\n item_group, study_event = self.get_item_group(item, form, case_id)\n item_dict = item_group.items[item.item_oid]\n self.question_items[form.get_id][question] = (item_dict, study_event)\n return item_dict, study_event\n\n @staticmethod\n def edit_item(item_dict, form, question, answer, audit_log_id_ref, oc_user):\n if AUDIT_LOGS:\n audit_log_id_ref['id'] += 1\n item_dict['audit_logs'].append({\n 'id': 'AL_{}'.format(audit_log_id_ref['id']),\n 'user_id': oc_user.user_id,\n 'username': oc_user.username,\n 'full_name': oc_user.full_name,\n 'timestamp': form.received_on,\n 'audit_type': 'Item data value updated',\n 'old_value': item_dict['value'],\n 'new_value': answer,\n 'value_type': question,\n })\n item_dict['value'] = answer\n\n @staticmethod\n @quickcache(['domain', 'user_id'])\n def _get_cc_user(domain, user_id):\n return CouchUser.get_by_user_id(user_id, domain)\n\n def _get_oc_user(self, user_id):\n if user_id not in self.mobile_workers:\n cc_user = self._get_cc_user(self._domain_name, user_id)\n oc_user = get_oc_user(self._domain_name, cc_user)\n if oc_user is None:\n raise OpenClinicaIntegrationError(\n 'OpenClinica user not found for CommCare user \"{}\"'.format(cc_user.username))\n self.mobile_workers[user_id] = oc_user\n return self.mobile_workers[user_id]\n\n def add_item(self, item, form, case_id, question, answer, audit_log_id_ref):\n answer = oc_format_date(answer)\n answer = oc_format_time(answer, self._domain.get_default_timezone())\n oc_user = self._get_oc_user(form.auth_context['user_id'])\n if getattr(form, 'deprecated_form_id', None) and question in self.question_items[form.deprecated_form_id]:\n # This form has been edited on HQ. Fetch original item\n item_dict, study_event = self.question_items[form.deprecated_form_id][question]\n if item_dict['value'] != answer:\n self.edit_item(item_dict, form, question, answer, audit_log_id_ref, oc_user)\n else:\n item_dict, study_event = self.get_item_dict(item, form, case_id, question)\n if item_dict and item_dict['value'] != answer:\n # This form has been submitted more than once for a non-repeating item group. This is an edit.\n self.edit_item(item_dict, form, question, answer, audit_log_id_ref, oc_user)\n else:\n item_dict['value'] = answer\n if AUDIT_LOGS:\n audit_log_id_ref['id'] += 1\n item_dict['audit_logs'] = [{\n 'id': 'AL_{}'.format(audit_log_id_ref['id']),\n 'user_id': oc_user.user_id,\n 'username': oc_user.username,\n 'full_name': oc_user.full_name,\n 'timestamp': form.received_on,\n 'audit_type': 'Item data value updated',\n 'reason': 'initial value',\n 'new_value': answer,\n 'value_type': question,\n }]\n mu_oid = get_item_measurement_unit(self._domain_name, item)\n if mu_oid:\n item_dict['measurement_unit_oid'] = mu_oid\n\n if study_event.start_datetime is None or form.form['meta']['timeStart'] < study_event.start_datetime:\n study_event.start_datetime = form.form['meta']['timeStart']\n if study_event.end_datetime is None or form.form['meta']['timeEnd'] > study_event.end_datetime:\n study_event.end_datetime = form.form['meta']['timeEnd']\n\n def add_item_group(self, item, form):\n study_event = self.get_study_event(item, form)\n oc_form = study_event.forms[item.form_oid]\n item_group = ItemGroup(self._domain_name, item.item_group_oid)\n oc_form[item.item_group_oid].append(item_group)\n\n def add_data(self, data, form, event_case, audit_log_id_ref):\n def get_next_item(event_id, question_list):\n for question_ in question_list:\n item_ = get_question_item(self._domain_name, event_id, question_)\n if item_:\n return item_\n return None\n\n event_id = getattr(event_case, 'event_type')\n # If a CommCare form is an OpenClinica repeating item group, then we would need to add a new item\n # group.\n for key, value in data.iteritems():\n if key in _reserved_keys:\n continue\n if isinstance(value, list):\n # Repeat group\n # NOTE: We need to assume that repeat groups can't be edited in later form submissions\n item = get_next_item(event_id, value)\n if item is None:\n # None of the questions in this group are OpenClinica items\n continue\n self.add_item_group(item, form)\n for v in value:\n if not isinstance(v, dict):\n raise OpenClinicaIntegrationError(\n 'CommCare question value is an unexpected data type. Form XMLNS: \"{}\"'.format(\n form.xmlns))\n self.add_data(v, form, event_case, audit_log_id_ref)\n elif isinstance(value, dict):\n # Group\n self.add_data(value, form, event_case, audit_log_id_ref)\n else:\n # key is a question and value is its answer\n item = get_question_item(self._domain_name, event_id, key)\n if item is None:\n # This is a CommCare-only question or form\n continue\n case_id = event_case.get_id\n self.add_item(item, form, case_id, key, value, audit_log_id_ref)\n\n def get_report_events(self):\n \"\"\"\n The events as they appear in the report.\n\n These are useful for scheduling events in OpenClinica, which cannot be imported from ODM until they have\n been scheduled.\n \"\"\"\n events = []\n for study_events in self.data.itervalues():\n for study_event in study_events:\n events.append(\n '\"{name}\" ({start} - {end})'.format(\n name=study_event.name,\n start=study_event.start_short,\n end=study_event.end_short))\n return ', '.join(events)\n\n def get_export_data(self):\n \"\"\"\n Transform Subject.data into the structure that CdiscOdmExportWriter expects\n \"\"\"\n mkitemlist = lambda d: [dict(v, item_oid=k) for k, v in d.iteritems()] # `dict()` updates v with item_oid\n\n def mkitemgrouplist(itemgroupdict):\n itemgrouplist = []\n for oid, item_groups in itemgroupdict.iteritems():\n for i, item_group in enumerate(item_groups):\n itemgrouplist.append({\n 'item_group_oid': oid,\n 'repeat_key': i + 1,\n 'items': mkitemlist(item_group.items)\n })\n return itemgrouplist\n\n mkformslist = lambda d: [{'form_oid': k, 'item_groups': mkitemgrouplist(v)} for k, v in d.iteritems()]\n\n def mkeventslist(eventsdict):\n eventslist = []\n for oid, study_events in eventsdict.iteritems():\n for i, study_event in enumerate(study_events):\n eventslist.append({\n 'study_event_oid': oid,\n 'repeat_key': i + 1,\n 'start_short': study_event.start_short,\n 'start_long': study_event.start_long,\n 'end_short': study_event.end_short,\n 'end_long': study_event.end_long,\n 'forms': mkformslist(study_event.forms)\n })\n return eventslist\n\n return mkeventslist(self.data)\n\n @classmethod\n def wrap(cls, case, audit_log_id_ref):\n subject = cls(getattr(case, CC_SUBJECT_KEY), getattr(case, CC_STUDY_SUBJECT_ID), case.domain)\n subject.enrollment_date = getattr(case, CC_ENROLLMENT_DATE, None)\n subject.sex = getattr(case, CC_SEX, None)\n subject.dob = getattr(case, CC_DOB, None)\n for event in case.get_subcases():\n for form in originals_first(event.get_forms()):\n # Pass audit log ID by reference to increment it for each audit log\n subject.add_data(form.form, form, event, audit_log_id_ref)\n return subject\n","repo_name":"WDDCP/commcare-wddcp","sub_path":"custom/openclinica/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":25765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"5258813595","text":"import os\nimport sys\nimport re\nimport time\nimport argparse\nimport pdb\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-c', '--case', default='')\nparser.add_argument('-l', '--log', default='TS_focus.log1')\nparser.add_argument('-H', '--html', action=\"store_true\", default=False)\nparser.add_argument('-f', '--filter', action=\"store_true\", default=False)\nargs = parser.parse_args()\n\n\n\ndef case_matched(case):\n if args.case=='':\n return True\n else:\n return re.search(args.case, case)\n\n\n\nos.chdir('.')\nif not os.path.exists('TS_focus_parsed'):\n os.mkdir('TS_focus_parsed')\n\nos.chdir('TS_focus_parsed')\nlogfile = open('../%s' % args.log, 'r')\n\nsublogname = 'testsuite.log'\ncase_num = 0\nsublogfile = open(sublogname, 'w')\nsublogfile.close()\n\nwhile(1):\n #pdb.set_trace()\n line = logfile.readline()\n \n if line=='':\n print('===> parse finish.')\n break\n\n #ret = re.findall(': [0-9]* (.*)', line)\n #if ret:\n # line = ret[0]+'\\n'\n\n #if len(line.split(' ')) > 2 and len(line.split(' ')[0])<13:\n # len_tag = len(line.split(' ')[0])\n # line = ' '*(13-len_tag) + line\n\n if 'proc TP_IsamTopLevelTest medium' in line:\n #pdb.set_trace()\n ret = re.findall('-test .*/(.*?).ars', line)\n case_name = ret[0]\n\n if case_matched(case_name):\n print('===> case %d: %s' % (case_num, case_name))\n case_num = case_num + 1\n if not sublogfile.closed:\n print('close log file')\n sublogfile.close()\n\n if case_matched(case_name):\n sublogfile = open('case%d_%s.log' % (case_num, case_name), 'w')\n print('start write sub log file')\n\n if not sublogfile.closed:\n if 'Step #' in line:\n line = line + '\\n\\n'\n sublogfile.write(line)\n\nos.chdir('..')\nif args.html:\n print('===> start parse case log to html:')\n for caselog in os.listdir('TS_focus_parsed'):\n if args.case in caselog and caselog.endswith('.log'):\n parse_html_cmd = 'tclsh /home/songsonl/myscripts/apme_tools/parseFocusLog_all.tcl -log TS_focus_parsed/%s' % caselog\n os.system(parse_html_cmd)\n\n\n\nos.chdir('TS_focus_parsed')\nif args.filter:\n print('===> start filter case log via ZY script:')\n for caselog in os.listdir('.'):\n if args.case in caselog and caselog.endswith('.log'):\n filter_cmd = 'tclsh /home/songsonl/myscripts/apme_tools/COMMAND_PARSE_ZhouYun_V4.1.tcl -LogPath %s -StcLog yes -PctaLog yes -Alarms yes' % caselog\n os.system(filter_cmd)\n","repo_name":"ss0357/myscripts","sub_path":"TItools/parse_TI_log.py","file_name":"parse_TI_log.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"39553620724","text":"# -*- coding: utf-8 -*-\n\n__all__ = [\"tabulate_prime\"]\n\n\n\"\"\"\nExtend `tabulate` module with prime print format.\n\"\"\"\n\nimport tabulate as tabulate_module\nfrom tabulate import DataRow, Line, TableFormat\n\nprime_format = TableFormat(\n lineabove=None,\n linebelowheader=Line(\"\", \"-\", \"-\", \"\"),\n linebetweenrows=None,\n linebelow=None,\n headerrow=DataRow(\"\", \" \", \"\"),\n datarow=DataRow(\"\", \" \", \"\"),\n padding=0, with_header_hide=None\n)\n\ntabulate_module._table_formats[\"prime\"] = prime_format\norig_tabulate = tabulate_module.tabulate\n\n\ndef tabulate_prime(tabular_data):\n \"\"\"\n This `tabulate_prime` function only support prime table requirement,\n just as ETL stuffs.\n \"\"\"\n # treat the second column as normal values.\n tabular_data = [([row[0]] + [\"|\"] + row[1:]) for row in tabular_data]\n\n # print table as customized format.\n output = orig_tabulate(tabular_data, headers=\"firstrow\",\n tablefmt=\"prime\", stralign=\"right\",)\n lines = output.split(\"\\n\")\n\n # add \"+\" sign to horizontal line row.\n first_line = lines[0]\n second_line = lines[1]\n sign_idx = first_line.index(\"|\")\n chars_in_line_2 = list(second_line)\n chars_in_line_2[sign_idx] = \"+\"\n lines[1] = \"\".join(chars_in_line_2)\n\n # align the second horizontal line row.\n last_line = lines[-1]\n max_width = len(last_line)\n lines[1] = lines[1][0:max_width]\n\n # remote the column after \"+\" sign\n lines = [line[0:sign_idx - 2] + line[sign_idx] + line[sign_idx + 2:]\n for line in lines]\n\n output = \"\\n\".join(lines)\n return output\n","repo_name":"dchentech/prints_a_multiplication_table_of_primes_numbers","sub_path":"prints_a_multiplication_table_of_primes_numbers/tabulate_ext.py","file_name":"tabulate_ext.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"19747721006","text":"import re\n\n# Part 1\n# def is_nice(s):\n# \tvowel_count = len([c for c in s if c in 'aeiou'])\n# \tdouble_letter_count = len(re.findall(r'(.)\\1', s))\n# \tbad_count = len(re.findall(r'ab|cd|pq|xy', s))\n\n# \treturn vowel_count >= 3 and double_letter_count >= 1 and bad_count == 0\n\n# Part 2\n# def is_nice(s):\n# \trepeated_pair_count = len(re.findall(r'(..).*\\1', s))\n# \tletter_repeat_count = len(re.findall(r'(.).\\1', s))\n\n# \treturn repeated_pair_count >= 1 and letter_repeat_count >= 1\n\ndef main():\n\tfile_data = ''\n\twith open('input.txt', 'r') as f:\n\t\tfile_data = f.read()\n\n\tstrings = [s.strip() for s in file_data.split('\\n') if s]\n\tnice_strings = [s for s in strings if is_nice(s)]\n\tprint(len(nice_strings))\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"the6p4c/adventofcode","sub_path":"2015/day5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"4058317619","text":"import requests\nimport re\nimport json\nimport progressbar\nfrom urllib.parse import urlparse\nfrom urllib.request import urlretrieve\n\n\npbar = None\n\n\ndef extract_steamid(url):\n return int(url.split(\"/\")[-1])\n\n\ndef verify_url(url, mode):\n url_dict = urlparse(url)\n if mode == 0:\n netloc = \"logs.tf\"\n pattern = \"/profile/7656[0-9]{13}\\/?$\"\n elif mode == 1:\n netloc = \"demos.tf\"\n pattern = \"/profiles/7656[0-9]{13}\\/?$\"\n if url_dict.netloc != netloc: return False\n if not re.match(pattern, url_dict.path): return False\n return True\n\n\ndef verify_search(string, limit):\n # Format: 1 2 3 \n # No repeating\n lst = string.split(\" \")\n if len(set(lst)) != len(lst): return False # Repeating\n if [s for s in lst if s.isdigit() and int(s) <= limit and int(s) > 0] != lst: return False\n return True\n\n\ndef show_progress(block_num, block_size, total_size):\n global pbar\n if pbar is None:\n pbar = progressbar.ProgressBar(maxval=total_size)\n pbar.start()\n\n downloaded = block_num * block_size\n if downloaded < total_size:\n pbar.update(downloaded)\n else:\n pbar.finish()\n pbar = None\n\n\ndef main():\n limit = 10\n\n logs_tf_url = input(\"Enter your Logs.tf profile: \")\n while not verify_url(logs_tf_url, 0):\n logs_tf_url = input(\"Enter your Logs.tf profile: \")\n\n steamid64 = extract_steamid(logs_tf_url)\n logs_api = rf\"https://logs.tf/api/v1/log?player={steamid64}&limit={limit}\"\n\n logs_response = requests.get(logs_api)\n logs = logs_response.json()\n\n file = open(\"search.json\", \"w\")\n json.dump(logs, file)\n\n print(f\"Last {limit} logs for {steamid64}:\")\n for i in range(limit):\n item = logs['logs'][i]\n print(rf\"{i+1}: logs.tf/{item['id']}, {item['title']}, {item['map']}\")\n\n search = input(\"Select logs to search for demos, separated by spaces: \")\n while not verify_search(search, limit):\n search = input(\"Select logs to search for demos, separated by spaces: \")\n \n selected_logs = [logs['logs'][int(j)-1] for j in search.split(\" \")]\n demos = []\n for log in selected_logs:\n demos_api = rf\"https://api.demos.tf/profiles/{steamid64}?after={log['date']-10000}&before={log['date']+10000}&map={log['map']}\"\n demos_response = requests.get(demos_api)\n demos += demos_response.json()\n \n if not demos:\n print(\"There is no demos.tf record for these logs.\")\n else:\n download_demos = []\n for i in demos:\n demo_url = i['url']\n filename = demo_url.split(\"/\")[-1]\n print(f\"URL: {demo_url}\")\n download_demos += [[demo_url, filename]]\n\n answer = input(\"Download these demos? (Y/N) : \")\n while answer.lower() not in (\"y\", \"n\"):\n answer = input(\"Download these demos? (Y/N) : \")\n if answer.lower() != \"y\":\n print(\"Exiting...\")\n return 0\n for i in download_demos:\n print(f\"Downloading {i[1]}...\")\n urlretrieve(i[0], i[1], show_progress)\n return 1\n \n \n \nif __name__ == \"__main__\":\n main()","repo_name":"n4ver/demofinder","sub_path":"demofinder/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"39274379899","text":"from inference import *\nfrom header import *\nfrom .utils import *\n\n\ndef gray_simcse_strategy(args):\n # read the embeddings\n embds, texts, indexes = [], [], []\n for idx in range(100):\n try:\n embd, text, index = torch.load(\n f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/inference_simcse_ctx_{args[\"model\"]}_{args[\"local_rank\"]}_{idx}.pt'\n )\n print(f'[!] load {args[\"root_dir\"]}/data/{args[\"dataset\"]}/inference_simcse_ctx_{args[\"model\"]}_{args[\"local_rank\"]}_{idx}.pt')\n except:\n break\n embds.append(embd)\n texts.extend(text)\n indexes.extend(index)\n embds = np.concatenate(embds)\n # read faiss index\n model_name = args['model']\n pretrained_model_name = args['pretrained_model'].replace('/', '_')\n searcher = Searcher(args['index_type'], dimension=args['dimension'], nprobe=args['index_nprobe'])\n searcher.load(\n f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/{model_name}_{pretrained_model_name}_faiss.ckpt',\n f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/{model_name}_{pretrained_model_name}_corpus.ckpt',\n )\n # speed up with gpu\n searcher.move_to_gpu(device=args['local_rank'])\n\n # search\n collection = {}\n pbar = tqdm(range(0, len(embds), args['batch_size']))\n for i in pbar:\n batch = embds[i:i+args['batch_size']] # [B, E]\n text = texts[i:i+args['batch_size']]\n index = indexes[i:i+args['batch_size']]\n result = searcher._search(batch, topk=args['pool_size'])\n for t, idx, rest in zip(text, index, result):\n if t in rest:\n rest.remove(t)\n rest = rest[-args['gray_topk']:]\n if idx in collection:\n collection[idx].append({\n 'text': t,\n 'cands': rest\n })\n else:\n collection[idx] = [{'text': t, 'cands': rest}]\n\n # write into new file\n path = f'{args[\"root_dir\"]}/data/{args[\"dataset\"]}/train_gray_simcse_{args[\"local_rank\"]}.pt'\n torch.save(collection, path)\n","repo_name":"gmftbyGMFTBY/SimpleReDial-v1","sub_path":"simpleredial/inference_utils/gray_simcse.py","file_name":"gray_simcse.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"33"} +{"seq_id":"70309034334","text":"import os\nimport xml.etree.ElementTree as ET\n\n# define the classes\nCLASSES = {\n 'with_mask': 0,\n 'mask_weared_incorrect': 1,\n 'without_mask': 2\n}\n\n# create the output directory\nos.makedirs('face_mask_data/csv_annotations', exist_ok=True)\n\n# define the input and output directories\ninput_dir = 'face_mask_data/annotations'\noutput_file = 'face_mask_data/annotations.csv'\n\n# open the output file\nwith open(output_file, 'w') as f:\n # loop through all the XML files in the input directory\n for filename in os.listdir(input_dir):\n if filename.endswith('.xml'):\n # parse the XML file\n tree = ET.parse(os.path.join(input_dir, filename))\n root = tree.getroot()\n\n # get the image filename\n image_filename = root.find('filename').text\n\n # get the image size\n size = root.find('size')\n width = int(size.find('width').text)\n height = int(size.find('height').text)\n\n # loop through all the objects in the XML file\n for obj in root.findall('object'):\n # get the class name and bounding box coordinates\n class_name = obj.find('name').text\n bbox = obj.find('bndbox')\n xmin = int(bbox.find('xmin').text)\n ymin = int(bbox.find('ymin').text)\n xmax = int(bbox.find('xmax').text)\n ymax = int(bbox.find('ymax').text)\n\n # write the line to the output file\n line = f'/face_mask_data/images/{image_filename},{xmin},{ymin},{xmax},{ymax},{class_name}\\n'\n f.write(line)","repo_name":"ingmarinho/VISN","sub_path":"RetinaNet/convert_dataset.py","file_name":"convert_dataset.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"71569797215","text":"from flask import Flask, render_template, request, jsonify\nimport openai\n\napp = Flask(__name__)\n\n# Configura tu única clave de API (asegúrate de que tenga acceso a ambas API)\napi_key = \"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\"\n\ndef generar_descripcion_imagen(descripcion, num_imagenes):\n openai.api_key = api_key\n\n # Genera una descripción para la imagen usando ChatGPT\n respuesta = openai.Completion.create(\n engine=\"text-davinci-003\",\n prompt=f\"Genera una descripción para una imagen: {descripcion}\",\n max_tokens=50\n )\n descripcion_generada = respuesta.choices[0].text.strip()\n\n # Llama a la función para crear imágenes con DALL-E\n imagenes = crear_imagenes(descripcion_generada, num_imagenes)\n\n return descripcion_generada, imagenes\n\ndef crear_imagenes(descripcion, num_imagenes):\n # Utiliza la misma clave de API para DALL-E si es aplicable\n openai.api_key = api_key\n\n # Llama a la función para crear imágenes con DALL-E\n # (asegúrate de que la clave de API tenga acceso a DALL-E)\n respuestas = []\n for _ in range(num_imagenes):\n respuesta = openai.Image.create(\n prompt=descripcion,\n n=1, # Generar una imagen a la vez\n size='512x512'\n )\n respuestas.append(respuesta[\"data\"][0][\"url\"])\n return respuestas\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n if request.method == \"POST\":\n data = request.json\n descripcion = data[\"descripcion\"]\n numero_imagenes = int(data[\"numeroImagenes\"])\n try:\n descripcion_generada, imagenes = generar_descripcion_imagen(descripcion, numero_imagenes)\n return jsonify({\"descripcion_generada\": descripcion_generada, \"imagenes\": imagenes})\n except openai.error.APIError as e:\n return jsonify({\"error\": str(e)})\n return render_template(\"index.html\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"JocelynJimenezML/flaskProjectE","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"43478669758","text":"import unittest\n\nfrom soundmining_tools import supercollider_client, supercollider_score\n\n\nclass TestSupercolliderScore(unittest.TestCase):\n\n def test_empty_score(self) -> None:\n score = supercollider_score.SupercolliderScore()\n score_string = score.make_score_string()\n print(score_string)\n expected = \"[\\n[0, [\\\\c_set, 0, 0]]\\n]\\n\"\n self.assertEqual(score_string, expected)\n\n def test_g_new(self) -> None:\n score = supercollider_score.SupercolliderScore()\n score.add_message(supercollider_client.group_head(0, 1004))\n score_string = score.make_score_string()\n expected = \"[\\n[0, [\\\\g_new, 1004, 0, 0]],\\n[0, [\\\\c_set, 0, 0]]\\n]\\n\"\n self.assertEqual(score_string, expected)\n\n def test_load_dir(self) -> None:\n score = supercollider_score.SupercolliderScore()\n dir = \"/Users/danielstahl/Documents/Projects/soundmining-modular/src/main/sc/synths\"\n message_string = score.message_to_string(0, supercollider_client.load_dir(dir))\n expected = f\"[0, [\\\\d_loadDir, '{dir}']]\"\n self.assertEqual(message_string, expected)\n\n def test_simple_new_instrument(self) -> None:\n score = supercollider_score.SupercolliderScore()\n new_synth_message = supercollider_client.new_synth(\"monoVolume\", 1, 1004, [\"out\", 90, \"dur\", 8.402653573017457, \"in\", 89, \"ampBus\", 24])\n message_string = score.message_to_string(18.994464844699948, new_synth_message)\n expected = \"[18.994464844699948, [\\\\s_new, \\\\monoVolume, -1, 1, 1004, \\\\out, 90, \\\\dur, 8.402653694152832, \\\\in, 89, \\\\ampBus, 24]]\"\n self.assertEqual(message_string, expected)\n\n def test_new_instrument_with_array(self) -> None:\n # [11.234355838764865, [\\s_new, \\twoBlockControl, -1, 0, 1004, \\out, 27, \\dur, 15.351078398119684, \\levels, [0.0, 0.07418931824630097, 0.0], \\times, [0.39561834608925445, 0.39679712617529117], \\curves, [0.0, 0.0]].asOSCArgArray]\n score = supercollider_score.SupercolliderScore()\n new_synth_message = supercollider_client.new_synth(\"twoBlockControl\", 1, 1004, [\"out\", 27, \"dur\", 15.351078398119684, \"levels\", [0.0, 0.07418931824630097, 0.0], \"times\", [0.39561834608925445, 0.39679712617529117], \"curves\", [0.0, 0.0]])\n message_string = score.message_to_string(11.234355838764865, new_synth_message)\n expected = \"[11.234355838764865, [\\\\s_new, \\\\twoBlockControl, -1, 1, 1004, \\\\out, 27, \\\\dur, 15.351078033447266, \\\\levels, [0.0, 0.07418932020664215, 0.0], \\\\times, [0.39561834931373596, 0.3967971205711365], \\\\curves, [0.0, 0.0]].asOSCArgArray]\"\n self.assertEqual(message_string, expected)\n","repo_name":"danielstahl/py-soundmining-tools","sub_path":"tests/test_supercollider_score.py","file_name":"test_supercollider_score.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"13831388904","text":"# -*- encoding: utf-8 -*-\r\n# -*- mode: python -*-\r\n# Скрипт сборки updater-а для PyInstaller.\r\nfrom glob import glob\r\na = Analysis([# Список основных файлов апгрейдера.\r\n 'k3a.py',\r\n 'Parser.py',\r\n 'upgrade.py',\r\n ],\r\n pathex=['C:\\\\Tools\\\\pyinstaller-2.0'],\r\n # Список неявно импортируемых модулей-плагинов апгрейдера.\r\n hiddenimports=map(lambda x: '.'.join(x.split('.')[:-1]), glob('upgrade-*.py')),\r\n hookspath=None)\r\npyz = PYZ(a.pure)\r\nexe = EXE(pyz,\r\n a.scripts,\r\n a.binaries,\r\n a.zipfiles,\r\n a.datas,\r\n name=os.path.join('upgrader.exe'),\r\n debug=False,\r\n strip=None,\r\n upx=True,\r\n console=True )\r\n","repo_name":"Mingun/k3a-utils","sub_path":"upgrader.spec","file_name":"upgrader.spec","file_ext":"spec","file_size_in_byte":875,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"36996165275","text":"import pytest\n\nfrom textual.css.errors import StyleValueError\nfrom textual.css.query import NoMatches\nfrom textual.dom import DOMNode, BadIdentifier\n\n\ndef test_display_default():\n node = DOMNode()\n assert node.display is True\n\n\n@pytest.mark.parametrize(\n \"setter_value,style_value\",\n [[True, \"block\"], [False, \"none\"], [\"block\", \"block\"], [\"none\", \"none\"]],\n)\ndef test_display_set_bool(setter_value, style_value):\n node = DOMNode()\n node.display = setter_value\n assert node.styles.display == style_value\n\n\ndef test_display_set_invalid_value():\n node = DOMNode()\n with pytest.raises(StyleValueError):\n node.display = \"blah\"\n\n\n@pytest.fixture\ndef parent():\n parent = DOMNode(id=\"parent\")\n child1 = DOMNode(id=\"child1\")\n child2 = DOMNode(id=\"child2\")\n grandchild1 = DOMNode(id=\"grandchild1\")\n child1._add_child(grandchild1)\n\n parent._add_child(child1)\n parent._add_child(child2)\n\n yield parent\n\n\ndef test_get_child_gets_first_child(parent):\n child = parent.get_child(id=\"child1\")\n assert child.id == \"child1\"\n assert child.get_child(id=\"grandchild1\").id == \"grandchild1\"\n assert parent.get_child(id=\"child2\").id == \"child2\"\n\n\ndef test_get_child_no_matching_child(parent):\n with pytest.raises(NoMatches):\n parent.get_child(id=\"doesnt-exist\")\n\n\ndef test_get_child_only_immediate_descendents(parent):\n with pytest.raises(NoMatches):\n parent.get_child(id=\"grandchild1\")\n\n\ndef test_validate():\n with pytest.raises(BadIdentifier):\n DOMNode(id=\"23\")\n with pytest.raises(BadIdentifier):\n DOMNode(id=\".3\")\n with pytest.raises(BadIdentifier):\n DOMNode(classes=\"+2323\")\n with pytest.raises(BadIdentifier):\n DOMNode(classes=\"foo 22\")\n\n node = DOMNode()\n node.add_class(\"foo\")\n with pytest.raises(BadIdentifier):\n node.add_class(\"1\")\n with pytest.raises(BadIdentifier):\n node.remove_class(\"1\")\n with pytest.raises(BadIdentifier):\n node.toggle_class(\"1\")\n\n\n@pytest.fixture\ndef search():\n \"\"\"\n a\n / \\\n b c\n / / \\\n d e f\n \"\"\"\n a = DOMNode(id=\"a\")\n b = DOMNode(id=\"b\")\n c = DOMNode(id=\"c\")\n d = DOMNode(id=\"d\")\n e = DOMNode(id=\"e\")\n f = DOMNode(id=\"f\")\n\n a._add_child(b)\n a._add_child(c)\n b._add_child(d)\n c._add_child(e)\n c._add_child(f)\n\n yield a\n\n\ndef test_walk_children_depth(search):\n children = [\n node.id for node in search.walk_children(method=\"depth\", with_self=False)\n ]\n assert children == [\"b\", \"d\", \"c\", \"e\", \"f\"]\n\n\ndef test_walk_children_with_self_depth(search):\n children = [\n node.id for node in search.walk_children(method=\"depth\", with_self=True)\n ]\n assert children == [\"a\", \"b\", \"d\", \"c\", \"e\", \"f\"]\n\n\ndef test_walk_children_breadth(search):\n children = [\n node.id for node in search.walk_children(with_self=False, method=\"breadth\")\n ]\n print(children)\n assert children == [\"b\", \"c\", \"d\", \"e\", \"f\"]\n\n\ndef test_walk_children_with_self_breadth(search):\n children = [\n node.id for node in search.walk_children(with_self=True, method=\"breadth\")\n ]\n print(children)\n assert children == [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n\n children = [\n node.id\n for node in search.walk_children(with_self=True, method=\"breadth\", reverse=True)\n ]\n\n assert children == [\"f\", \"e\", \"d\", \"c\", \"b\", \"a\"]\n","repo_name":"pengwon/textual","sub_path":"tests/test_dom.py","file_name":"test_dom.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"33"} +{"seq_id":"11815349657","text":"import tkinter as tk\nimport os\nimport shutil\nimport os.path\nfrom tkinter.filedialog import askdirectory, askopenfile, askopenfilename\n\n# voice assistant module\nimport pyttsx3\nimport speech_recognition as sr\nimport wikipedia\nimport pyjokes\nimport random\nimport requests\nimport datetime\n\n\nimport threading\n\n# utilities for voice assistant\nengine = pyttsx3.init(\"sapi5\")\nvoices = engine.getProperty(\"voices\")\nengine.setProperty(\"voice\", voices[0].id)\n\n\ndef speak(audio):\n \"\"\"\n Speaks audio\n \"\"\"\n engine.say(audio)\n engine.runAndWait()\n\n\ndef command():\n \"\"\"\n Listens to commands\n \"\"\"\n\n r = sr.Recognizer()\n i = 0\n while True:\n with sr.Microphone() as source:\n if i == 0:\n r.adjust_for_ambient_noise(source, duration=1)\n speak(\"Alexa: Listening...\")\n audio = r.listen(source, phrase_time_limit=6)\n try:\n query = r.recognize_google(audio)\n speak(f\"You said: {query}\")\n return query\n except:\n speak(\"Try Again\")\n i += 1\n\n\ndef clickVoiceAssistantButton():\n lbl_text.set(\"Voice Assistant mode: ON\")\n window.update_idletasks()\n\n def VoiceAssistantButtonActions():\n\n while True:\n query = command().lower() ## takes user command\n\n if \"name\" in query:\n speak(\"Hello Machine! My Name is Alexa\")\n elif \"are you single\" in query:\n answers = [\n \"I am in a relationship with wifi\",\n \"No, I love spending time thinking about my crush wifi\",\n ]\n speak(random.choice(answers))\n elif \"hate\" in query:\n speak(\"I hate when people called me a machine\")\n elif \"love\" in query:\n speak(\"I loves to chat with machines like you\")\n ### time\n elif \"time\" in query:\n time = datetime.datetime.now().strftime(\"%I:%M %p\")\n speak(f\"It's {time} master\")\n\n ### celebrity\n elif \"who is\" in query:\n query = query.replace(\"who is\", \"\")\n speak(wikipedia.summary(query, 2))\n\n ### Joke\n elif \"joke\" in query:\n speak(pyjokes.get_joke())\n\n ### news\n elif \"news\" in query:\n\n def trndnews():\n url = \"http://newsapi.org/v2/top-headlines?country=in&apiKey=59ff055b7c754a10a1f8afb4583ef1ab\"\n page = requests.get(url).json()\n article = page[\"articles\"]\n results = []\n for ar in article:\n results.append(ar[\"title\"])\n\n results = results[:3]\n speak(\"here are the top trending news....!!\")\n speak(\"Do yo want me to read!!!\")\n reply = command().lower()\n reply = str(reply)\n if reply == \"yes\":\n speak(results)\n else:\n speak(\"ok!!!!\")\n pass\n\n trndnews()\n\n ### music\n elif \"music\" in query:\n with open(r\"C://Desktop Assistant/music_folder_location.txt\") as f:\n music_dir = f.read()\n songs = os.listdir(music_dir)\n song = random.randint(0, len(songs) - 1)\n print(songs[song])\n speak(f\"playing {songs[song]}\")\n os.startfile(os.path.join(music_dir, songs[0]))\n\n elif \"exit\" in query:\n lbl_text.set(\"Voice Assistant mode: OFF\")\n window.update_idletasks()\n speak(\"Have a nice day ! \")\n break\n else:\n speak(\"I don't understand what you are saying\")\n\n t = threading.Thread(target=VoiceAssistantButtonActions)\n t.daemon = True\n t.start()\n\n\ndef clickOpenApplicationsButton():\n\n speak(\"Opening Applications...\")\n\n def OpenAppsActions():\n import subprocess\n\n with open(r\"C://Desktop Assistant/app_exe_locations.txt\") as f:\n lines = f.readlines()\n lines = [line.strip() for line in lines]\n for exe_location in lines:\n subprocess.Popen(exe_location)\n\n t = threading.Thread(target=OpenAppsActions)\n t.daemon = True\n t.start()\n\n\ndef clickMusicPlayerButton():\n\n speak(\"Playing music...\")\n\n def PlayMusicActions():\n with open(r\"C://Desktop Assistant/music_folder_location.txt\") as f:\n music_dir = f.read()\n songs = os.listdir(music_dir)\n song = random.randint(0, len(songs) - 1)\n print(songs[song])\n speak(f\"playing {songs[song]}\")\n os.startfile(os.path.join(music_dir, songs[song]))\n\n t = threading.Thread(target=PlayMusicActions)\n t.daemon = True\n t.start()\n\n\n# Information to ask when installing app for first time\n# - C://Desktop Assistant/music_folder_location.txt\n# C://Desktop Assistant/app_exe_locations.txt\n# if os.path.isdir(r'C://Desktop Assistant'): # this was in testing phase\n# shutil.rmtree(r'C://Desktop Assistant', ignore_errors=True)\n\nif not os.path.isdir(r\"C://Desktop Assistant\"):\n os.mkdir(r\"C://Desktop Assistant\")\n\n # Muisc part\n window = tk.Tk()\n window.title(\"Music folder location info\")\n\n window.rowconfigure(list(range(3)), minsize=40, weight=1)\n window.columnconfigure(list(range(1)), minsize=100, weight=1)\n\n def open_folder():\n folder_name = askdirectory()\n lbl_flr_name[\"text\"] = f\"You selected {folder_name}\"\n with open(r\"C://Desktop Assistant/music_folder_location.txt\", \"w\") as f:\n f.write(folder_name)\n\n lbl_info = tk.Label(\n master=window,\n text=\"Please select folder location of music files.\",\n font=(\"TkDefaultFont\", 20),\n )\n btns_frame = tk.Frame(master=window)\n btns_frame.rowconfigure(0, weight=1)\n btns_frame.columnconfigure(list(range(2)), weight=1)\n btn_open = tk.Button(\n master=btns_frame,\n text=\"Open\",\n command=open_folder,\n width=10,\n height=1,\n font=(\"TkDefaultFont\", 15),\n )\n btn_done = tk.Button(\n master=btns_frame,\n text=\"Done\",\n command=lambda: window.destroy(),\n width=10,\n height=1,\n font=(\"TkDefaultFont\", 15),\n )\n btn_open.grid(row=0, column=0, padx=5, pady=5)\n btn_done.grid(row=0, column=1, padx=5, pady=5)\n\n lbl_flr_name = tk.Label(\n master=window,\n text=\"Selected folder will be displayed here.\",\n font=(\"TkDefaultFont\", 10),\n )\n\n lbl_info.grid(row=0, column=0, padx=5, pady=5)\n btns_frame.grid(row=1, column=0, padx=5, pady=5, sticky=\"nsew\")\n lbl_flr_name.grid(row=2, column=0, padx=5, pady=5)\n\n height = 400\n width = 600\n window.geometry(f\"{width}x{height}\")\n window.mainloop()\n\n # Applications part\n window = tk.Tk()\n window.title(\"App exes location info\")\n\n window.rowconfigure(list(range(3)), minsize=40, weight=1)\n window.columnconfigure(list(range(1)), minsize=100, weight=1)\n\n def open_file():\n file_name = askopenfilename()\n if lbl_file_names[\"text\"] == \"Selected files will be displayed here.\":\n lbl_file_names[\"text\"] = f\"You selected:\\n{file_name}\"\n else:\n lbl_file_names[\"text\"] += f\"\\n{file_name}\"\n\n mode = (\n \"r+\"\n if os.path.exists(r\"C://Desktop Assistant/app_exe_locations.txt\")\n else \"w\"\n )\n with open(r\"C://Desktop Assistant/app_exe_locations.txt\", mode) as f:\n if mode == \"w\":\n write_text = file_name\n if mode == \"r+\":\n lines = f.readlines()\n lines = [line.strip() for line in lines]\n if file_name in lines:\n write_text = \"\"\n else:\n write_text = \"\\n\" + file_name\n f.write(write_text)\n\n lbl_info = tk.Label(\n master=window,\n text=\"Please select file locations of app executables.\",\n font=(\"TkDefaultFont\", 20),\n )\n btns_frame = tk.Frame(master=window)\n btns_frame.rowconfigure(0, weight=1)\n btns_frame.columnconfigure(list(range(2)), weight=1)\n btn_open = tk.Button(\n master=btns_frame,\n text=\"Open\",\n command=open_file,\n width=10,\n height=1,\n font=(\"TkDefaultFont\", 15),\n )\n btn_done = tk.Button(\n master=btns_frame,\n text=\"Done\",\n command=lambda: window.destroy(),\n width=10,\n height=1,\n font=(\"TkDefaultFont\", 15),\n )\n btn_open.grid(row=0, column=0, padx=5, pady=5)\n btn_done.grid(row=0, column=1, padx=5, pady=5)\n lbl_file_names = tk.Label(\n master=window,\n text=\"Selected files will be displayed here.\",\n font=(\"TkDefaultFont\", 10),\n )\n\n lbl_info.grid(row=0, column=0, padx=5, pady=5)\n btns_frame.grid(row=1, column=0, padx=5, pady=5, sticky=\"nsew\")\n lbl_file_names.grid(row=2, column=0, padx=5, pady=5)\n\n height = 400\n width = 600\n window.geometry(f\"{width}x{height}\")\n window.mainloop()\n\nwindow = tk.Tk()\nwindow.title(\"Desktop Assistant\")\n\n# configuring main window cells properties\nwindow.rowconfigure(list(range(1)), minsize=100, weight=1)\nwindow.columnconfigure(0, minsize=200, weight=1)\n\n# configuring buttons frame cells properties\nbtns_frame = tk.Frame(master=window, relief=tk.RAISED, bd=3)\nbtns_frame.rowconfigure(0, weight=1)\nbtns_frame.columnconfigure(list(range(3)), weight=1)\n\n# configure label at second row\nlbl_text = tk.StringVar()\nlbl_text.set(\"Voice Assistant mode: OFF\")\nlbl_info = tk.Label(master=window, textvariable=lbl_text, width=100, height=1)\n\n\n# Adding buttons\nbtn_voice_ass = tk.Button(\n master=btns_frame,\n text=\"Voice Assistant 🎤\",\n command=clickVoiceAssistantButton,\n font=(\"TkDefaultFont\", 15),\n)\nbtn_open_apps = tk.Button(\n master=btns_frame,\n text=\"Open Applications\",\n command=clickOpenApplicationsButton,\n font=(\"TkDefaultFont\", 15),\n)\nbtn_music_player = tk.Button(\n master=btns_frame,\n text=\"Play music\",\n command=clickMusicPlayerButton,\n font=(\"TkDefaultFont\", 15),\n width=14,\n height=1,\n)\n\n# Placing buttonsX\nbtn_voice_ass.grid(row=0, column=0)\nbtn_open_apps.grid(row=0, column=1)\nbtn_music_player.grid(row=0, column=2)\n# Placing frame\nbtns_frame.grid(row=0, column=0, sticky=\"nsew\")\nlbl_info.place(anchor=\"se\", relx=1.0, rely=1.0)\n\n# starting mainloop\nheight = 400\nwidth = 700\nwindow.geometry(f\"{width}x{height}\")\nwindow.mainloop()\n","repo_name":"shiva1998-R/DesktopAssistant","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"6968851974","text":"import os\n\nfrom flask import request, make_response\n\nfrom flask_restx import Api, Resource, fields\nfrom src.services.route_service import RouteService\nfrom src.services.business_trips_service import BusinessTripService\n\nfrom src import app\nfrom src.database import connect_to_database\nfrom src.routes import add_routes\n\n\nconnect_to_database(os.getenv(\"DB_URI\"))\nadd_routes()\n\n\napi = Api(app)\n\n\nmodel = api.model(\n \"CalculatePathPayload\",\n {\n \"name\": fields.String(required=True, description=\"str. Penguin name.\"),\n \"destinations\": fields.List(\n fields.String, required=True, description=\"List of destinations.\"\n ),\n \"business\": fields.Boolean(\n required=True,\n description='Indicates if it is a business trip. `true` for \"business\" trip, `false` for \"casual\" trip.',\n ),\n \"distances\": fields.List(\n fields.String, required=True, description=\"List with all places to visit.\"\n ),\n },\n)\n\n\n@api.route(\"/calculate\")\nclass CalculatePathRouter(Resource):\n @api.expect(model)\n def post(self):\n service = RouteService(**request.json)\n result = service.get_path()\n return make_response(result, 200)\n\n\n@api.route(\"/business-trips\")\nclass BusinessTripsRouter(Resource):\n def get(self):\n service = BusinessTripService()\n result = service.get_data()\n return make_response(result)\n","repo_name":"artemziborev/python_navigation_api","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"32033300804","text":"import json\nimport sys\n\ndef create_seven_char_dict( allpath, sevenp):\n with open( allpath, 'rt') as allf:\n all_dict = json.load( allf)\n seven_dict = dict( )\n for word, _ in all_dict.items( ):\n if len( word) < 8:\n seven_dict[word] = 1\n with open( sevenp, 'wt') as sevenf:\n json.dump( seven_dict, sevenf)\n\nif __name__ == \"__main__\":\n create_seven_char_dict( sys.argv[1], sys.argv[2])\n","repo_name":"osullivj/plates","sub_path":"src/py/util/seven_char_words.py","file_name":"seven_char_words.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"12832185707","text":"import logging\nfrom typing import Dict, Tuple\n\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash_table.Format import Format, Scheme, Group\nfrom pkg_resources import resource_string as resource_bytes\n\nfrom craid.club.regions.RegionFactory import RegionFactory\nfrom craid.eddb.faction.SquadronXYZ import SquadronXYZ\nfrom craid.eddb.system.SystemXYZ import SystemXYZ\n\n\nclass AnnoyingCrap(object):\n # NOTE: Don't use index 0\n cannedActions: Dict[int, Tuple[str, str, str, str]] = \\\n {1 : (\"find Club Activity near me\",\n \"{isHomeSystem} contains false\",\n [{'column_id': 'distance', 'direction': 'asc'}],\n \"overview\"),\n 2 : (\"fight The Club in war zones\",\n \"{vulnerable} contains War && {isHomeSystem} contains false\",\n [{'column_id': 'distance', 'direction': 'asc'}],\n \"cz\"),\n 3 : (\"hunt for bounties\",\n \"{isHomeSystem} contains false && {bountyHuntingScore} >= 50\",\n [{'column_id': 'distance', 'direction': 'asc'}],\n \"bh\"),\n 4 : (\"smuggle\",\n \"{isHomeSystem} contains false && {smugglingScore} >= 50\",\n [{'column_id': 'distance', 'direction': 'asc'}],\n \"smuggle\"),\n 5 : (\"trade\",\n \"{isHomeSystem} contains false && {salesScore} > 50\",\n [{'column_id': 'distance', 'direction': 'asc'}],\n \"trade\"),\n 6 : (\"mine\",\n \"{isHomeSystem} contains false && {mineralSalesScore} > 1\",\n [{'column_id': 'distance', 'direction': 'asc'}],\n \"mine\"),\n 7 : (\"explore\",\n \"{isHomeSystem} contains false\",\n [{'column_id': 'explorationScore', 'direction': 'desc'}],\n \"explore\"),\n 8 : (\"spy behind enemy lines\",\n '{isHomeSystem} contains false',\n [{'column_id': 'updated', 'direction': 'asc'}],\n \"scouting\"),\n 9 : (\"go on a piracy/murder rampage\",\n \"{isHomeSystem} contains false && {piracyMurderScore} >= 50\",\n [{'column_id': 'piracyMurderScore', 'direction': 'desc'}, {'column_id': 'distance', 'direction': 'asc'}],\n \"piracyMurder\"),\n 10: (\"run missions\", \"{isHomeSystem} contains false && {missionScore} > 120 && {distance} < 100\",\n [{'column_id': 'missionScore', 'direction': 'desc'}, {'column_id': 'distance', 'direction': 'asc'}],\n \"missions\"),\n 11: (\"beat The Club in an election\",\n \"{vulnerable} contains Elect && {isHomeSystem} contains false\",\n [{'column_id': 'distance', 'direction': 'asc'}],\n \"election\"),\n 12: (\"see easy club systems to solo\",\n \"{isHomeSystem} contains false && {difficulty} < 5\",\n [{'column_id': 'difficulty', 'direction': 'asc'}],\n \"single\"),\n 13: (\"see hard club systems to solo\",\n \"{isHomeSystem} contains false && {difficulty} > 5 && {difficulty} < 50\",\n [{'column_id': 'difficulty', 'direction': 'asc'}],\n \"single\"),\n 14: (\"see systems for small groups\",\n \"{isHomeSystem} contains false && {difficulty} > 25 && {difficulty} < 150\",\n [{'column_id': 'difficulty', 'direction': 'asc'}],\n \"group\"),\n 15: (\"see systems for large groups\",\n \"{isHomeSystem} contains false && {difficulty} > 100 && {difficulty} < 750\",\n [{'column_id': 'difficulty', 'direction': 'asc'}],\n \"group\"),\n 16: (\"see systems for squadron alliances\",\n \"{isHomeSystem} contains false && {difficulty} > 750 && {difficulty} < 950000\",\n [{'column_id': 'difficulty', 'direction': 'asc'}],\n \"group\")}\n\n def __init__(self):\n super().__init__()\n\n @staticmethod\n def getMarkdown(which: str) -> dcc.Markdown:\n text = resource_bytes('craid.dashbd.text', which + \".md\").decode('utf-8')\n return dcc.Markdown(text)\n\n @staticmethod\n def getString(which: str) -> dcc.Markdown:\n text = resource_bytes('craid.dashbd.text', which + \".md\").decode('utf-8')\n return text\n\n @staticmethod\n def getLocationDropdown():\n # _systemNameToXYZ = SystemXYZ.myDict\n # print(\"dropdown len=\" + str(len(SystemXYZ.myDict)))\n opts = []\n logging.debug(\"Loading location dropdown\")\n # keys: List[str] = sorted(SystemXYZ.myDict)\n for it in SystemXYZ.myDict.keys():\n opts.append({'label': it, 'value': it})\n return opts\n\n @staticmethod\n def getFilter(val3: int):\n if val3 == 0: val3 = 1\n tup = AnnoyingCrap.cannedActions[val3]\n return tup[1]\n\n @staticmethod\n def getSort(val3: int):\n if val3 == 0: val3 = 1\n return AnnoyingCrap.cannedActions[val3][2]\n\n @staticmethod\n def getMessage(val3: int):\n if val3 == 0: val3 = 1\n shortFile: str = AnnoyingCrap.cannedActions[val3][3]\n return AnnoyingCrap.getMarkdown(shortFile)\n\n @staticmethod\n def getThirdDropdown():\n gopts = []\n keys = AnnoyingCrap.cannedActions.keys()\n key: int\n for key in keys:\n lab = AnnoyingCrap.cannedActions[key][0]\n gopts.append({'label': lab, 'value': key})\n\n return gopts\n\n # \"hidden\": True, is not a thing, unfortunately\n @staticmethod\n def getTheColumns():\n allowHiddenColumns = False # INFO: pending a dash bug fix, see https://github.com/plotly/dash-table/issues/789\n return [\n {\"name\": 'System', \"id\": 'systemName', \"deletable\": False, \"selectable\": False},\n {\"name\": 'Faction', \"id\": 'factionName', \"deletable\": False, \"selectable\": False},\n # {\"name\": 'x', \"id\": 'x', \"deletable\": False, \"selectable\": False, \"hideable\": True, \"type\": \"numeric\"},\n # {\"name\": 'y', \"id\": 'y', \"deletable\": False, \"selectable\": False, \"hideable\": True, \"type\": \"numeric\"},\n # {\"name\": 'z', \"id\": 'z', \"deletable\": False, \"selectable\": False, \"hideable\": True, \"type\": \"numeric\"},\n {\"name\" : 'Home', \"id\": 'isHomeSystem', \"deletable\": False, \"hideable\": allowHiddenColumns,\n \"selectable\": False},\n {\"name\" : 'Population', \"id\": 'population', \"deletable\": False, \"hideable\": allowHiddenColumns,\n \"selectable\": False,\n \"type\" : \"numeric\", 'format': Format(precision=0, scheme=Scheme.fixed, group=Group.yes)},\n {\"name\": 'Inf.', \"id\": 'influence', \"deletable\": False, \"hideable\": allowHiddenColumns, \"selectable\": False,\n \"type\": \"numeric\", 'format': Format(precision=2, scheme=Scheme.fixed, group=Group.yes)},\n {\"name\" : 'Difficulty', \"id\": 'difficulty', \"deletable\": False, \"selectable\": False, \"type\": \"numeric\",\n 'format': Format(precision=1, scheme=Scheme.fixed, group=Group.yes)},\n {\"name\": 'Scouted', \"id\": 'updated', \"deletable\": False, \"selectable\": False, \"type\": \"datetime\"},\n {\"name\" : 'Control', \"id\": 'control', \"deletable\": False, \"hideable\": allowHiddenColumns,\n \"selectable\": False},\n {\"name\": 'Vulnerable', \"id\": 'vulnerable', \"deletable\": False, \"selectable\": False},\n {\"name\": 'Dist.', \"id\": 'distance', \"deletable\": False, \"selectable\": False, \"type\": \"numeric\"},\n {\"name\" : 'MissionScore', \"id\": 'missionScore', \"deletable\": False, \"selectable\": False,\n \"hideable\": allowHiddenColumns, \"type\": \"numeric\"},\n {\"name\" : 'TradeScore', \"id\": 'salesScore', \"deletable\": False, \"selectable\": False,\n \"hideable\": allowHiddenColumns, \"type\": \"numeric\"},\n {\"name\": 'ExploreScore', \"id\": 'explorationScore', \"hideable\": allowHiddenColumns, \"type\": \"numeric\"},\n {\"name\" : 'MineralSalesScore', \"id\": 'mineralSalesScore', \"deletable\": False, \"selectable\": False,\n \"hideable\": allowHiddenColumns, \"type\": \"numeric\"},\n {\"name\": 'BountyHuntScore', \"id\": 'bountyHuntingScore', \"hideable\": allowHiddenColumns, \"type\": \"numeric\"},\n {\"name\": 'SmugglingScore', \"id\": 'smugglingScore', \"hideable\": allowHiddenColumns, \"type\": \"numeric\"},\n {\"name\": 'PiracyMurderScore', \"id\": 'piracyMurderScore', \"hideable\": allowHiddenColumns, \"type\": \"numeric\"},\n {\"name\": 'controllingFaction', \"id\": 'controllingFaction', \"deletable\": False, \"selectable\": False},\n\n ]\n\n #\n # 3d Map Stuff Follows\n #\n\n @staticmethod\n def getSquadronDropdown():\n logging.info(\"dropdown len=\" + str(len(SquadronXYZ.myDict)))\n opts = []\n logging.debug(\"Loading squadron dropdown\")\n for it in SquadronXYZ.myDict.keys():\n opts.append({'label': it, 'value': it})\n\n # print(\"shape= \" + str(np.shape(opts)))\n systemDropdown = dcc.Dropdown(\n id='squadronDropdown',\n options=opts,\n # value='Sol',\n placeholder='Select squadron',\n className=\"dropdown-select\",\n # persistence=True,\n )\n return systemDropdown\n\n @staticmethod\n def getRegionDropdown():\n logging.info(\"dropdown len=\" + str(len(RegionFactory.regionDict)))\n opts = []\n # logging.debug(\"Loading squadron dropdown\")\n for it in RegionFactory.regionDict.keys():\n opts.append({'label': it, 'value': it})\n\n regionDropdown = dcc.Dropdown(\n id='regionDropdown',\n options=opts,\n # value='Sol',\n placeholder='Select region',\n className=\"dropdown-select\",\n # persistence=True,\n )\n return regionDropdown\n\n @staticmethod\n def setMarkerSize(dataFrame):\n dataFrame.loc[dataFrame['control'] == True, 'marker_size'] = 8 # Medium is not home/control\n dataFrame.loc[dataFrame['control'] == False, 'marker_size'] = 5 # Small is not home/not control\n dataFrame.loc[dataFrame['isHomeSystem'] == True, 'marker_size'] = 15 # Large is home\n # df[\"marker_size\"] = df[\"influence\"].apply(lambda x: 5+ x/5)\n\n @staticmethod\n def setMarkerColors(dataFrame):\n dataFrame.loc[dataFrame['control'] == True, 'color'] = \"#ffbf00\" # Yellow is control/not home\n dataFrame.loc[dataFrame['control'] == False, 'color'] = \"#00ff00\" # Green is not home/not control\n dataFrame.loc[dataFrame['isHomeSystem'] == True, 'color'] = \"#ff0000\" # Red is homesystem\n\n @staticmethod\n def setHovertext(dataFrame):\n dataFrame['htext'] = dataFrame[['systemName', 'factionName']].agg('\\n'.join, axis=1)\n\n\n\ntab_style = {\n 'borderBottom' : '1px solid #d6d6d6',\n 'padding' : '6px',\n 'backgroundColor': '#3c3f41',\n 'color' : 'whitesmoke',\n}\ntab_selected_style = {\n 'borderTop' : '1px solid #d6d6d6',\n 'borderBottom' : '1px solid #d6d6d6',\n 'fontWeight' : 'bold',\n 'backgroundColor': '#4e5254',\n 'color' : 'white',\n 'padding' : '6px'\n}\n\n\ndef enCard(contents) -> html.Div:\n return html.Div(className=\"card\", children=[\n contents,\n ])\n\n\ndef makeArticleCard(contents, id_) -> html.Div:\n return enCard(html.Article(contents, id=id_, className=\"simpleColItem\"))\n\n\ndef makeDiscordCard(msg, _id, _idnum) -> html.Div:\n return html.Div(className=\"card\", children=[\n dcc.Markdown(msg),\n html.Iframe(id=f\"{_id}\", src=f\"https://discordapp.com/widget?id={_idnum}&theme=dark\",\n width=\"350\", height=\"400\"),\n ])\n\ndef makeDiscordIframe(_id, _idnum) -> html.Iframe:\n return html.Iframe(id=f\"{_id}\", src=f\"https://discordapp.com/widget?id={_idnum}&theme=dark\",\n width=\"350\", height=\"400\")\n\n\nmy_meta_tags = [\n # A description of the app, used by e.g.\n # search engines when displaying search results.\n {\n 'name' : 'description',\n 'content': 'Tool to help Elite: Dangerous commanders identify, evaluate and eradicate factions linked to the shadowy organization known as The Club.'\n },\n # A tag that tells Internet Explorer (IE)\n # to use the latest renderer version available\n # to that browser (e.g. Edge)\n {\n 'http-equiv': 'X-UA-Compatible',\n 'content' : 'IE=edge'\n },\n # A tag that tells the browser not to scale\n # desktop widths to fit mobile screens.\n # Sets the width of the viewport (browser)\n # to the width of the device, and the zoom level\n # (initial scale) to 1.\n #\n # Necessary for \"true\" mobile support.\n {\n 'name' : 'viewport',\n 'content': 'width=device-width, initial-scale=1.0'\n }\n]\n","repo_name":"HausReport/ClubRaiders","sub_path":"appHelpers.py","file_name":"appHelpers.py","file_ext":"py","file_size_in_byte":12757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"26071529203","text":"import logging\n\ndef bubble_sort(arr):\n for end in range(len(arr)-1, -1, -1):\n for i in range(end):\n if arr[i] > arr[i+1]:\n arr[i], arr[i+1] = arr[i+1], arr[i]\n logging.info(str(arr))\n return arr\n\n\ndef better_bubble(arr):\n for end in range(len(arr)-1, -1, -1):\n is_sorted = True\n for i in range(end):\n if arr[i] > arr[i+1]:\n arr[i], arr[i+1] = arr[i+1], arr[i]\n logging.info(str(arr))\n is_sorted = False\n if is_sorted:\n break\n return arr\n\n\ndef main():\n logging.basicConfig(level=logging.INFO)\n lst = [5,3,2,4,1]\n print(bubble_sort(lst[:]))\n print(better_bubble(lst[:]))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"iskhakov-s/algorithms_class","sub_path":"sort/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"70068879456","text":"import pandas as pd\nimport time\nimport datetime\n#from .custom_graph import *\nimport numpy as np\n\nfrom src.custom_graph import get_Graph, get_data\n\n\n# TODO: Probably lot of abundance here. fix Imports as well\n\ndef time_func(f, args=[], kw_args={}):\n \"\"\"\n Times one call to f with args, kw_args.\n\n Arguments:\n f -- the function to be timed\n args -- list of arguments to pass to f\n kw_args -- dictionary of keyword arguments to pass to f.\n\n Returns:\n a tuple containing the result of the call and the time it\n took (in seconds).\n\n \"\"\"\n start_time = time.time()\n result = f(*args, **kw_args)\n end_time = time.time()\n\n return result, end_time - start_time\n\n\ndef get_window(start_datetime, df, time_window=2, date_feature=' Timestamp', time_scale='min', return_next_time=False):\n \"\"\"\n Returns the time window starting with start_datetime index and sync_window_size min long interval\n Also returns the next datetime in the df if df's date_col column is datetime and sorted ascending\n \"\"\"\n if time_scale == 'min':\n min_delta = datetime.timedelta(minutes=time_window)\n elif time_scale == 'sec':\n min_delta = datetime.timedelta(seconds=time_window)\n else:\n raise SyntaxError('time_scale should be {min} or {sec}')\n end_datetime = start_datetime + min_delta\n window = df[(df[date_feature] < end_datetime) & (df[date_feature] >= start_datetime)]\n if return_next_time:\n # Sorted assumed\n last_ind = df[df[date_feature] < end_datetime].index[-1]\n ind = np.argwhere(df.index == last_ind)[0, 0]\n next_ind = df.index[ind] if ind + 1 >= df.shape[0] else df.index[ind + 1]\n next_datetime = df[date_feature][next_ind]\n return window, end_datetime, next_datetime\n else:\n return window, end_datetime\n\n\ndef get_endDatetime(start_datetime, TW=2):\n \"Faster for just getting end datetime\"\n min_delta = datetime.timedelta(minutes=TW)\n end_datetime = start_datetime + min_delta\n return end_datetime\n\n\ndef append_Gfeats(df, g_data, G):\n \"\"\"\n Appends graph features to dataframe. g_data is the dictionary of graph\n features returned by get_data funtion and g is the graph\n \"\"\"\n node_feats = list(g_data.keys())\n\n for feat in node_feats:\n temp_s_sr = df.iloc[:, 1].apply(lambda node: G.nodes[node][feat])\n temp_s_df = pd.DataFrame(temp_s_sr.values, index=temp_s_sr.index, columns=['s_' + feat])\n\n temp_d_sr = df.iloc[:, 3].apply(lambda node: G.nodes[node][feat])\n temp_d_df = pd.DataFrame(temp_d_sr.values, index=temp_d_sr.index, columns=['d_' + feat])\n\n df.loc[:, 's_' + feat] = temp_s_df.values\n df.loc[:, 'd_' + feat] = temp_d_df.values\n\n return df.copy()\n\n\ndef getNewCols(df, start_datetime):\n # Returns the appended column names of the dataframe with graph features\n window, current_datetime = get_window(start_datetime, df, 1)\n G = get_Graph(window, df.columns)\n g_data, G = get_data(G)\n temp_df = append_Gfeats(window.copy(), g_data, G)\n return temp_df.columns\n\n\ndef appendTimeWinGFeats(df, date_feature, TW, time_scale, new_cols):\n # Appends the time windowed graph features to the whole dataset\n b_DF = pd.DataFrame(columns=new_cols)\n\n current_datetime = df.iloc[0][date_feature]\n last_datetime = df.iloc[-1][date_feature]\n while current_datetime <= last_datetime:\n window, current_datetime = get_window(current_datetime, df, TW, time_scale=time_scale)\n if window.empty:\n continue\n G = get_Graph(window, new_cols)\n g_data, G = get_data(G)\n\n temp_df = append_Gfeats(window.copy(), g_data, G)\n b_DF = b_DF.append(temp_df)\n return b_DF.copy()\n","repo_name":"ab126/NRE","sub_path":"src/archive/time_windowed_archive.py","file_name":"time_windowed_archive.py","file_ext":"py","file_size_in_byte":3736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"25307883848","text":"a=int(input())\nimport math\nb= math.sqrt(a)\nc=0\nfor i in range(1,a):\n if i*i==a:\n c=i\nif c==b:\n print(\"True\")\nelse:\n print(\"False\")\n ","repo_name":"deepakdeepu000/codemind-python","sub_path":"perfect_square_root_or_not.py","file_name":"perfect_square_root_or_not.py","file_ext":"py","file_size_in_byte":151,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"4832399997","text":"import sys\nsys.setrecursionlimit(10000)\ndef dfs(v):\n visited[v] = True\n for u in vertex_list[v]:\n if not visited[u]:\n visited[u] = True\n parent[u] = v\n dfs(u)\n\ndef find(v):\n if v != parent[v]:\n parent[v] = find(parent[v])\n return parent[v]\n return v\n\nN, M = map(int, sys.stdin.readline().split())\nedge_list = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]\nparent = [i for i in range(N + 1)]\nvertex_list = [[] for _ in range(N + 1)]\nvisited = [False] * (N + 1)\n\nfor u, v in edge_list:\n vertex_list[u].append(v)\n vertex_list[v].append(u)\n\nfor i in range(1, N):\n if not visited[i]:\n dfs(i)\n\nfor i in range(len(parent)):\n find(i)\n\nprint(len(list(set(parent[1:]))))","repo_name":"uujeen/algorithm","sub_path":"Baekjoon-py/Silver/11724.py","file_name":"11724.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"18671659318","text":"# 백준\n# 4881번 : 자리수의 제곱\nimport sys\n\n##* 89, 1\n##* 0< a,b < 10^9\n\n# 1.숫자 제곱 합 함수\ndef square_fun(number):\n str_num = list(number) # map -> list\n # print(str_num[0][0]) # 첫째 자리\n # print(str_num[0]) # 넘버\n # print(str_num) # 리스트\n sum_next = 0\n # breakPoint = True\n while str_num.count(str_num[-1]) < 2:\n if str_num.count(str_num[-1]) <2:\n # breakPoint = False\n break\n for i in str_num[-1]:\n temp_num = int(i) * int(i)\n sum_next += temp_num\n str_num.append(str(sum_next))\n # print(str_num) # 제곱합한 숫자 리스트에 추가, 루프 리스트 리턴\n return str_num\n\n\n# 수열 길이\ndef count_list_fun(list_l):\n # temp = list_l.split(',')\n # length = len(temp)\n length = len(list_l)\n return length\n\n\n# 재귀\ndef loop_fun(list_n):\n list_length = 0\n # loop_escape = False\n while True:\n\n added_next = square_fun(list_n)\n # for i in added_next:\n # if i == added_next[-1]:\n # list_length = count_list_fun(added_next)\n # loop_escape = True\n # break\n # if loop_escape == True:\n # break\n if added_next[-1] in list_n:\n list_length = count_list_fun(added_next)\n break\n\n return list_length\n\ndef compare_fun(A, B):\n pass\n\n\n##! 0 0 입력일경우 종료\nif __name__ == '__main__':\n while True:\n a, b = map(str, sys.stdin.readline().split()) # str\n if a == 0 and b == 0:\n break\n else:\n A_list = loop_fun(a) # 제곱합 루프\n B_list = loop_fun(b) # \n print(a, b, compare_fun(A_list, B_list))\n # a = map(str, sys.stdin.readline().split()) # str\n # A_list = square_fun(a)\n # print(A_list)\n\n","repo_name":"KwanHoo/Data-Structure__Algorithm","sub_path":"parc/pracCode_24060/Baek_4881proto.py","file_name":"Baek_4881proto.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"70791752415","text":"import json\nimport re\n\nimport pandas as pd\nimport requests\nimport telebot\nimport sqlite3 as sq\nimport parse\nfrom hardcode import *\nimport os\nimport random\nfrom time import sleep\n\nbot = telebot.TeleBot(token)\ndb = sq.connect('grinder.db', check_same_thread=False)\ncursor = db.cursor()\n\n\ndef isu_parse(message):\n isu = message.text\n if len(isu) == 6:\n driver = parse.setup_browser(login_url=\"https://isu.ifmo.ru/\", login=isu_username, password=isu_password)\n course, faculty, program, name = parse.get_student_info(isu=isu, driver=driver, timeout=3)\n\n bot.send_message(message.chat.id, f\"Имя: {name}\\n\"\n f\"Факультет: {faculty}\\n\"\n f\"ОП: {program}\\n\"\n f\"Курс: {course}\")\n\n params = (message.chat.id, isu, course, faculty, program, name)\n cursor.execute(\"INSERT INTO temp_isu (tg_id, isu, course, faculty, program, credentials) VALUES (?, ?, ?, ?, ?, ?)\", params)\n db.commit()\n\n confirmation_markup = telebot.types.InlineKeyboardMarkup()\n confirmation_markup.add(telebot.types.InlineKeyboardButton('Да', callback_data='isu_verification|yes'),\n telebot.types.InlineKeyboardButton('Нет', callback_data='isu_verification|no'))\n bot.send_message(message.chat.id, \"Верны ли ваши данные?\", reply_markup=confirmation_markup)\n\n else:\n isu = bot.send_message(message.chat.id, \"Введите корректный номер ИСУ\")\n bot.register_next_step_handler(isu, isu_parse)\n\n\n@bot.callback_query_handler(func=lambda call: call.data.startswith('isu_verification'))\ndef isu_verification(call):\n if call.data == 'isu_verification|yes':\n cursor.execute(\"SELECT tg_id, isu, course, faculty, program, credentials FROM temp_isu WHERE tg_id=?\", [str(call.message.chat.id)])\n tg_id, isu, course, faculty, program, name = cursor.fetchone()\n\n cursor.execute(\"UPDATE main SET (ISU, faculty, major, grade, credentials) =(?, ?, ?, ?, ?) WHERE tg_id =?\",\n (int(isu), faculty, program, course, name, call.message.chat.id))\n set_gender(call.message)\n\n elif call.data == 'isu_verification|no':\n isu = bot.send_message(call.message.chat.id, \"Введите ваш номер ИСУ\")\n bot.register_next_step_handler(isu, isu_parse)\n\n\ndef set_gender(message):\n gender_markup = telebot.types.InlineKeyboardMarkup()\n gender_markup.add(telebot.types.InlineKeyboardButton('Мужчина', callback_data='male'),\n telebot.types.InlineKeyboardButton('Женщина', callback_data='female'),\n telebot.types.InlineKeyboardButton('Иное', callback_data='trans'))\n bot.send_message(message.chat.id, text='Ваш гендер?', reply_markup=gender_markup)\n\n\n@bot.callback_query_handler(func=lambda call: call.data in ['male', 'female', 'trans'])\ndef _set_gender(call):\n cursor.execute(\"UPDATE main SET gender =? WHERE tg_id =?\", (call.data, call.message.chat.id))\n set_ed_level(call.message)\n\n\ndef set_ed_level(message):\n education_markup = telebot.types.InlineKeyboardMarkup()\n education_markup.add(telebot.types.InlineKeyboardButton('Бакалавриат', callback_data='bachelor'),\n telebot.types.InlineKeyboardButton('Магистратура', callback_data='master'),\n telebot.types.InlineKeyboardButton('Аспирантура', callback_data='xz'))\n bot.send_message(message.chat.id, text='Уровень вашего образования?', reply_markup=education_markup)\n\n\n@bot.callback_query_handler(func=lambda call: call.data in ['bachelor', 'master', 'xz'])\ndef _set_ed_level(call):\n cursor.execute(\"UPDATE main SET education_level =? WHERE tg_id =?\", (call.data, call.message.chat.id))\n db.commit()\n bio = bot.send_message(call.message.chat.id, \"Напишите вкратце о себе\")\n bot.register_next_step_handler(bio, add_bio)\n\n\n@bot.message_handler(content_types=['photo'])\ndef add_bio(message):\n cursor.execute(\"UPDATE main SET bio =? WHERE tg_id =?\", [str(message.text), str(message.chat.id)])\n db.commit()\n msg = bot.send_message(message.chat.id, \"Отправьте ваши фотографии\")\n bot.register_next_step_handler(msg, download_photos)\n\n\n# @bot.message_handler(content_types=['photo'])\n# def add_profile_photo(message):\n# bot.register_next_step_handler(message, download_photos)\n\n\ndef download_photos(message):\n \"\"\"\n Asks user to upload multiple photos and stores it in directory called res\n :param message:\n :return:\n \"\"\"\n # find the largest photo in the list\n largest_photo = max(message.photo, key=lambda p: p.width * p.height)\n file_id = largest_photo.file_id\n\n file_info = bot.get_file(file_id)\n file_path = file_info.file_path\n file_name = f'{message.chat.id}{random.randint(1, 100)}.jpg'\n downloaded_file = bot.download_file(file_path)\n # save the downloaded file to your local machine\n with open(f'res/{file_name}', 'wb') as f:\n f.write(downloaded_file)\n sleep(2)\n # download_ph = bot.send_message(message.chat.id, \"Фотографии добавлены\")\n # bot.register_next_step_handler(download_ph, registration_finale)\n registration_finale(message)\n\n\ndef get_photos(tg_id=691476720):\n \"\"\"\n Finds all photos from specific telegram user by his tg_id, returns a list of photos\n :param tg_id:\n :return:\n \"\"\"\n prefix = str(tg_id)\n\n # get a list of all files in the directory\n files = os.listdir('res')\n\n # filter the list to only include files that start with the prefix\n filtered_files = [f for f in files if f.startswith(prefix)]\n\n # create the filtered list of files\n photo_list = []\n for file_name in filtered_files:\n with open(os.path.join('res', file_name), 'rb') as f:\n # add each photo to the list of PhotoSize objects\n photo_list.append(telebot.types.InputMediaPhoto(f.read()))\n return photo_list\n\n\ndef send_photos_with_text(message, target_tg_id=691476720, displayed_text=\"zhopa\"):\n \"\"\"\n Sends a message with photos of specific user. User is determined by target_tg_id, displayed_text is just text\n :param message:\n :param target_tg_id:\n :param displayed_text:\n :return:\n \"\"\"\n # set the text displayed underneath\n photo_list = get_photos(target_tg_id)\n print(photo_list)\n try:\n photo_list[0].caption = displayed_text\n bot.send_media_group(chat_id=message.chat.id, media=photo_list)\n except IndexError:\n bot.send_message(message.chat.id, \"Мы не знаем где ваши фото\")\n # use send_media_group() method to send all photos in one message\n\n\ndef registration_finale(message):\n bot.send_message(message.chat.id, \"Вот так выглядит ваша анкета:\")\n\n cursor.execute(\"SELECT tg_id, isu, grade, faculty, major, credentials, bio FROM main WHERE tg_id=?\", [str(message.chat.id)])\n tg_id, isu, course, faculty, program, credentials, bio = cursor.fetchone()\n send_photos_with_text(message, target_tg_id=message.chat.id, displayed_text=f\"{credentials}\\n\"\n f\"{faculty}\\n\"\n f\"{program}\\n\"\n f\"{course}\\n\"\n f\"{bio}\")\n\n\n@bot.message_handler(commands=[\"start\"])\ndef start(message):\n bot.send_message(message.chat.id, \"*написать приветствие*\")\n\n params = (message.chat.id, str(message.chat.username))\n cursor.execute(\"INSERT INTO main (tg_id, tg_username) VALUES (?, ?)\", params)\n\n isu = bot.send_message(message.chat.id, \"Введите ваш номер ИСУ\")\n bot.register_next_step_handler(isu, isu_parse)\n\n\nbot.infinity_polling()\n","repo_name":"ssenichev/ITMOLove","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"39018743815","text":"from . import cart\nfrom flask import redirect, render_template, url_for, flash\nfrom flask_login import login_required, current_user\nfrom .forms import ProductForm, SearchForm\nfrom .models import Product, Cart\nfrom app import db\n\n@cart.route('/')\ndef index():\n title = 'Home'\n products = Product.query.filter(Product.unavailable == False).all()\n return render_template('index.html', title=title, products=products)\n\n# Creating the product routes (eventually set to admin function)\n\n@cart.route('/create-product', methods=['GET', 'POST'])\n@login_required\ndef create_product():\n title = 'Create a Product'\n form = ProductForm()\n products = Product.query.all()\n\n if form.validate_on_submit():\n name = form.name.data\n price = form.price.data\n description = form.description.data\n try:\n new_product = Product(name=name, price=price, description=description, user_id=current_user.id)\n except: # EVENTUALLY add modal for the except (removed unique constraint since product items are now hidden)\n flash(\"This product already exists or was recently deleted! Please try again with another Product Name\", 'danger')\n return redirect(url_for('cart.create_product'))\n else:\n flash(f\"{new_product.name} has been created\", 'secondary')\n\n return redirect(url_for('cart.index'))\n return render_template('create_product.html', title=title, form=form)\n\n# Get A Single product by ID\n@cart.route('/products/')\n@login_required\ndef single_product(product_id):\n product = Product.query.get_or_404(product_id)\n title = \"More information\"\n return render_template('single_product.html', title=title, product=product)\n\n# Get all products that match search\n@cart.route('/search-products', methods=['GET', 'POST'])\ndef search_products():\n title = 'Search Products'\n form = SearchForm()\n products = []\n message = \"\"\n if form.validate_on_submit():\n term = form.search.data\n products = Product.query.filter( ( Product.name.ilike(f'%{term}%')) | ( Product.price.ilike(f'%{term}%')) ).all()\n if not products:\n message = \"There are no products that match your search\"\n return render_template('search_products.html', title=title, products=products, form=form, message=message)\n\n# insert my_products (edit, delete)\n\n\n# Cart routes \n\n# Eventually add edit route\n\n@cart.route('/my-products')\ndef my_products():\n title = 'My Products'\n products = Product.query.filter(Product.user_id == current_user.id, Product.unavailable == False).all()\n return render_template('my_products.html', title=title, products=products)\n\n@cart.route('/remove-product/')\ndef hide_product(product_id):\n product_to_hide = Product.query.get_or_404(product_id)\n product_to_hide.remove()\n flash(f\"{product_to_hide.name} has successfully been removed\",\"success\")\n return redirect(url_for('cart.my_products'))\n\n\n# update the quantity eventually sick \n@cart.route('/add-to-cart/')\n@login_required \ndef add_to_cart(product_id):\n product_to_add = Product.query.get_or_404(product_id)\n if product_to_add:\n user_cart = current_user.my_cart.all()\n product_id = product_to_add.id\n current_user_id = current_user.id\n if product_to_add in user_cart: # update quantity not add\n quantity = product_to_add.quantity + 1\n else:\n quantity = 1\n add_to_cart = Cart(user_id = current_user_id, product_id = product_id, quantity=quantity)\n flash(f\"Product has been added to your cart.\", \"success\")\n return redirect(url_for('cart.index'))\n else:\n flash(\"Sorry, there was an error adding this item to your cart.\", \"danger\")\n return redirect(url_for('cart.index'))\n\n@cart.route('/my-cart-products', methods=['GET', 'POST'])\n@login_required\ndef my_cart_products():\n title = 'My Cart'\n form = SearchForm()\n\n\n products = [Product.query.filter(Product.id == cart.product_id).all()[0] for cart in current_user.my_cart.all()]\n total = sum([float(product.price) for product in products])\n\n duplicate = {}\n cart = []\n\n for p in products:\n if p.id not in duplicate.keys():\n duplicate[p.id] = 1\n cart.append(p)\n else:\n print(\"else\")\n duplicate[p.id] += 1\n\n products = cart\n user_cart = zip(products, cart)\n\n if form.validate_on_submit():\n term = form.search.data\n cart_search = Cart.query.filter(Cart.user_id == current_user.id).all()\n cart = []\n\n duplicate = {}\n\n products = db.session.query(Product).join(Cart).filter(Product.id == Cart.product_id).filter(Product.name.ilike(f'%{term}%')).filter(Cart.user_id == current_user.id).all()\n\n for p in products:\n if p.id not in duplicate.keys():\n cart.append(p)\n count = 0\n for item in cart_search:\n if item.product_id == p.id:\n count += 1\n duplicate[p.id] = count\n\n user_cart = zip(products, cart)\n total = sum([float(product.price) for product in products])\n return render_template('my_cart_products.html', title=title, products=products, total=total, form=form, user_cart=user_cart, duplicate = duplicate)\n\n\n return render_template('my_cart_products.html', title=title, form=form, user_cart=user_cart, total=total, duplicate=duplicate)\n\n\n@cart.route(\"/remove-from-cart/\")\n@login_required\ndef remove_from_cart(product_id):\n title = 'Remove product from cart'\n cart = Cart.query.filter(Cart.product_id == product_id, Cart.user_id == current_user.id).first()\n cart.delete()\n flash('Product has been removed from your cart!', 'success')\n return redirect(url_for('cart.my_cart_products'))\n\n\n@cart.route('/checkout')\n@login_required \ndef checkout():\n my_cart = current_user.my_cart.all()\n for cart in my_cart:\n cart.delete()\n flash(f\"You have successfully checked out! Your cart is now empty.\", \"success\")\n return redirect(url_for('cart.index'))\n","repo_name":"kmehner/Shopping_Flask","sub_path":"app/blueprints/cart/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":6135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"10067156230","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 15 21:28:32 2018\n\n@author: dmytr\n\"\"\"\nimport re\nimport numpy as np\nfrom bs4 import BeautifulSoup as BS\nfrom bs4 import Tag\nfrom shutil import copyfile\n\ndef open_f():\n \"\"\"open tune file\"\"\"\n source = \"fugh.mscx\"\n target=\"fugh_copy.mscx\"\n infile = open(source,\"r\")\n contents = infile.read()\n data = BS(contents, 'xml')\n copyfile(source, target)\n return data\n\ndef save_f(data):\n \"\"\"save modified data\"\"\"\n target=\"fugh_copy.mscx\"\n st1=str(data)\n with open(target,'w') as file1:\n file1.write(st1)\n\ndef find_note(notesb,pitch,tps):\n \"\"\"find a note based on file's pitch and tps\"\"\"\n for ch in notesb:\n for ii in range(1,5,2):\n if ch[ii]==pitch and ch[ii+1]==tps:\n let=ch[0]\n return let\n\ndef find_pitch(notesb,let,number):\n \"\"\"find pitch and tps based on letter\"\"\"\n for ch in notesb:\n if ch[0]==let:\n if number==0:\n pitch=ch[1]\n tps=ch[2]\n else:\n pitch=ch[3]\n tps=ch[4]\n return pitch,tps\n\ndef find_chord(chord,note):\n chor=[]\n chor1=[]\n i=0\n while i1:\n# if counter%2==0:\n# rest=mm.find_all('Rest')\n# bb=BS(\"\",\"lxml\")\n# for ii in range(len(tune[0])):\n# ch=make_chord(0,tune[0][ii][0],thirdV[tune[0][ii][1]][1],thirdV[tune[0][ii][1]][2])\n# bb.append(ch)\n# rest[0].replaceWith(bb)\n# else:\n# rest=mm.find_all('Rest')\n# bb=BS(\"\",\"lxml\")\n# for ii in range(len(tune[1])):\n# ch=make_chord(0,tune[1][ii][0],thirdV[tune[1][ii][1]][1],thirdV[tune[1][ii][1]][2])\n# bb.append(ch)\n# rest[0].replaceWith(bb)\n# counter+=1\n# \n \n","repo_name":"dlotnyk/cia_home","sub_path":"fug.py","file_name":"fug.py","file_ext":"py","file_size_in_byte":9627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"74158562015","text":"import os\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\nimport argparse\nimport multiprocessing as mp\nimport pickle\nimport math\nimport numpy as np\nimport time\nimport json\nfrom collections import defaultdict\nimport tensorflow as tf\nfrom tqdm import tqdm as progress_bar\n\nfrom model import LatentFactorModel, trainingStep\n\ndef params():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--input\", default='data/example.json.gz', type=str,\n help=\"The input data file\")\n parser.add_argument(\"--split\", default=100, type=int,\n help=\"test/train split ratio.\")\n parser.add_argument(\"--factors\", default=5, type=int,\n help=\"number of latent factors to use.\")\n parser.add_argument(\"--epochs\", default=1, type=int,\n help=\"Total number of training epochs to perform.\")\n parser.add_argument(\"--learning-rate\", default=0.1, type=float,\n help=\"Model learning rate starting point.\")\n parser.add_argument(\"--regularization\", default=0.0001, type=float,\n help=\"regularization factor.\")\n\n args = parser.parse_args()\n return args\n\ndef count_entries(pkl_file):\n with open(pkl_file, 'rb') as file_read:\n items = pickle.load(file_read)\n return len(items)\n\ndef collect_ratings_data(pkl_file):\n with open(pkl_file, 'rb') as file_read:\n items = pickle.load(file_read)\n data = []\n for item in items:\n u,i,r = item['reviewerID'], item['asin'], item['overall']\n data.append((u,i,r))\n return data\n\n \nif __name__ == \"__main__\":\n args = params()\n\n data_path = args.input\n data_folder, data_file = os.path.split(data_path)\n data_name = data_file.split('.')[0]\n batches_folder = os.path.join(data_folder, data_name)\n os.makedirs(batches_folder, exist_ok=True) \n num_threads = mp.cpu_count()\n batch_size = 8192\n\n all_files = os.listdir(batches_folder)\n all_files = [ os.path.join(batches_folder, name) for name in all_files ]\n pkl_files = [ name for name in all_files if '.pkl' in name ]\n pkl_files.sort()\n # print(len(pkl_files))\n\n all_files = os.listdir(batches_folder)\n all_files = [ os.path.join(batches_folder, name) for name in all_files ]\n pkl_files = [ name for name in all_files if '.pkl' in name ]\n pkl_files.sort()\n # print(len(pkl_files))\n\n with mp.Pool(num_threads) as p:\n batch_lens = p.map(count_entries, pkl_files)\n dataset_len = sum(batch_lens)\n # print(dataset_len)\n\n start_time = time.time()\n with mp.Pool(num_threads) as p:\n datasets = p.map(collect_ratings_data, pkl_files)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n # print(len(datasets))\n\n dataset_all = []\n for dataset in datasets:\n dataset_all.extend(dataset)\n # len(dataset_all)\n\n test_size = math.floor(len(dataset_all) / args.split)\n\n dataset_train = dataset_all[:-test_size]\n dataset_test = dataset_all[-test_size:]\n assert len(dataset_train)+len(dataset_test) == len(dataset_all)\n\n trainRatings = [r[2] for r in dataset_train]\n globalAverage = np.mean(trainRatings)\n print(globalAverage)\n\n for idx, item in enumerate(dataset_train):\n dataset_train[idx] = item[0], item[1], item[2] - globalAverage\n for idx, item in enumerate(dataset_test):\n dataset_test[idx] = item[0], item[1], item[2] - globalAverage\n\n\n ratingsPerUser = defaultdict(list)\n ratingsPerItem = defaultdict(list)\n userIDs = {}\n itemIDs = {}\n for u,i,r in dataset_train:\n ratingsPerUser[u].append((i,r))\n ratingsPerItem[i].append((u,r))\n if not u in userIDs: userIDs[u] = len(userIDs)\n if not i in itemIDs: itemIDs[i] = len(itemIDs)\n # with open('cache.pkl', 'wb') as cache_file:\n # pickle.dump((ratingsPerUser, ratingsPerItem, userIDs, itemIDs), cache_file)\n # with open('cache.pkl', 'rb') as cache_file:\n # ratingsPerUser, ratingsPerItem, userIDs, itemIDs = pickle.load(cache_file)\n\n mu = globalAverage\n\n u_test = []\n i_test = []\n r_actual = []\n for u,i,r in progress_bar(dataset_test, total=len(dataset_test)):\n if u not in userIDs or i not in itemIDs:\n continue\n else:\n u_test.append(userIDs[u])\n i_test.append(itemIDs[i])\n r_actual.append(r)\n u_test = np.array(u_test)\n i_test = np.array(i_test)\n r_actual = np.array(r_actual)\n\n optimizer = tf.keras.optimizers.Adam(args.learning_rate)\n model = LatentFactorModel(mu, args.factors, args.regularization, userIDs, itemIDs)\n\n # 10 iterations of gradient descent\n iterations = args.epochs\n pbar = progress_bar(range(iterations), total=iterations)\n\n results = []\n for i in pbar:\n obj = trainingStep(dataset_train, model, optimizer, userIDs, itemIDs)\n \n r_pred = model.predictSample(u_test, i_test).numpy()\n mse = np.mean(np.square(r_pred-r_actual))\n \n result = {'obj': obj, 'test:': mse}\n results.append(result)\n pbar.set_postfix(result)\n \n # print(\"iteration \" + str(i) + \", objective = \" + str(obj))\n print(\"objective = \" + str(obj))\n\n r_pred = model.predictSample(u_test, i_test).numpy()\n mse = np.mean(np.square(r_pred-r_actual))\n print(mse)\n\n baseline = np.mean(np.square( r_actual - globalAverage ))\n print(baseline)\n\n results_final = {\n 'data_path': data_path,\n 'batches_folder': batches_folder,\n 'batch_size': batch_size,\n 'args': vars(args),\n 'results': results,\n 'mse': mse,\n 'baseline': baseline,\n 'dataset_len': len(datasets),\n }\n\n results_folder = 'results'\n os.makedirs(results_folder, exist_ok=True) \n results_file = os.path.join(results_folder, data_name+'.pkl')\n with open(results_file, 'wb') as fp:\n pickle.dump(results_final, fp)","repo_name":"curtisrlee/cse258-assignment2","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"42840392020","text":"import bot_vision as bv # build LevelLogger of BotView\nimport os # open/save files\nimport re # filtering files by name\nimport pickle # import macro_dd\nimport numpy as np\nfrom PIL import Image\nimport sys # flush stdout\n\nimport csv # log results to file\n\nimport cv2 # template matching (can't just compare directly because of a few animated elements)\n\nmistake_threshold = 0.99\nthreshold = 0.999\n\t# want fewer false positives (hence really high threshold)\n\t# but since there are some animations that can cause a mismatch (moving cursor, \"bang\" effect)\n\t# as well as the funkiness of floats\n\t# we don't have a solid 1.0 as the threshold\n\t# 0.999 *does* recognize the different sandbag configurations though, which is good\n\t#\n\t# for mistake templates, we bump down to 0.99\n\t# because for some reason they wouldn't match 1.0 or even 0.999+\n\t# (despite there not being animations in the templated area)\nhist_dir = 'history'\nout_dir = 'outputs'\ndebug = False\n\nmax_index = 1 # index of max_value for tuple returned by cv2.minMaxLoc()\n\nwindow_class_title = 'PPSSPPWnd'\n\nkey_fmt = 'area_{0}' # to be used in logging\nhistory_file_fmt = '{0}-{1}.bmp' # {0} = key_fmt, {1} = index_num of screenshot\n\nindex_finder = re.compile(r'-(\\d+)\\.')\nmarker_indicator = 'marker'\nmarker_fmt = 'marker-{0}.png'\nmarker_dir = 'markers'\n\nmistake_indicator = 'macro_mistake'\n\ncsv_fp = os.path.join(hist_dir, 'results.csv')\n\nmacros_dd = pickle.load(open(os.path.join(hist_dir, \"macro_dd.p\"), mode = 'rb'))\n\nclass LevelLogger(bv.BotView):\n\t\"\"\"\n\tA bit \"dumber\" than EvaluatorBot\n\tWill continually enter the level on different seeds and\n\texplore the level in order to expose all enemy locations.\n\tIt will compare the current screens with screen it's seen before\n\t(and will assign the screen a new index if it's new).\n\tIt will log the combinations of screens it sees into a CSV.\n\tWill keep going until it receives a KeyboardInterrupt.\n\t\"\"\"\n\tdef __init__(self, window, macros, threshold = threshold, vjoy_device_num = 1, hist_dir = hist_dir):\n\t\tself.threshold = threshold\n\t\t# self.output_dir = output_dir\n\t\tself.hist_dir = hist_dir\n\t\tself.num_iter = 0\n\t\tself.area_keys = [key_fmt.format(n) for n in range(2,6)] #areas 2-5\n\t\tself.valid_keyset = set(self.area_keys)\n\t\tself.next_area_values = self.init_next_area_values() # \"Area X\" : (what would be the next unseen area's index)\n\t\tself.seen_areas = {}\n\t\tself.templates = self.init_templates()\n\t\t# self.mistake_templates = self.init_mistake_templates()\n\t\tself.marker_templates = self.init_verification_dict()\n\t\tself.made_mistake = False\n\t\tsuper().__init__(window, macros, vjoy_device_num)\n\n\tdef refresh(self):\n\t\t\"\"\" Prepare for next iteration. \"\"\"\n\t\tself.seen_areas = {} # forget what we've seen\n\t\tself.made_mistake = False\n\n\n\tdef init_verification_dict(self):\n\t\t\"\"\" Returns a dict from marker_fnames (*not* paths!) to cv2 templates.\"\"\"\n\t\tfpath = os.path.join(self.hist_dir, marker_dir)\n\t\treturn {fn.lower():cv2.imread(os.path.join(fpath, fn)) for fn in os.listdir(fpath)}\n\t\t# marker_fpaths = [os.path.join(self.hist_dir, fn) for fn in os.listdir(self.hist_dir) if marker_indicator in fn]\n\t\t# return {fp:cv2.imread(fp) for fp in marker_fpaths}\n\n\n\n\tdef run_macro(self, macro_label, verify = True):\n\t\t\"\"\" Run specified macro dictionary.\n\n\t\tIf verify is set to True, will see whether there is a match with the marker associated with the macro label\n\t\tas stored in marker_templates. \n\t\tIt determines which template to use by seeing whether macro_label is in the template's fpath\n\t\taccording to the format described in marker_fmt.\"\"\"\n\t\tsuper().run_macro(macro_label)\n\t\t# for fun\n\t\t# if macro_label == 'advance_rng_seed':\n\t\tif macro_label == 'enter_briefing':\n\t\t\tself.num_iter += 1\n\t\t\tprint(\"\\nStarting Iteration #{0}...\".format(self.num_iter))\n\t\tif verify:\n\t\t\tkey = marker_fmt.format(macro_label)\n\t\t\ttry:\n\t\t\t\tself.update_view() # will need to compare with template\n\t\t\t\tprint(\"Verifying macro results ... \", end = '')\n\t\t\t\tsys.stdout.flush()\n\t\t\t\ttemplate = self.marker_templates[key]\n\t\t\t\tif not self.is_matching_template(template, threshold = mistake_threshold):\n\t\t\t\t\tself.made_mistake = True\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Looks OK to me!\")\n\t\t\texcept KeyError:\n\t\t\t\tprint(\"No valid marker template found. Looking for {0}\".format(key))\n\n\n\n\n\tdef init_templates(self):\n\t\t\"\"\"Load in templates for bot to use.\"\"\"\n\t\ttemplates = {}\n\t\t\t# get list of filepaths to open with cv2\n\t\thist_files = [os.path.join(self.hist_dir, fn) for fn in os.listdir(self.hist_dir)]\n\t\t\t# load files into memory\n\t\tfor key in self.valid_keyset:\n\t\t\tcur_fns = [fn for fn in hist_files if key in fn]\n\t\t\ttemplates[key] = {fn: cv2.imread(fn) for fn in cur_fns}\n\t\t\t\t# can use key to get to dict of just the relevant templates\n\t\t\t\t# within each dict, have fn -> cv2 template\n\t\treturn templates\n\n\n\t# def init_mistake_templates(self):\n\t# \tmistake_files = [os.path.join(self.hist_dir, fn) for fn in os.listdir(self.hist_dir) if mistake_indicator in fn]\n\t# \treturn {fn: cv2.imread(fn) for fn in mistake_files}\n\n\tdef log_to_csv(self):\n\t\t\"\"\" Log what the bot has seen into the filepath indicated by csv_fp. \"\"\"\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\twith open(csv_fp, mode = 'x', newline = '') as f:\n\t\t\t\t\twriter = csv.DictWriter(f, fieldnames = self.area_keys)\n\t\t\t\t\twriter.writeheader()\n\t\t\t\t\twriter.writerow(self.seen_areas)\n\t\t\t\tbreak\n\t\t\texcept PermissionError: # CSV is currently open\n\t\t\t\tinput(\"Output CSV currently open! Close and press Enter to retry.\\n\")\n\t\t\t\tcontinue\n\t\t\texcept FileExistsError: # don't (re)write header\n\t\t\t\twith open(csv_fp, mode = 'a', newline = '') as f:\n\t\t\t\t\twriter = csv.DictWriter(f, fieldnames = self.area_keys)\n\t\t\t\t\twriter.writerow(self.seen_areas)\n\t\t\t\tbreak\n\n\n\n\tdef init_next_area_values(self):\n\t\t\"\"\" Based on the filenames in hist_dir, determine the next available open index for each key. \"\"\"\n\t\t# count how many contain the keyname; that's the next index\n\t\td = {}\n\t\tfor key in self.valid_keyset:\n\t\t\td[key] = len([fn for fn in os.listdir(self.hist_dir) if key in fn])\n\t\treturn d\n\n\tdef is_matching_template(self, template, threshold = None):\n\t\t\"\"\" Sees if the maximum value in a cv2.matchTemplate is at least threshold. Default is self.threshold\"\"\"\n\t\tif threshold is None:\n\t\t\tthreshold = self.threshold # can't seem to make this default in function definition\n\t\ttemp_res = cv2.matchTemplate(self.view, template, cv2.TM_CCOEFF_NORMED)\n\t\tmax_val = cv2.minMaxLoc(temp_res)[max_index]\n\t\treturn max_val >= threshold\n\n\tdef match_templates(self, templates):\n\t\t\"\"\" Returns a dictionary of (max value of cv2.matchTemplate(self.view, template):fn) for each template in templates. \"\"\"\n\t\treturn {cv2.minMaxLoc(cv2.matchTemplate(self.view, template, cv2.TM_CCOEFF_NORMED))[max_index]:fn \\\n\t\t\t\t\t\tfor (fn, template) in templates.items()}\n\n\tdef evaluate_screen(self, key_str):\n\t\t\"\"\"\n\t\tLooks at screen and updates values accordingly.\n\n\t\tIf the screen hasn't been seen before (i.e. it doesn't match any templates in hist_dir),\n\t\tit adds the screenshot to the directory with a new index and adds it as a new template.\n\t\tIn any case, self.seen_areas is updated with key_str:index_of_image\n\t\t\"\"\"\n\t\t# # first see if our macro messed up\n\t\t# # (a bit ugly having two nearly identical loops...)\n\t\t# for (fn, mistake_template) in self.mistake_templates.items():\n\t\t# \tif self.is_matching_template(mistake_template):\n\t\t# \t\tself.made_mistake = True\n\t\t# \t\treturn\n\t\t# for (fn, template) in self.templates[key_str].items():\n\t\t# \tif self.is_matching_template(template, threshold = 0.999): # \n\t\t# \t\tindex = index_finder.findall(fn)[0] # get index from filename\n\t\t# \t\tself.seen_areas[key_str] = index\n\t\t# \t\treturn\n\t\tmax_vals_dict = self.match_templates(self.templates[key_str])\n\n\t\tmax_val = max(max_vals_dict.keys(), default = -1) # default only if empty dictionary\n\t\t# debug but slow...\n\t\tif debug:\n\t\t\tfiltered_dict = {k:v for (k,v) in max_vals_dict.items() if k == max_val}\n\t\t\ttry:\n\t\t\t\tassert len(filtered_dict) == 1 # we expect that no two templates both have max_val\n\t\t\texcept AssertionError: # more than one value had the same max_val\n\t\t\t\tprint(\"More than one template had the same match value. Filenames: {0}\"\\\n\t\t\t\t\t\t\t.format(filtered_dict.values())) # I guess, at least be aware of it?\n\t\t\t\t# if it actually happens, may want to add flag in dict and write to CSV\n\n\t\tif max_val >= self.threshold: # match existing image\n\t\t\tprint(\"Found a match. max_val = {0}, filename = {1}\".format(max_val, max_vals_dict[max_val]))\n\t\t\tindex = index_finder.findall(max_vals_dict[max_val])[0]\n\t\t\tself.seen_areas[key_str] = index\n\t\t\treturn\n\t\telse: # new instance\n\t\t\tcur_max_index = self.next_area_values[key_str]\n\t\t\tfp_newimg = os.path.join(self.hist_dir, history_file_fmt.format(key_str, cur_max_index))\n\t\t\tprint(\"New instance. Saving to {0}.\".format(fp_newimg))\n\t\t\tself.save_view_as_image(fp_newimg) # save image to history for future runs (and visual inspection)\n\t\t\t\t# save current view as new template directly (without opening newly saved image)\n\t\t\tself.templates[key_str][fp_newimg] = self.view # already in BGR order, can add directly to templates\n\t\t\tself.seen_areas[key_str] = cur_max_index\n\t\t\tself.next_area_values[key_str] += 1 # update index\n\n\n\n\n\n\tdef run(self):\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\twhile True:\n\t\t\t\t\tself.refresh() # initialize values for next run (including reseting mistake flag)\n\t\t\t\t\tself.run_macro('enter_briefing', verify = False)\n\t\t\t\t\tself.run_macro('enter_mission', verify = True)\n\n\t\t\t\t\t# explore each area and evaluate area before exploring next\n\t\t\t\t\tfor x in [5,4,2,3]: # order dependent on how macros were recorded\n\t\t\t\t\t\tkey_str = key_fmt.format(x)\n\t\t\t\t\t\tif key_str not in self.valid_keyset:\n\t\t\t\t\t\t\traise ValueError(\"Invalid key_str made! key_str = {0}, \\\n\t\t\t\t\t\t\t\tself.valid_keyset = {1}\".format(key_str, self.valid_keyset))\n\t\t\t\t\t\tself.run_macro('explore_{0}'.format(key_str), verify = True)\n\t\t\t\t\t\tif self.made_mistake:\n\t\t\t\t\t\t\tprint(\"Whoops! Macro didn't execute properly. Retrying from start...\")\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tself.update_view()\n\t\t\t\t\t\tself.evaluate_screen(key_str)\n\n\t\t\t\t\t# out of exploration loop\n\t\t\t\t\tif self.made_mistake:\n\t\t\t\t\t\tcontinue # don't log (and don't advance rng)\n\t\t\t\t\t\t\n\t\t\t\t\tself.log_to_csv() # log to file if there wasn't a mistake\n\t\t\t\t\tself.run_macro('advance_rng_seed', verify = False)\n\t\t\t\t\t# ...and on we go!\n\t\t\texcept KeyboardInterrupt:\n\t\t\t\tinput(\"{0}{1}\".format(\"Send another KeyboardInterrupt to exit the program.\\n\",\n\t\t\t\t\t\"Otherwise, press Enter to continue.\\n\"))\n\t\t\t\tcontinue","repo_name":"dkhachatrian/xinput-pybot","sub_path":"example_bots/level_logger.py","file_name":"level_logger.py","file_ext":"py","file_size_in_byte":10361,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"28037862537","text":"\"\"\"Users controllers module.\"\"\"\nfrom fastapi import HTTPException\nfrom sqlalchemy.exc import IntegrityError\n\nfrom app.users.exceptions.role_exceptions import RoleNotFoundException\nfrom app.users.services import RoleService\n\n\nclass RoleController:\n \"\"\"RoleController class\"\"\"\n @staticmethod\n def create_role(role_type: str):\n \"\"\"create_role function\"\"\"\n try:\n role = RoleService.create_role(role_type)\n return role\n except IntegrityError as exc:\n raise HTTPException(status_code=400, detail=f\"Role of this type {role_type} already exists.\") from exc\n except Exception as e:\n raise HTTPException(status_code=500, detail=str(e)) from e\n\n @staticmethod\n def read_role_by_id(role_id: str):\n \"\"\"read_role_by_id function\"\"\"\n role = RoleService.read_role_by_id(role_id)\n if role:\n return role\n raise HTTPException(status_code=400, detail=f\"Role with provided id {role_id} does not exist\")\n\n @staticmethod\n def read_role_by_type(role_type: str):\n \"\"\"read_role_by_type function\"\"\"\n role = RoleService.read_role_by_type(role_type)\n if role:\n return role\n raise HTTPException(status_code=400, detail=f\"Role with provided type {role_type} does not exist\")\n\n @staticmethod\n def read_all_roles():\n \"\"\"read_all_roles function\"\"\"\n roles = RoleService.read_all_roles()\n return roles\n\n @staticmethod\n def delete_role_by_id(role_id: str):\n \"\"\"delete_role_by_id function\"\"\"\n try:\n RoleService.delete_role_by_id(role_id)\n return {\"message\": f\"Role with provided id, {role_id} has been deleted.\"}\n except RoleNotFoundException as e:\n raise HTTPException(status_code=e.code, detail=e.message) from e\n except Exception as e:\n raise HTTPException(status_code=400, detail=str(e)) from e\n","repo_name":"ivantot/ITBC_Final_project","sub_path":"app/users/controllers/role_controller.py","file_name":"role_controller.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"22284353345","text":"#!/usr/bin/python3\n\"\"\"Defines an island perimeter measuring function.\"\"\"\n\n\ndef island_perimeter(grid):\n \"\"\"Return the perimiter of an island.\n\n The grid represents water by 0 and land by 1.\n\n Args:\n grid (list): A list of list of integers representing an island.\n Returns:\n The perimeter of the island defined in grid.\n \"\"\"\n\n island = 0\n neighbor = 0\n\n for y in range(len(grid)):\n for x in range(len(grid[y])):\n if grid[y][x] == 1:\n island += 1\n if x < len(grid[y])-1 and grid[y][x+1] == 1:\n neighbor = neighbor + 1\n if y < len(grid ) -1 and grid[y+1][x] == 1:\n neighbor = neighbor + 1\n return island*4 - 2*neighbor\n","repo_name":"silvioukoth/alx-low_level_programming","sub_path":"0x1C-makefiles/5-island_perimeter.py","file_name":"5-island_perimeter.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"23908804174","text":"# https://www.acmicpc.net/problem/2307\n\nimport sys, heapq\nfrom collections import defaultdict\n\ninput = lambda: sys.stdin.readline().rstrip()\nINF = float(\"inf\")\nn, m = map(int, input().split())\ngraph = defaultdict(list)\nedges = []\nfor _ in range(m):\n a, b, t = map(int, input().split())\n graph[a].append((b, t))\n graph[b].append((a, t))\n edges.append((a, b))\n\n\ndef dijkstra(x, y):\n heap = []\n heapq.heappush(heap, (0, 1))\n distance = [INF] * (n + 1)\n distance[1] = 0\n while heap:\n dist, now = heapq.heappop(heap)\n\n if dist > distance[now]:\n continue\n\n for next, d in graph[now]:\n if now == x and next == y:\n continue\n if now == y and next == x:\n continue\n cost = dist + d\n if cost < distance[next]:\n distance[next] = cost\n heapq.heappush(heap, (cost, next))\n return distance[n]\n\n\ndef solve():\n answer = 0\n for x, y in edges:\n escape_time = dijkstra(x, y)\n if escape_time == INF:\n print(-1)\n return\n answer = max(answer, escape_time)\n\n print(answer - dijkstra(0, 0))\n\n\nsolve()\n","repo_name":"h-spear/problem-solving-python","sub_path":"baekjoon/shortest_path/road_check.py","file_name":"road_check.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"34858586364","text":"class Solution(object):\n def isInterleave(self, s1, s2, s3):\n \"\"\"\n :type s1: str\n :type s2: str\n :type s3: str\n :rtype: bool\n \"\"\"\n l1, l2, l3 = len(s1), len(s2), len(s3)\n # return False if the length of s1 and s2 not equal to s3\n if l1 + l2 != l3:\n \treturn False\n # Initialize the dp table with False\n dp = [[False for _ in xrange(l2 + 1)] for _ in xrange(l1 + 1)]\n for i in xrange(l1 + 1):\n \tfor j in xrange(l2 + 1):\n \t\t# If both s1 and s2 are empty string\n \t\tif i == 0 and j == 0:\n \t\t\tdp[i][j] = True\n \t\t# If s1 is empty\n \t\telif i == 0 and s2[j - 1] == s3[j - 1]:\n \t\t\tdp[i][j] = dp[i][j - 1]\n \t\t# If s2 is empty\n \t\telif j == 0 and s1[i - 1] == s3[i - 1]:\n \t\t\tdp[i][j] = dp[i - 1][j]\n \t\t# If the current character in s3 only matches s1\n \t\telif s1[i - 1] == s3[i + j - 1] and s2[j - 1] != s3[i + j - 1]:\n \t\t\tdp[i][j] = dp[i - 1][j]\n \t\t# If the current character in s3 only matches s2\n \t\telif s1[j - 1] != s3[i + j - 1] and s2[j - 1] == s3[i + j - 1]:\n \t\t\tdp[i][j] = dp[i][j - 1]\n \t\t# If the current character in s3 matches both of s1 and s2\n \t\telif s1[i - 1] == s3[i + j - 1] and s2[j - 1] == s3[i + j - 1]:\n \t\t\tdp[i][j] = dp[i - 1][j] or dp[i][j - 1]\n\n return dp[-1][-1]\n","repo_name":"JoshuaW1990/leetcode-session1","sub_path":"leetcode97.py","file_name":"leetcode97.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"1725982793","text":"from purpledefrag import CvarDict, Map, MapList, BunnyResponse\nfrom redis import Redis\nfrom hashlib import sha256\n\n\nclass GentleReminder(Map):\n\tdef match(self, request):\n\t\tif request.command.startswith('!') and \\\n\t\t\t\"reminder\" in self.routes:\n\t\t\treturn self.routes[\"reminder\"], None\n\n\t\treturn Map.match(self, request)\n\n\tdef getRecognized(self):\n\t\tk = Map.getRecognized(self)\n\t\treturn k - set((\"reminder\",))\n\ndef initCDict(pid):\n\tglobal cvars\n\tcvars = CvarDict(\"/openarena:\" + pid)\n\ncvars = None\nroutes = GentleReminder()\nmaps = MapList()\ndb = Redis(host = \"localhost\", port = 6379, db = 0)\nsalt = sha256(\"your salt here\")\n","repo_name":"bryant/purpledefrag","sub_path":"test/lib/python2.6/site-packages/purpledefrag/app/g.py","file_name":"g.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"33"} +{"seq_id":"8822918255","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 1 10:05:40 2021\r\n\r\n@author: Annette Malapally\r\n\"\"\"\r\n\r\nimport pandas as pd\r\npd.options.mode.chained_assignment = None # default='warn'\r\nimport nltk\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem.snowball import SnowballStemmer\r\nimport re\r\nimport spacy\r\n\r\nnlp = spacy.load(\"en_core_web_sm\")\r\n\r\n# Removes non-English tweets\r\ndef only_english (df):\r\n # Remove non-English tweets\r\n df = df[df['language'] == 'en']\r\n \r\n # Reset index\r\n df = df.reset_index(drop=True)\r\n\r\n return df\r\n\r\n# Recodes special characters\r\ndef recode_chars (df):\r\n # Recode special characters\r\n df['text'] = df['text'] .str.replace('&','&', regex = True)\r\n \r\n return df\r\n\r\n# Finds mentions of \"than\"\r\ndef contains_than(text):\r\n if (re.search(r\"\\sthan\\s\", text)):\r\n return 'than'\r\n elif (re.search(r\"\\sThan\\s\", text)):\r\n return 'than'\r\n if (re.search(r\"\\sTHAN\\s\", text)):\r\n return 'than'\r\n else: \r\n return 'NaN'\r\n \r\n# Makes sure that each tweet contains the word \"than\"\r\ndef tweets_with_than(df):\r\n df['than'] = df['text'].apply(contains_than)\r\n df = df[df['than'] == \"than\"]\r\n df = df.drop(['than'], axis = 1)\r\n \r\n # Reset index\r\n df = df.reset_index(drop=True)\r\n return df\r\n\r\n# Removes urls from tweets\r\ndef remove_urls(df, column):\r\n # Remove URLs\r\n df[column] = df[column].str.replace('http\\S+|www.\\S+', '', case=False, regex = True)\r\n \r\n return df\r\n\r\n# Removes mentions from tweets\r\ndef remove_mentions(df, column):\r\n text = df[column]\r\n \r\n # Check if given column is text or tokens\r\n # If it is tokens\r\n if isinstance(text[0], list):\r\n # Iterate over rows\r\n for i in range(len(text)):\r\n # Remove mentions\r\n text_row = [re.sub('@[A-Za-z0-9_]+', '', element) for element in text[i]]\r\n \r\n # Remove empty strings\r\n text_row = [element for element in text_row if element != '']\r\n\r\n # Save row\r\n df[column].iloc[i] = text_row\r\n \r\n # If it is text\r\n else:\r\n # Remove mentions\r\n df[column] = df[column].str.replace('@[A-Za-z0-9_]+', '', case=False, regex = True)\r\n \r\n return df\r\n\r\n# Make all words lower case\r\ndef lower_case(df, column):\r\n df[column] = df[column].map(lambda x: list(map(str.lower, x)))\r\n return df\r\n\r\n# Splits tweets into sentences\r\ndef split_sentences(df): \r\n # Split tweets into sentences\r\n df['sentences'] = df.apply(lambda row: nltk.tokenize.sent_tokenize(row['text cleaned']), axis=1)\r\n \r\n # Make sentences lower case\r\n df = lower_case(df, 'sentences')\r\n \r\n return df\r\n\r\n# Drops duplicate tweets\r\ndef drop_duplicates (df, column = 'text cleaned'):\r\n # Remove tweets with duplicate text\r\n df = df.drop_duplicates(subset = column, keep= 'first', inplace = False)\r\n print(' Dropped duplicate tweets.')\r\n \r\n # Reset index\r\n df = df.reset_index(drop=True)\r\n \r\n return df\r\n\r\n# Remove stop words, except 'than'\r\n# Define stopwords\r\nstop = set(stopwords.words(\"english\"))\r\nstop_wothan = [item for item in stop if item != 'than']\r\n\r\n# Remove stop words in text\r\ndef remove_stopwords(df, column, keepthan):\r\n if keepthan == True:\r\n stopwords = stop_wothan\r\n elif keepthan == False:\r\n stopwords = stop\r\n df[column] = df[column].apply(lambda x: ' '.join([word for word in x.split() if word not in (stopwords)]))\r\n return df\r\n\r\n# Remove punctuation\r\ndef remove_punctuation(df, column):\r\n df[column] = df[column].str.replace('[^\\w\\s]','', regex = True)\r\n return df\r\n\r\n# Tokenize tweets\r\ndef tokenize_tweets(df, text_column, target_column):\r\n # Tokenize tweets\r\n tokens = df[text_column].apply(lambda x: nlp.tokenizer(x))\r\n df[target_column] = [[token for token in tweet if token.pos_ == \"NOUN\" or token.pos_ == \"ADJ\" or token.pos_ == \"VERB\"] for tweet in tokens]\r\n df[target_column] = [[token.text for token in tweet if token.text[0] != ' '] for tweet in tokens]\r\n \r\n return df\r\n\r\n# Lemmatize tweets\r\ndef lemmatize_tweets(df, column):\r\n df[column] = df[column].apply(lambda row: \" \".join([w.lemma_ for w in nlp(row)]))\r\n return df\r\n\r\ndef stem_tweets(df, column):\r\n stemmer = SnowballStemmer(language = 'english')\r\n df[column] = df[column].apply(lambda row: \" \".join([stemmer.stem(w.text) for w in nlp(row)]))\r\n return df\r\n","repo_name":"annettemala/tweetinginequality","sub_path":"Python scripts/prepare_tweets.py","file_name":"prepare_tweets.py","file_ext":"py","file_size_in_byte":4416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"17610849746","text":"import requests\nimport os\nimport sys\nimport time\nimport re\nimport random\nfrom fake_useragent import UserAgent\nfrom log import logger\n\n\nclass DouYin:\n \"\"\"\n 抓取抖音分享链接里的用户信息和视频信息\n \"\"\"\n user_info_url = 'https://www.iesdouyin.com/web/api/v2/user/info/?' # 用户信息\n video_list_url = 'https://www.iesdouyin.com/web/api/v2/aweme/post/?' # 用户视频列表\n video_url = 'https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?' # 单个视频信息\n\n def __init__(self, user_share_link, download_dir=None):\n self.user_share_link = user_share_link\n self.sec_uid = self.get_sec_uid()\n self.user_info = self.get_user_info()\n\n self.nickname = self.user_info[\"nickname\"]\n self.unique_id = self.user_info[\"unique_id\"]\n\n '''设置下载目录'''\n logger.info(f'nickname: {self.nickname}, unique_id: {self.unique_id}')\n if not download_dir:\n path = f'{self.nickname}_{self.unique_id}'\n self.set_download_dir(os.path.join(r\"/Users/liu/Downloads\", path))\n else:\n self.set_download_dir(download_dir)\n\n def set_download_dir(self, path):\n if not os.path.exists(path=path):\n os.mkdir(path=path)\n os.chdir(path=path)\n\n @property\n def headers(self):\n return {\"user-agent\": UserAgent(verify_ssl=False).random}\n\n def get_sec_uid(self):\n short_url = re.findall('[a-z]+://[\\S]+', self.user_share_link, re.I | re.M)[0]\n start_page = requests.get(url=short_url, headers=self.headers, allow_redirects=False)\n location = start_page.headers['location']\n return re.findall('(?<=sec_uid=)[a-zA-Z0-9_-]+', location)[0]\n\n def get_user_info(self):\n params = {'sec_uid': self.sec_uid}\n data = requests.get(DouYin.user_info_url, params=params, headers=self.headers).json()\n return data['user_info']\n\n @property\n def cursor_list(self):\n start_date = '2017-01-01 00:00:01' # 抓取开始时间\n day_gap = 15 # 间隔时间\n one_day = 86400 # 60 * 60 * 24\n start = int(time.mktime(time.strptime(start_date, \"%Y-%m-%d %H:%M:%S\")))\n ct = time.time()\n cl = []\n while start < ct:\n end = start + one_day * day_gap\n cl.append((start, end))\n start = end\n return cl\n\n def get_aweme_param_list(self):\n return [\n {\n 'sec_uid': self.sec_uid,\n 'count': 100,\n 'min_cursor': t1 * 1000,\n 'max_cursor': t2 * 1000,\n 'aid': 1128,\n '_signature': 'PtCNCgAAXljWCq93QOKsFT7QjR'\n }\n for t1, t2 in self.cursor_list\n ]\n\n @staticmethod\n def gtime(ts):\n ts = int(str(ts)[:-3])\n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(ts))\n\n def get_user_video_list(self):\n \"\"\"获取用户视频列表\"\"\"\n v_sum = 0\n for p in self.get_aweme_param_list():\n data = requests.get(DouYin.video_list_url, params=p, headers=self.headers).json()\n aweme_num = len(data['aweme_list'])\n\n if aweme_num > 0:\n v_sum += aweme_num\n logger.info(f\"video_num: {aweme_num}, \"\n f\"min_cursor: {self.gtime(p.get('min_cursor'))}, \"\n f\"max_cursor: {self.gtime(p.get('max_cursor'))}, param: {p}\")\n\n # time.sleep(random.random())\n for i in data['aweme_list']:\n aweme_id = i['aweme_id']\n video_url = i['video']['play_addr']['url_list'][0]\n uri = i['video']['play_addr']['uri']\n logger.info(f'video_uri: {uri}')\n self.download_video(aweme_id, video_url)\n\n logger.info(f'aweme_count: {self.user_info[\"aweme_count\"]}, download_count: {v_sum}, nickname: {self.nickname}')\n\n def download_video(self, aweme_id, video_url):\n \"\"\"视频下载\"\"\"\n start = time.time()\n logger.info(' {} ===>downloading'.format(aweme_id))\n with open(aweme_id + '.mp4', 'wb') as v:\n try:\n v.write(requests.get(url=video_url, headers=self.headers).content)\n end = time.time()\n cost = end - start\n logger.info(f' {aweme_id} ===>downloaded ===>cost {round(cost, 3)}s')\n except Exception as e:\n logger.error(f'download error: {e}')\n\n def get_one_video(self, aweme_id):\n \"\"\"获取单个视频信息\"\"\"\n pass\n\n def upload_video(self):\n \"\"\"视频上传\"\"\"\n pass\n\n\nif __name__ == '__main__':\n # share_url_list = [\n # 'https://v.douyin.com/YWdUKqk/', # nickname: 勐巴娜西乐团·德宏五兄弟\n # 'https://v.douyin.com/YhUn3rq/', # nickname: 谢二妹\n # ]\n\n share_url_list = sys.argv[1:]\n for share_url in share_url_list:\n d = DouYin(share_url)\n d.get_user_video_list()\n","repo_name":"liuyaming123/douyin","sub_path":"douyin.py","file_name":"douyin.py","file_ext":"py","file_size_in_byte":5010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"36150830083","text":"#!/usr/bin/env python3\n\nimport shutil\nimport os\nfrom typing import List\nfrom pathlib import Path\n\nfrom . import specification as spec\nfrom . import documentation_to_specification\nfrom .. import logger\nfrom ..parser import Parser\n\n\nclass Generator:\n def __init__(\n self,\n parsers: List[Parser],\n template_folder: Path,\n pattern: str,\n output: str,\n ark_version: str,\n root: str,\n ):\n self.template_folder = template_folder\n self.templates = {\n file.name: file.read_text(\"utf-8\") for file in template_folder.glob(pattern)\n }\n self.output_path = Path(output)\n self.version = ark_version\n self.output_path_ver = self.output_path / self.version\n self.root = root if root and root[-1] != \"/\" else root[:-1]\n self.list = spec.FileList([])\n self._create_files_list(parsers)\n\n def _create_files_list(self, parsers: List[Parser]):\n registered = {}\n\n for p in parsers:\n functions = []\n for doc in p.extract_documentation():\n functions.append(documentation_to_specification(doc))\n\n base = os.path.splitext(os.path.basename(p.filename))[0]\n if base in registered:\n registered[base].functions += functions\n else:\n registered[base] = spec.File(base, functions)\n self.list.files.append(registered[base])\n\n self.list.files = sorted(\n [f for f in self.list.files if len(f.functions)], key=lambda file: file.path\n )\n\n def generate_index(self):\n raise NotImplementedError\n\n def generate_one(self, path: str, functions: List[spec.Function]):\n raise NotImplementedError\n\n def __call__(self):\n if not self.output_path_ver.exists():\n self.output_path_ver.mkdir(parents=True)\n else:\n shutil.rmtree(str(self.output_path_ver))\n return self.__call__()\n\n self.generate_index()\n\n for file in self.list.files:\n logger.info(\n f\"Generating {file.path} documentation... found {len(file.functions)} functions\"\n )\n\n self.generate_one(file.path, file.functions)\n","repo_name":"ArkScript-lang/ArkDoc","sub_path":"arkdoc/generator/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"6615168081","text":"#!/usr/bin/env python3\n#3.30 SNMP 서비스 구동 점검\nimport sys\nimport subprocess\nC_END = \"\\033[0m\"\nC_RED = \"\\033[31m\"\nC_GREEN = \"\\033[32m\"\nC_YELLOW = \"\\033[33m\"\ndef U_67(): \n sys.stdout = open('./U-67.txt', mode='w', encoding='utf-8')\n print(\"[U-67] SNMP 서비스 구동 점검\")\n out = subprocess.getoutput('ps -ef | grep snmp')\n\n if 'snmp' in out :\n print(C_RED + \"[검사 결과] 보안 조치가 필요합니다.\" + C_END)\n report = True\n\n else : \n print(C_GREEN + \"[검사 결과] 안전합니다.\" + C_END)\n report = False\n###########################################################################################\n if (report) :\n print(\"[U-67] 조치 방법\")\n print(\"\\t1. \\\"ps -ef | grep snmp\\\"로 구동중인 snmp를 검색합니다.\")\n print(\"\\t\\troot 2028 1 0 Nov 24 ? 0:00 /usr/sbin/snmpdm\")\n print(\"\\t2. snmp를 사용하지 않을 시 서비스를 중지합니다.\")\n print(\"\\t\\t#service snmpd stop\")\n sys.stdout.close()\n subprocess.call('cat ./U-67.txt', shell=True)\nU_67()","repo_name":"BoB-Linux/BoB-Linux","sub_path":"security_check/U_67.py","file_name":"U_67.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"33"} +{"seq_id":"7316910994","text":"from transitions import *\nfrom transitions.extensions import GraphMachine\n\nclass IR_Model(object):\n def __init__(self, name):\n self.name = name\n self.states = ['start']\n self.machine = GraphMachine(model=self, initial='start', title=name, show_conditions=True, show_state_attributes=True)\n\n def get_condition_list(self, self_transitions):\n condition_list = []\n existing_conditions = self_transitions[0].conditions\n for condition in existing_conditions:\n condition_list.append(condition.func) # get the string of the condition, not the condition obj\n return condition_list\n\n def update_condition_list(self, self_transitions, new_condition_list):\n condition_list = self.get_condition_list(self_transitions)\n for new_condition in new_condition_list:\n if new_condition not in condition_list:\n condition_list.append(new_condition)\n return condition_list\n\n def add_new_transition(self, trigger, source, dest):\n existing_transitions = self.machine.get_transitions(trigger=trigger, source=source, dest=dest)\n if len(existing_transitions) == 0:\n self.machine.add_transition(trigger=trigger, source=source, dest=dest)\n self.states.append(source)\n self.states.append(dest)\n\n def add_self_transition(self, state, new_condition_list):\n trigger_list = self.machine.get_triggers(state)\n for trigger in trigger_list:\n if trigger == 'self': # self loop exists in the usage model\n self_transitions = self.machine.get_transitions('self', state, state)\n condition_list = self.update_condition_list(self_transitions, new_condition_list)\n self.machine.remove_transition('self', state, state)\n self.machine.add_transition(trigger='self', source=state, dest=state, conditions=condition_list)\n self.states.append(state)\n return\n # when self loop doesn't exist or the state doesn't exist\n self.machine.add_transition(trigger='self', source=state, dest=state, conditions=new_condition_list)\n self.states.append(state)\n\n\nif __name__ == '__main__':\n# transitions = [\n# {'trigger': 'widget1', 'source': 'start', 'dest': 'state1', 'unless': 'aaa'},\n# {'trigger': 'widget2', 'source': 'start', 'dest': 'ICSE',\n# 'conditions': ['is_valid', 'is_also_valid']}\n# ]\n# states = [{'name': 'ICSE', 'on_exit': ['resume', 'notify']},\n# {'name': 'final', 'on_enter': 'alert', 'on_exit': 'resume'}]\n model1 = IR_Model('HELLO')\n transition = {'trigger': 'self', 'source': 'start', 'dest': 'aaa', 'conditions': ['con1', 'con2'], 'label': ['label1']}\n model1.machine.add_transitions(transition)\n model1.states.append('aaa')\n model1.states.append('start')\n print(model1.states)\n # conditions = []\n # for cond in model1.machine.get_transitions('self', 'start', 'start')[0].conditions:\n # conditions.append(cond.func)\n # model1.machine.remove_transition('self', 'start', 'start')\n # conditions.append('333333')\n # model1.machine.add_transition(trigger='self', source='start', dest='start', conditions=conditions)\n# model1.machine.add_state(states)\n# print(model1.machine.get_state('final').name)\n model1.get_graph().draw('my_state_diagram.png', prog='dot')","repo_name":"felicitia/UsageTesting-Repo","sub_path":"code/3_model_generation/entities.py","file_name":"entities.py","file_ext":"py","file_size_in_byte":3415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"24250283455","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# File: imagenet_utils.py\n\nimport os\nimport sys\nimport time\nimport pickle\n\nfrom sklearn.metrics import confusion_matrix\n\nimport cv2\nimport numpy as np\nimport multiprocessing\nimport tensorflow as tf\nfrom abc import abstractmethod\n\nfrom tensorpack import imgaug, dataset, ModelDesc, InputDesc\nfrom tensorpack.dataflow import (\n AugmentImageComponent, PrefetchDataZMQ,\n BatchData, MultiThreadMapData, RepeatedDataPoint)\nfrom tensorpack.predict import PredictConfig, SimpleDatasetPredictor\nfrom tensorpack.utils.stats import RatioCounter\nfrom tensorpack.models import regularize_cost\nfrom tensorpack.tfutils.summary import add_moving_summary\nfrom tensorpack.utils import viz\n\n\nclass GoogleNetResize(imgaug.ImageAugmentor):\n \"\"\"\n crop 8%~100% of the original image\n See `Going Deeper with Convolutions` by Google.\n \"\"\"\n def __init__(self, crop_area_fraction=0.08,\n aspect_ratio_low=0.75, aspect_ratio_high=1.333):\n self._init(locals())\n\n def _augment(self, img, _):\n h, w = img.shape[:2]\n area = h * w\n for _ in range(10):\n targetArea = self.rng.uniform(self.crop_area_fraction, 1.0) * area\n aspectR = self.rng.uniform(self.aspect_ratio_low, self.aspect_ratio_high)\n ww = int(np.sqrt(targetArea * aspectR) + 0.5)\n hh = int(np.sqrt(targetArea / aspectR) + 0.5)\n if self.rng.uniform() < 0.5:\n ww, hh = hh, ww\n if hh <= h and ww <= w:\n x1 = 0 if w == ww else self.rng.randint(0, w - ww)\n y1 = 0 if h == hh else self.rng.randint(0, h - hh)\n out = img[y1:y1 + hh, x1:x1 + ww]\n out = cv2.resize(out, (224, 224), interpolation=cv2.INTER_CUBIC)\n return out\n out = imgaug.ResizeShortestEdge(224, interp=cv2.INTER_CUBIC).augment(img)\n out = imgaug.CenterCrop(224).augment(out)\n return out\n\n\n# @ 20171120: introduce crop_method for TR and TS; specific the color_augmentation\ndef fbresnet_augmentor(isTrain, crop_method, color_augmentation):\n \"\"\"\n Augmentor used in fb.resnet.torch, for BGR images in range [0,255].\n \"\"\"\n execution_lst = []\n\n if isTrain:\n augmentors = [\n # 1. crop_method\n # a) GoogleNetResize\n GoogleNetResize(),\n # b) ShortestEdgeResize\n imgaug.ResizeShortestEdge(256),\n # c) GlobalWarp\n imgaug.Resize(226), # NOTE: for CAM generation\n imgaug.RandomCrop((224, 224)),\n # d) CAMCrop\n # (when CAMCrop is set, the output from the original DataFlow has already been cropped)\n # 2. color_augmentation\n imgaug.RandomOrderAug(\n [imgaug.BrightnessScale((0.6, 1.4), clip=False),\n imgaug.Contrast((0.6, 1.4), clip=False),\n imgaug.Saturation(0.4, rgb=False),\n # rgb-bgr conversion for the constants copied from fb.resnet.torch\n imgaug.Lighting(0.1,\n eigval=np.asarray(\n [0.2175, 0.0188, 0.0045][::-1]) * 255.0,\n eigvec=np.array(\n [[-0.5675, 0.7192, 0.4009],\n [-0.5808, -0.0045, -0.8140],\n [-0.5836, -0.6948, 0.4203]],\n dtype='float32')[::-1, ::-1]\n )]),\n imgaug.Flip(horiz=True),\n ]\n\n #\n if crop_method == 'GoogleNetResize':\n print('--> perform GoogleNetResize cropping method during the training pipeline')\n execution_lst.extend([0])\n elif crop_method == 'ShortestEdgeResize':\n print('--> perform ShortestEdgeResize cropping method during the training pipeline')\n execution_lst.extend([1, 3])\n elif crop_method == 'GlobalWarp':\n print('--> perform GlobalWarp cropping method during the training pipeline')\n execution_lst.extend([2, 3])\n elif crop_method == 'CAMCrop':\n # enable CAMCrop @ 20171124\n print('*** Perform CAMCrop to better the training dynamics and the results ***')\n\n if color_augmentation:\n print('--> perform color augmentation during the training pipeline')\n execution_lst.extend([4])\n else:\n print('--> discard the color jittering process during the training pipeline')\n\n # perform mirror reflection augmentation anyway\n execution_lst.extend([5])\n\n else:\n augmentors = [\n imgaug.ResizeShortestEdge(256, cv2.INTER_CUBIC),\n imgaug.CenterCrop((224, 224)),\n imgaug.RandomCrop((224, 224)),\n ]\n\n if crop_method == 'RandomCrop':\n execution_lst.extend([0, 2])\n\n elif crop_method == 'CenterCrop':\n execution_lst.extend([0, 1])\n\n return [ item_ for id_, item_ in enumerate(augmentors) if id_ in execution_lst ]\n\n\n# @ 20171121: introduce repeat_times for the purpose of average estimation during the eval stage\n# @ 20171122: introduce strict_order to keep the order of get_image_lst('val')[0] and the order of\n# dataflow in harmony ...\n# @ 20171124: to extract the CAM_viz of all the images of the train set, we introduce remainder_TR\n# @ 20171125: for CAMCropR\ndef get_AVA2012_dataflow(datadir, name, batch_size, augmentors,\n CAM_dir_pkl = None, CAMCropR = False,\n repeat_times = 1, strict_order = False, remainder_TR = False):\n \"\"\"\n See explanations in the tutorial:\n http://tensorpack.readthedocs.io/en/latest/tutorial/efficient-dataflow.html\n \"\"\"\n assert name in ['train', 'val']\n assert datadir is not None\n assert isinstance(augmentors, list)\n\n isTrain = name == 'train'\n cpu = min(2, multiprocessing.cpu_count())\n if isTrain:\n # change @ 20171122\n # change @ 20171125: for CAMCropR\n ds = dataset.AVA2012(datadir, name, CAM_dir_pkl = CAM_dir_pkl, CAMCropR = CAMCropR,\n shuffle = (strict_order == False))\n print('--> information about the original dataFlow from AVA2012 [TRAIN]:')\n print(ds)\n\n ds = AugmentImageComponent(ds, augmentors, copy = False)\n # change @ 20171122\n # NOTE: When ``nr_proc=1``, the dataflow produces the same data as ``ds`` in the same order\n ds = PrefetchDataZMQ(ds, cpu if strict_order == False else 1)\n ds = BatchData(ds, batch_size, remainder = remainder_TR)\n\n else:\n ds = dataset.AVA2012(datadir, name, shuffle = False)\n print('--> information about the original dataFlow from AVA2012 [VALIDATION]:')\n print(ds)\n\n # add @ 20171121\n ds = RepeatedDataPoint(ds, repeat_times)\n\n aug = imgaug.AugmentorList(augmentors)\n\n def mapf(dp):\n im, cls = dp\n im = aug.augment(im)\n return im, cls\n\n # change @ 20171122\n # BUG @ 20171128\n # NOTE: The order of data points out of MultiThreadMapData.get_data()\n # is not the same as ds.get_data() !\n # NOTE: buffer_size is the minimum number of images loaded from a given folder\n ds = MultiThreadMapData(ds, cpu if strict_order == False else 1, \\\n mapf, buffer_size = 500, strict = True)\n ds = BatchData(ds, batch_size, remainder = True)\n ds = PrefetchDataZMQ(ds, 1)\n\n return ds\n\n\n### adapt from eval_on_ILSVRC12\n# @ 20171121: introduce repeat_times for the purpose of average estimation during the eval stage\n# @ 20171122: introduce confusion_matrix from sklearn for details about the classification performance\n# @ 20171127: introduce fusion_method to refine the approach of fusion\n# @ 20171201: introduce output_predictions to save the interval results for further experiments\n# TODO: feature extraction and other experiments for explaination and exploration\ndef eval_on_AVA2012(model, sessinit, dataflow, repeat_times, fusion_method = 'GlobalAverage',\n output_predictions = True):\n pred_config = PredictConfig(\n model = model,\n session_init = sessinit,\n input_names = ['input', 'label'],\n output_names = ['softmax-logits', 'label']\n )\n\n # add @ 20171127\n def DeMaxMin_GlobalAverage(dps):\n res01 = []\n\n for cls in range(2):\n s = dps[:, cls]\n s_sum_denoise = np.sum(s) - np.max(s) - np.min(s)\n res01.append(s_sum_denoise / (s.shape[0] - 2))\n\n return res01\n\n # add @ 20171127\n def Median(dps):\n res01 = []\n\n for cls in range(2):\n res01.append(np.median(dps[:, cls]))\n\n return res01\n\n #\n def accuracyEstimation(log01_, GTs01_):\n batch_size = log01_.shape[0]\n acc01_ = np.zeros((int(batch_size // repeat_times),))\n y_True_Pred = np.zeros((int(batch_size // repeat_times), 2))\n avg_p = np.zeros((int(batch_size // repeat_times), log01_.shape[1]))\n\n #\n for i in range(acc01_.shape[0]):\n # change @ 20171127 : refine the fusion approaches\n if fusion_method == 'GlobalAverage':\n avgLog01__ = np.average(log01_[(i * repeat_times) : ((i + 1) * repeat_times), :], axis = 0)\n elif fusion_method == 'DeMaxMin_Average':\n assert log01_.shape[0] >= 3, '*** ***'\n avgLog01__ = DeMaxMin_GlobalAverage(log01_[(i * repeat_times) : ((i + 1) * repeat_times), :])\n elif fusion_method == 'Median':\n avgLog01__ = Median(log01_[(i * repeat_times) : ((i + 1) * repeat_times), :])\n\n pred01__ = 0 if avgLog01__[0] > avgLog01__[1] else 1 # TODO: confidence gap? or what if aesthetic_level > 2\n # GTs01_ vs pred01__\n acc01_[i] = int(pred01__ == GTs01_[(i * repeat_times)])\n # add @ 20171122\n y_True_Pred[i, 0] = GTs01_[(i * repeat_times)]\n y_True_Pred[i, 1] = pred01__\n # add @ 20171201\n avg_p[i, :] = avgLog01__[:]\n\n return acc01_, y_True_Pred, avg_p\n\n pred = SimpleDatasetPredictor(pred_config, dataflow)\n acc1 = RatioCounter()\n y_True_Pred_list = []\n interval_results = []\n\n # add @ 20180709: to estimate the time consumption\n elapsed_times = []\n for pred_res in pred.get_result():\n # for each image, we perform the prediction pipeline for repeat_times\n # therefore, ...\n logs01 = pred_res[0]\n GTs01 = pred_res[1]\n batch_size = logs01.shape[0]\n assert batch_size % repeat_times == 0, \\\n '*** batch_size % repeat_times != 0, which makes the accuracyEstimation difficult ***'\n\n start_time = time.time()\n # change @ 20171122\n # change @ 20171201\n acc01, y_True_Pred_, avg_p = accuracyEstimation(logs01, GTs01)\n elapsed_times.append(time.time() - start_time)\n\n y_True_Pred_list.append(y_True_Pred_)\n\n acc1.feed(acc01.sum(), acc01.shape[0])\n\n # add @ 20171201\n interval_results.append(np.hstack( (y_True_Pred_, avg_p) ))\n\n # performance exhibition\n print(\"--> detailed performance exhibition\")\n print(\" Top1 Accuracy: {}\".format(acc1.ratio))\n\n # add @ 20171122\n y_True_Pred_Matrix = np.vstack(y_True_Pred_list)\n conf_matrix = confusion_matrix(y_True_Pred_Matrix[:, 0], y_True_Pred_Matrix[:, 1])\n print(\" Confusion matrix is:\")\n print(conf_matrix)\n print(\" Accuracy of Negative Prediction: \", (conf_matrix[0, 0]) / (conf_matrix[0, 0] + conf_matrix[1, 0]))\n print(\" Accuracy of Positive Prediction: \", (conf_matrix[1, 1]) / (conf_matrix[0, 1] + conf_matrix[1, 1]))\n print(\" Recall of Negative Instances : \", (conf_matrix[0, 0]) / (conf_matrix[0, 0] + conf_matrix[0, 1]))\n print(\" Recall of Positive Instances : \", (conf_matrix[1, 1]) / (conf_matrix[1, 0] + conf_matrix[1, 1]))\n\n # add @ 20171201\n if output_predictions:\n print(' and save interval_results to ./interval_results_AVA2012.pkl for further investigation ...')\n with open('./interval_results_AVA2012.pkl', 'wb') as output_stream:\n pickle.dump({'interval_results' : interval_results}, output_stream)\n\n # add @ 20180709: exhibit the information of time consumption\n print('--> average time consumption per image : {0:.3f}ms'.format( \\\n 1000 * np.sum(elapsed_times) / y_True_Pred_Matrix.shape[0]))\n\n\n### add @ 20171223 to extract the reps from the given specific graph module\ndef feature_extraction_on_AVA2012(model, sessinit, dataflow, data_format, output_name, batch_size_times, feature_dir):\n # set the configuration during the prediction process\n # and apply the SimpleDatasetPredictor to extract the output_name\n pred_config = PredictConfig(\n model = model,\n session_init = sessinit,\n # NOTE: the names in input_names & output_names depends on the definitions in the loaded model\n input_names = ['input', 'label'],\n\toutput_names = [output_name])\n pred = SimpleDatasetPredictor(pred_config, dataflow)\n\n # BEGIN\n cnt = 0\n rep_dict = { output_name : [] }\n for outp in pred.get_result():\n #\n rep = outp[0]\n if (len(rep.shape) == 4) and (data_format == 'NCHW'):\n rep = np.transpose(rep, (0, 2, 3, 1))\n rep_dict[output_name].append(rep)\n\n #\n cnt += 1\n if cnt >= batch_size_times:\n rep_dict[output_name] = np.concatenate(rep_dict[output_name], axis = 0)\n print(' early stop for getting enough reps')\n break;\n\n #\n with open(\"{0}/reps_{1}.pkl\".format(feature_dir, output_name.replace('/', '-')), 'wb') as output_stream:\n print('--> save {} to a local pkl file ...'.format(output_name))\n print(' shape : ', end = '')\n print(rep_dict[output_name].shape)\n pickle.dump(rep_dict, output_stream, protocol = 2)\n\n\n### @ 20171122 to extract the CAM visualization results for an enhanced understanding on\n### the aesthetic awareness within the neural networks\ndef viz_CAM(model, sessinit, name, dataflow, CAM_dir, save_PKL = False, save_REP = False):\n # set the configuration during the prediction process\n # and apply the SimpleDatasetPredictor to extract the output_names\n pred_config = PredictConfig(\n model = model,\n session_init = sessinit,\n # NOTE: the names in input_names & output_names depends on the definitions in the loaded model\n input_names = ['input', 'label'],\n\toutput_names = ['wrong-top1', 'group3/block1/ReLU_output', 'linear_C2/W'],\n return_input = True)\n pred = SimpleDatasetPredictor(pred_config, dataflow)\n\n # create or clear CAM_dir for the output of results of CAM visualization\n CAM_dir = '{}{}'.format(CAM_dir, name)\n if os.path.isdir(CAM_dir):\n print('--> clear the existing results in the directory {}'.format(CAM_dir))\n os.system('rm -r {}'.format(CAM_dir))\n os.system('mkdir -p {}'.format(CAM_dir))\n\n # for the sake of the ease of file government, we save\n # jpgs, pkls and reps into three different directories\n print('--> during the viz_CAM, we will generate the jpgs', end = '')\n os.system('mkdir -p {}'.format(CAM_dir + '/jpg'))\n if save_PKL:\n print(', pkl', end = '')\n os.system('mkdir -p {}'.format(CAM_dir + '/pkl'))\n if save_REP:\n print(', rep', end = '')\n os.system('mkdir -p {}'.format(CAM_dir + '/rep'))\n print(' files for furthre usage')\n\n # get the img_lab_list for proper formation of result recording\n img_lab_list = dataset.AVA2012Meta().get_image_list(name)[0]\n\n # BEGIN\n cnt = 0\n for inp, outp in pred.get_result():\n #\n images, labels = inp\n wrongs, convmaps, W = outp\n batch = wrongs.shape[0]\n\n #\n for i in range(batch):\n convmap = convmaps[i, :, :, :] # 512 x 7 x 7\n weight0 = W[:, 0].T # 512 x 1 for negative\n mergedmap0_7x7 = np.matmul(weight0, convmap.reshape((512, -1))).reshape(7, 7)\n mergedmap0 = cv2.resize(mergedmap0_7x7, (224, 224))\n heatmap0 = viz.intensity_to_rgb(mergedmap0)\n blend0 = images[i] * 0.5 + heatmap0 * 0.5\n\n weight1 = W[:, 1].T # 512 x 1 for positive\n mergedmap1_7x7 = np.matmul(weight1, convmap.reshape((512, -1))).reshape(7, 7)\n mergedmap1 = cv2.resize(mergedmap1_7x7, (224, 224))\n heatmap1 = viz.intensity_to_rgb(mergedmap1)\n blend1 = images[i] * 0.5 + heatmap1 * 0.5\n\n concat = np.concatenate((images[i], heatmap0, blend0, heatmap1, blend1), axis = 1)\n\n imgName, lab01 = img_lab_list[cnt]\n assert lab01 == labels[i], \\\n '*** in viz_CAM: lab01 ({0}) != labels[i] ({1}) in image {2}'.format(lab01, labels[i], imgName)\n\n # save image of CAM visualization\n cv2.imwrite('{0}/jpg/cam_{1}_{2}_{3}.jpg'.format(CAM_dir, os.path.splitext(imgName)[0], \\\n lab01, int(wrongs[i])), concat)\n # add @20171123: for CAMCrop\n if save_PKL:\n with open('{0}/pkl/{1}.pkl'.format(CAM_dir, os.path.splitext(imgName)[0]), 'wb') as output_stream:\n pickle.dump({\"GT01\" : lab01, \"CAM0\" : mergedmap0_7x7, \"CAM1\" : mergedmap1_7x7}, output_stream)\n\n if save_REP:\n with open('{0}/rep/{1}.rep'.format(CAM_dir, os.path.splitext(imgName)[0]), 'wb') as output_stream:\n pickle.dump({\"convmap\" : convmap, \"W\" : W, \"GT01\" : lab01}, output_stream)\n\n cnt += 1\n\n #\n print('=== Finish CAM_viz on all the images in the validation dataset in AVA2012')\n\n\n### TODO\n### follow the procedures as they are given the ImageNet datasets (e.g., BGR)\n### the zero-mean-unit-variance normalization is for ResNet\n### please ensure the harmony between your loaded model and your data pipeline\ndef image_preprocess(image, bgr = True):\n with tf.name_scope('image_preprocess'):\n if image.dtype.base_dtype != tf.float32:\n image = tf.cast(image, tf.float32)\n image = image * (1.0 / 255)\n\n # stats of images from ImageNet, in RGB channel format\n mean = [0.485, 0.456, 0.406]\n std = [0.229, 0.224, 0.225]\n if bgr:\n mean = mean[::-1]\n std = std[::-1]\n\n image_mean = tf.constant(mean, dtype=tf.float32)\n image_std = tf.constant(std, dtype=tf.float32)\n image = (image - image_mean) / image_std\n\n return image\n\n\n### TODO\n### update @ 20171229: introduce JensenFactor for the purpose of JensenEnhanced Loss\n### update @ 20180705: introduce output_dims for the purpose of AESTHETIC_LEVEL experiments\ndef compute_loss_and_error(logits, label, JensenFactor = 0.0, output_dims = 2):\n # update @ 20171229\n if JensenFactor == 0.0:\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = logits, labels = label)\n loss = tf.reduce_mean(loss, name = 'xentropy-loss')\n\n else:\n # weighted cross entropy with JensenFactor\n # L = \\sum (1 - P^{\\JensenFactor}) \\cdot log(P)\n softmax_01 = tf.nn.softmax(logits, dim = -1)\n # choose the corresponding softmax_01 due to label\n label_matrix = tf.one_hot(label, output_dims, axis = -1)\n target_p = tf.reduce_sum(tf.multiply(label_matrix, softmax_01), axis = 1)\n weights_JensenFactor = tf.ones_like(target_p, dtype = 'float32') - tf.pow(target_p, JensenFactor)\n\n # add @ 20180308 to track the trendency of weights_JensenFactor as optimization progresses\n # in order to better understand the function of weights_JensenFactor\n label_float_pos = tf.cast(label, tf.float32)\n weights_JensenFactor_pos = tf.reduce_sum(tf.multiply(weights_JensenFactor, label_float_pos)) / \\\n (tf.reduce_sum(label_float_pos) + 1e-7)\n add_moving_summary(tf.reduce_mean(weights_JensenFactor_pos, name = \"weights_JensenFactor_pos\"))\n\n label_float_neg = tf.ones_like(label_float_pos) - label_float_pos\n weights_JensenFactor_neg = tf.reduce_sum(tf.multiply(weights_JensenFactor, label_float_neg)) / \\\n (tf.reduce_sum(label_float_neg) + 1e-7)\n add_moving_summary(tf.reduce_mean(weights_JensenFactor_neg, name = \"weights_JensenFactor_neg\"))\n\n # BUG: reduction ?\n loss = tf.losses.sparse_softmax_cross_entropy(label, logits, weights = weights_JensenFactor, \\\n reduction = tf.losses.Reduction.NONE)\n\n loss = tf.reduce_mean(loss, name = 'JEentropy-loss')\n\n def prediction_incorrect(logits, label, topk = 1, name = 'incorrect_vector'):\n with tf.name_scope('prediction_incorrect'):\n x = tf.logical_not(tf.nn.in_top_k(logits, label, topk))\n return tf.cast(x, tf.float32, name = name)\n\n wrong = prediction_incorrect(logits, label, 1, name = 'wrong-top1')\n add_moving_summary(tf.reduce_mean(wrong, name = 'train-error-itop1'))\n\n return loss\n\n\n### the proto-type of the ImageNetModel\n### SPECIFIC: image_dtype, data_format, size of X & Y, preprocessing, loss function & regularization method\n### TODO : get_logits\nclass ImageNetModel(ModelDesc):\n\n \"\"\"\n uint8 instead of float32 is used as input type to reduce copy overhead.\n It might hurt the performance a liiiitle bit.\n The pretrained models were trained with float32.\n \"\"\"\n image_dtype = tf.uint8\n\n # update @ 20171229: introduce JensenFactor for JensenEnhanced Loss\n # update @ 20180705: introduce output_dims for AESTHETIC_LEVEL experiments\n def __init__(self, data_format = 'NCHW', JensenFactor = 0.0, output_dims = 2, weight_decay = 1e-4):\n if data_format == 'NCHW':\n assert tf.test.is_gpu_available()\n self.data_format = data_format\n self.weight_decay = weight_decay\n self.JensenFactor = JensenFactor\n\n def _get_inputs(self):\n # despite the setting of self.data_format\n # the original format of the input data is batch_size x H x W x C\n return [InputDesc(self.image_dtype, [None, 224, 224, 3], 'input'),\n InputDesc(tf.int32, [None], 'label')]\n\n def _build_graph(self, inputs):\n image, label = inputs\n image = image_preprocess(image, bgr = True)\n # transform the data_format if necessary\n if self.data_format == 'NCHW':\n image = tf.transpose(image, [0, 3, 1, 2])\n\n # UNDEFINED\n logits = tf.identity(self.get_logits(image), name = 'logits')\n softmax_logits = tf.nn.softmax(logits, name = 'softmax-logits')\n\n # definition of loss\n # update @ 20180705: for AESTHETIC_LEVEL experiments, introduce output_dims\n loss = compute_loss_and_error(logits, label, JensenFactor = self.JensenFactor, output_dims = self.output_dims)\n\n wd_loss = regularize_cost('.*/W', tf.contrib.layers.l2_regularizer(self.weight_decay),\n name='l2_regularize_loss')\n add_moving_summary(loss, wd_loss)\n\n self.cost = tf.add_n([loss, wd_loss], name = 'cost')\n\n @abstractmethod\n def get_logits(self, image):\n \"\"\"\n Args:\n image: 4D tensor of 224x224 in ``self.data_format``\n\n Returns:\n batch_size x output_dims logits\n \"\"\"\n\n def _get_optimizer(self):\n # NOTE: the learning_rate is set to be 0.1 for initialization\n lr = tf.get_variable('learning_rate', initializer = 0.1, trainable = False)\n tf.summary.scalar('learning_rate', lr)\n\n return tf.train.MomentumOptimizer(lr, 0.9, use_nesterov = True)\n\n\n### THE END\n","repo_name":"Openning07/MPADA","sub_path":"imagenet_utils.py","file_name":"imagenet_utils.py","file_ext":"py","file_size_in_byte":23783,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"33"} +{"seq_id":"74781217375","text":"\n#%%\nimport sklearn\nfrom sklearn import svm\nimport sys\nimport os\npath = os.path.join(os.path.dirname(__file__), '../tools/')\nsys.path.insert(1,path)\nfrom email_preprocess import preprocess\nfrom sklearn import metrics\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import classification_report\nimport time\n\n#%%\n# split data\nfeatures_train, features_test, labels_train, labels_test = preprocess()\n# one persent of the train data\nfeatures_train_1 = features_train[:int(len(features_train)/100)]\nlabels_train_1 = labels_train[:int(len(labels_train)/100)]\n#%%\n# linear kernel\nclf = svm.SVC(kernel='linear')\nstart_time = time.time()\npred = clf.fit(features_train, labels_train).predict(features_test)\nprint(\"Accuracy:\",metrics.accuracy_score(labels_test, pred))\nprint(round(time.time()-start_time,2),\" seconds\")\n\n# %%\n# Exhaustive Grid Search\nc_values = [0.001,0.01,0.1,1,10,100,500,1000,5000]\ngamma_values = [0.001,0.01,0.1,10,20,100,500]\nkernels = ['linear', 'rbf', 'sigmoid','poly']\nresults = []\n# test with 1% of the data for performance puposes\nfor c in c_values:\n for k in kernels:\n if k != 'rbf':\n start_time = time.time()\n clf = svm.SVC(kernel=k,C=c)\n pred = clf.fit(features_train_1, labels_train_1).predict(features_test)\n duration = time.time()-start_time\n acc = metrics.accuracy_score(labels_test, pred)\n print('kernel:',k,\"C:\",c)\n print(\"Accuracy:\",acc)\n print(round(time.time()-start_time,2),\" seconds \\n\")\n results.append({'kernel':k, 'C':c,'Accuracy':acc,'time':duration})\n else:\n for g in gamma_values:\n start_time = time.time()\n clf = svm.SVC(kernel=k,C=c, gamma=g)\n pred = clf.fit(features_train_1, labels_train_1).predict(features_test)\n duration = time.time()-start_time\n acc = metrics.accuracy_score(labels_test, pred)\n print('kernel:',k,\"C:\",c, 'gamma:',g)\n print(\"Accuracy:\",acc)\n print(round(time.time()-start_time,2),\" seconds \\n\")\n results.append({'kernel':k, 'C':c, 'gamma':g,'Accuracy':acc,'time':duration})\n\n#%%\nbest = max(results, key=lambda x: x['Accuracy'])\nbest_kernel = best['kernel']\nbest_c = best['C']\nbest_gamma = best['gamma']\n\nprint(best_kernel, best_c, best['Accuracy'])\n\n# %%\n# rbf kernel with the best parameters\nclf = svm.SVC(kernel=best_kernel, C = best_c, gamma = best_gamma)\npred = clf.fit(features_train, labels_train).predict(features_test)\nprint(\"Accuracy:\",metrics.accuracy_score(labels_test, pred))\nprint(round(time.time()-start_time,2),\" seconds\")\n\n\n# %%\n# Parameter estimation using grid search with cross-validation\n\ntuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4,1,10],\n 'C': [0.1,1, 10, 100, 1000, 6000]},\n {'kernel': ['linear', 'sigmoid','poly'], 'C': [1, 10, 100, 1000,6000]}]\n\nscores = ['precision', 'recall','f1']\n\nfor score in scores:\n print(\"# Tuning hyper-parameters for %s\" % score)\n print()\n\n clf = GridSearchCV(\n svm.SVC(), tuned_parameters, scoring='%s_macro' % score\n )\n clf.fit(features_train_1, labels_train_1)\n\n print(\"Best parameters set found on development set:\")\n print()\n print(clf.best_params_)\n\n print()\n print(\"The model is trained on the full development set.\")\n print(\"The scores are computed on the full evaluation set.\")\n print()\n y_true, y_pred = labels_test, clf.predict(features_test)\n print(classification_report(y_true, y_pred))\n print()\n\n#%%\n# Parameter estimation using grid search with cross-validation\nsvr = svm.SVC()\nclf = GridSearchCV(svr, tuned_parameters)\npred = clf.fit(features_train_1, labels_train_1).predict(features_test)\nprint(\"Accuracy:\",metrics.accuracy_score(labels_test, pred))\n\n\n# %%\nsklearn.metrics.SCORERS.keys()\n\n# %%\n","repo_name":"hamidkhbl/ML","sub_path":"SVM/svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"39935315585","text":"import pandas as pd\nimport os\n\n# path => Chemin du csv / size => nombre de ligne par csv\ndef divise_csv(path, size):\n # read DataFrame\n data = pd.read_csv(path + '.tsv',sep='\\t')\n \n # k -> nombre de csv créé\n k = (len(data) // 10000) + 1\n\n # creation csv \n for i in range(k):\n df = data[size*i:size*(i+1)]\n df.to_csv(f'{path}_{i+1}.csv', index=False)\n\n\n\nmy_list = os.listdir('csv')\nfor name in my_list: \n # my_path = \"csv/\" + name + '/'+ name + '.tsv'\n my_path = \"csv/\" + name + '/'+ name\n print(my_path)\n divise_csv(my_path, 10000)\n # data =pd.read_csv(my_path, sep='\\t')\n \n","repo_name":"JeremYnov/admin-database-imdb","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"39435503001","text":"\"\"\"\nGenerally useful functions that don't relate to anything else in Playtools but\nare used in Playtools.\n\"\"\"\nimport os\nimport re\n\nfrom twisted.python.util import sibpath\n\nRESOURCE = lambda f: sibpath(__file__, f)\n\ndef rdfName(s):\n \"\"\"Return a string suitable for an IRI from s\"\"\"\n s = s.replace('.', ' ')\n s = s.replace('-', ' ')\n s = s.replace(\"'\", '')\n s = s.replace('/', ' ')\n s = s.replace(':', ' ')\n s = s.replace(',', ' ')\n s = s.replace('+', ' ')\n s = s.replace('(', ' ').replace(\")\", ' ')\n s = s.replace('[', ' ').replace(\"]\", ' ')\n parts = s.split()\n parts[0] = parts[0].lower()\n parts[1:] = [p.capitalize() for p in parts[1:]]\n ret = ''.join(parts)\n if ret[0].isdigit(): ret = '_' + ret\n return ret\n\ndef filenameAsUri(fn):\n return 'file://' + os.path.abspath(fn)\n\ndef prefixen(prefixes, ref):\n \"\"\"\n Return a shorter version of ref (as unicode) that replaces the long URI\n with a prefix in prefixes. Or otherwise format it as a short unicode\n string.\n \"\"\"\n # this path for formulae\n if hasattr(ref, 'namespaces'):\n return ref.n3()\n\n parts = ref.partition('#')\n doc = parts[0] + '#'\n for k,v in prefixes.items():\n if unicode(v) == doc:\n return '%s:%s' % (k, parts[2])\n return ref.n3()\n\ndef columnizeResult(res, prefixes=None):\n \"\"\"\n Print a query result in nice columns\n \"\"\"\n if prefixes is None:\n prefixes = {}\n ret = []\n for colName in res.selectionF:\n ret.append(colName[:26].ljust(28))\n ret.append('\\n')\n px = lambda s: prefixen(prefixes, s)\n for item in res:\n for col in item:\n ret.append(px(col)[:26].ljust(28))\n ret.append('\\n')\n return ''.join(ret)\n\ndef substituteNodes(node, replacements):\n \"\"\"\n Replace the node with a list of nodes that replace it\n \"\"\"\n p = node.parentNode\n for r in replacements:\n p.insertBefore(r, node)\n p.removeChild(node)\n\ndef doNodes(dom, matcher, cb=None):\n \"\"\"\n Call cb(node) on every node under dom for which matcher(node) == True\n \"\"\"\n todo = [dom]\n\n if cb is None:\n cb = lambda x: x\n\n for n, node in enumerate(todo):\n # slice assignment is fucking awesome\n todo[n+1:n+1] = list(node.childNodes)\n if matcher(node):\n yield cb(node)\n\ndef findNodes(dom, matcher):\n \"\"\"\n Generate nodes matching the matcher function\n \"\"\"\n for node in doNodes(dom, matcher):\n yield node\n\ndef gatherText(dom, accumulator=None):\n \"\"\"\n Return all the text nodes\n \"\"\"\n tn = findNodes(dom, lambda x: x.nodeName == '#text')\n return ' '.join([t.toxml() for t in tn])\n\ndef findNodeByAttribute(root, attribute, value=None):\n \"\"\"\n Return the first node under root that has attr=\"value\"\n \"\"\"\n try:\n return findNodesByAttribute(root, attribute, value).next()\n except StopIteration:\n return None\n\ndef findNodesByAttribute(root, attribute, value=None):\n \"\"\"\n Iterate all nodes under root that have attribute=\"value\". Specify value=None to\n find any node that has attribute set at all.\n \"\"\"\n def matcher(n):\n return attr(n, attribute, value)\n return findNodes(root, matcher)\n\ndef attr(node, name, value=None):\n \"\"\"\n If value is None: true if node has an attribute 'name'\n If value is specified: true if node's attribute 'name' is equal to value\n \"\"\"\n if not hasattr(node, 'getAttribute'):\n return False\n if not node.hasAttribute(name):\n return False\n if value is None:\n return True\n return node.getAttribute(name) == value\n\n","repo_name":"corydodt/Playtools","sub_path":"playtools/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"72792198494","text":"#!/usr/bin/python3\nimport operator\nimport sys, getopt\nimport json\nimport os\nsys.path.append(os.getcwd())\nsys.path.append(\"..\")\nsys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"../\"))\nimport log\nimport log.logger\nimport traceback\nimport datetime\nimport sqlalchemy\nimport stmanage\nimport requests\nimport comm\nimport comm.error\nimport comm.result\nfrom comm.result import result\nfrom comm.error import error\nfrom comm.parseargs import parseargs\nfrom comm.functions import (\n json_print,\n root_path\n )\nfrom ethopt.ethclient import ethclient, ethwallet\nfrom enum import Enum\nfrom vrequest.request_client import requestclient\nfrom analysis.analysis_filter import afilter\nfrom dataproof import dataproof\n\n#module name\nname=\"ethtools\"\nchain = \"ethereum\"\n\n\n#load logging\nlogger = log.logger.getLogger(name) \n\n'''\n*************************************************ethclient oper*******************************************************\n'''\n\nclient = None\n\ndef get_ethclient(usd_erc20 = True):\n global client\n if client:\n return client\n\n client = ethclient(name, stmanage.get_eth_nodes(), chain)\n client.load_vlsmproof(stmanage.get_eth_token(\"vlsmproof\")[\"address\"])\n if usd_erc20:\n tokens = client.get_token_list().datas\n logger.debug(f\"support tokens: {tokens}\")\n for token in tokens:\n client.load_contract(token)\n return client\n \newclient = None\ndef get_ethwallet():\n global ewclient\n if ewclient:\n return eclient\n ewclient = ethwallet(name, dataproof.wallets(\"ethereum\"), chain)\n return ewclient\n\ndef get_ethproof(dtype = \"v2b\"):\n\n return requestclient(name, stmanage.get_db(dtype))\n\ndef show_token_list():\n logger.debug(f\"start show_token_name()\")\n client = get_ethclient()\n ret = client.get_token_list()\n assert ret.state == error.SUCCEED, \"get tokens failed.\"\n json_print(ret.datas)\n\ndef show_proof_contract_address(name):\n logger.debug(f\"start show_proof_contract_address({name})\")\n client = get_ethclient()\n ret = client.get_proof_contract_address(name)\n assert ret.state == error.SUCCEED, \"get proof contract failed.\"\n print(ret.datas)\n\ndef mint_coin(address, amount, token_id, module):\n logger.debug(\"start mint_coin({address}, {amount}, {token_id}, {module})\")\n print(client.get_balance(address, token_id, module).datas)\n\ndef bind_token_id(address, token_id, gas_token_id):\n logger.debug(f\"start bind_token_id({address}, {token_id}, {gas_token_id}\")\n\ndef send_coin(from_address, to_address, amount, token_id):\n wallet = get_ethwallet()\n ret = wallet.get_account(from_address)\n if ret.state != error.SUCCEED:\n raise Exception(\"get account failed\")\n account = ret.datas\n\n client = get_ethclient()\n ret = client.send_coin_erc20(account, to_address, amount, token_id)\n assert ret.state == error.SUCCEED, ret.message\n print(f\"cur balance :{client.get_balance(account.address, token_id).datas}\")\n\ndef approve(from_address, to_address, amount, token_id):\n wallet = get_ethwallet()\n ret = wallet.get_account(from_address)\n if ret.state != error.SUCCEED:\n raise Exception(\"get account failed\")\n account = ret.datas\n\n client = get_ethclient()\n ret = client.approve(account, to_address, amount, token_id)\n assert ret.state == error.SUCCEED, ret.message\n print(f\"cur balance :{client.allowance(from_address, to_address, token_id).datas}\")\n\ndef send_proof(from_address, token_id, datas):\n wallet = get_ethwallet()\n ret = wallet.get_account(from_address)\n if ret.state != error.SUCCEED:\n raise Exception(\"get account failed\")\n account = ret.datas\n\n client = get_ethclient()\n \n ret = client.send_proof(account, token_id, datas)\n assert ret.state == error.SUCCEED, ret.message\n print(f\"cur balance :{client.get_balance(account.address, token_id).datas}\")\n\ndef allowance(from_address, to_address, token_id):\n client = get_ethclient()\n ret = client.allowance(from_address, to_address, token_id)\n assert ret.state == error.SUCCEED, ret.message\n print(f\"allowance balance :{ret.datas}\")\n\ndef get_balance(address, token_id, module = \"\"):\n logger.debug(f\"start get_balance address= {address} module = {module} token_id= {token_id}\")\n client = get_ethclient()\n ret = client.get_balance(address, token_id, module)\n logger.debug(\"balance: {0}\".format(ret.datas))\n\ndef get_decimals(token_id):\n logger.debug(f\"start get_decimals token_id= {token_id}\")\n client = get_ethclient()\n ret = client.get_decimals(token_id)\n logger.debug(f\"decimals: {ret}\")\n\ndef get_balances(address):\n logger.debug(f\"start get_balances address= {address}\")\n client = get_ethclient()\n ret = client.get_balances(address)\n logger.debug(\"balance: {0}\".format(ret.datas))\n\ndef get_latest_transaction_version():\n logger.debug(f\"start get_latest_transaction_version\")\n client = get_ethclient()\n ret = client.get_latest_transaction_version()\n logger.debug(\"latest version: {0}\".format(ret.datas))\n\ndef get_address_latest_version(address):\n logger.debug(f\"start get_address_latest_version({address})\")\n client = get_ethclient()\n ret = client.get_address_latest_version(address)\n logger.debug(\"latest version: {0}\".format(ret.datas))\n\ndef get_transactions(start_version, limit = 1, fetch_event = True, raw = False):\n logger.debug(f\"start get_transactions(start_version={start_version}, limit={limit}, fetch_event={fetch_event})\")\n\n client = get_ethclient()\n ret = client.get_transactions(start_version, limit, fetch_event)\n print(f\"count: {len(ret.datas)}\")\n if ret.state != error.SUCCEED:\n return\n if ret.datas is None or len(ret.datas) == 0:\n return\n for data in ret.datas:\n if raw:\n print(data)\n else:\n info = afilter.get_tran_data(data, chain ==\"violas\")\n json_print(info)\n\ndef get_rawtransaction(txhash):\n logger.debug(f\"start get_rawtransaction(txhash={txhash}\")\n\n client = get_ethclient()\n ret = client.get_rawtransaction(txhash)\n if ret.state != error.SUCCEED:\n return\n\n print(ret.datas)\n\ndef get_address_sequence(address):\n logger.debug(f\"start get_address_sequence({address})\")\n client = get_ethclient()\n ret = client.get_address_sequence(address)\n logger.debug(\"version: {0}\".format(ret.datas))\n\ndef get_transaction_version(address, sequence):\n logger.debug(f\"start get_address_version({address}, {sequence})\")\n client = get_ethclient()\n ret = client.get_transaction_version(address, sequence)\n logger.debug(\"version: {0}\".format(ret.datas))\n\ndef get_syncing_state():\n logger.debug(f\"start get_syncing_state()\")\n client = get_ethclient()\n ret = client.get_syncing_state()\n logger.debug(\"version: {0}\".format(ret.datas))\n\ndef get_chain_id():\n logger.debug(f\"start get_chain_id()\")\n client = get_ethclient(False)\n ret = client.get_chain_id()\n logger.debug(\"version: {0}\".format(ret.datas))\n\ndef get_token_min_amount(token_id):\n logger.debug(f\"start get_token_min_amount({token_id})\")\n client = get_ethclient(False)\n ret = client.get_token_min_amount(token_id)\n logger.debug(\"amount: {0}\".format(ret.datas))\n\ndef get_token_max_amount(token_id):\n logger.debug(f\"start get_token_max_amount({token_id})\")\n client = get_ethclient(False)\n ret = client.get_token_max_amount(token_id)\n logger.debug(\"amount: {0}\".format(ret.datas))\n\n'''\n*************************************************ethwallet oper*******************************************************\n'''\ndef new_account():\n wallet = get_ethwallet()\n ret = wallet.new_account()\n wallet.dump_wallet()\n assert ret.state == error.SUCCEED, \"new_account failed\"\n logger.debug(\"account address : {}\".format(ret.datas.address))\n\ndef address_has_token_id(address, token_id):\n logger.debug(f\"start address_has_token_id address= {address} module = {token_id}\")\n client = get_ethclient()\n logger.debug(client.has_token_id(address, token_id).datas)\n\ndef show_accounts():\n wallet = get_ethwallet()\n i = 0\n account_count = wallet.get_account_count()\n print(f\"account count: {account_count}\")\n while True and i < account_count:\n ret = wallet.get_account(int(i))\n if ret.state != error.SUCCEED:\n break \n account = ret.datas\n logger.debug(f\"{i}: {account.address}\")\n i += 1\n\ndef show_accounts_full():\n wallet = get_ethwallet()\n i = 0\n account_count = wallet.get_account_count()\n while True and i < account_count:\n ret = wallet.get_account(i)\n if ret.state != error.SUCCEED:\n break \n account = ret.datas\n logger.debug(f\"({i:03}): address: {account.address} privkey: {account.key.hex()}\")\n i += 1\n\ndef get_account(address):\n client = get_ethclient()\n print(client.get_account_state(address).datas)\n\ndef has_account(address):\n wallet = get_ethwallet()\n logger.debug(wallet.has_account_by_address(address).datas)\n\n\n'''\n*************************************************main oper*******************************************************\n'''\ndef init_args(pargs):\n pargs.clear()\n pargs.append(\"help\", \"show arg list.\")\n pargs.append(\"conf\", \"config file path name. default:bvexchange.toml, find from . and /etc/bvexchange/\", True, \"toml file\", priority = 5)\n pargs.append(\"wallet\", \"inpurt wallet file or mnemonic\", True, \"file name/mnemonic\", priority = 13, argtype = parseargs.argtype.STR)\n\n #wallet \n pargs.append(new_account, \"new account and save to local wallet.\")\n pargs.append(get_account, \"show account info.\")\n pargs.append(has_account, \"has target account in wallet.\")\n pargs.append(show_accounts, \"show all counts address list(local wallet).\")\n pargs.append(show_accounts_full, \"show all counts address list(local wallet) with privkey.\")\n\n #client\n pargs.append(send_coin, \"send token(erc20 coin) to target address\")\n pargs.append(approve, \"approve to_address use coin amount from from_address\")\n pargs.append(allowance, \"request to_address can use coin amount from from_address\")\n pargs.append(send_proof, \"send mapping proof\")\n pargs.append(get_balance, \"get address's token(module) amount.\")\n pargs.append(get_balances, \"get address's tokens.\")\n pargs.append(get_transactions, \"get transactions from eth nodes.\")\n pargs.append(get_rawtransaction, \"get transaction from eth nodes.\")\n pargs.append(get_latest_transaction_version, \"show latest transaction version.\")\n pargs.append(get_address_latest_version, \"get address's latest version'.\")\n pargs.append(get_address_sequence, \"get address's latest sequence'.\")\n pargs.append(get_transaction_version, \"get address's version'.\")\n pargs.append(get_decimals, \"get address's token decimals.\")\n pargs.append(get_syncing_state, \"get chain syncing state.\",)\n pargs.append(get_chain_id, \"get chain id.\")\n pargs.append(get_token_min_amount, \"get token min amount of main contract.\")\n pargs.append(get_token_max_amount, \"get token min amount of main contract.\")\n pargs.append(show_token_list, \"show token list.\")\n pargs.append(show_proof_contract_address, \"show proof main address(args = main datas state).\")\n\n\ndef run(argc, argv, exit = True):\n try:\n logger.debug(\"start eth.main\")\n pargs = parseargs(exit = exit)\n init_args(pargs)\n if pargs.show_help(argv):\n return\n\n opts, err_args = pargs.getopt(argv)\n except getopt.GetoptError as e:\n logger.error(e)\n if exit:\n sys.exit(2)\n return \n except Exception as e:\n logger.error(e)\n if exit:\n sys.exit(2)\n return \n\n #argument start for --\n if len(err_args) > 0:\n pargs.show_args()\n return\n\n names = [opt for opt, arg in opts]\n pargs.check_unique(names)\n\n global chain\n for opt, arg in opts:\n \n arg_list = []\n if len(arg) > 0:\n count, arg_list = pargs.split_arg(opt, arg)\n\n print(\"opt = {}, arg = {}\".format(opt, arg_list))\n if pargs.is_matched(opt, [\"conf\"]):\n stmanage.set_conf_env(arg)\n elif pargs.is_matched(opt, [\"help\"]):\n pargs.show_args()\n return\n elif pargs.is_matched(opt, [\"wallet\"]):\n if not arg:\n pargs.exit_error_opt(opt)\n dataproof.wallets.update_wallet(\"ethereum\", arg)\n elif pargs.is_matched(opt, [\"chain\"]):\n if len(arg_list) != 1:\n pargs.exit_error_opt(opt)\n chain = arg_list[0]\n elif pargs.is_matched(opt, [\"get_transactions\"]):\n if len(arg_list) != 3 and len(arg_list) != 2 and len(arg_list) != 1:\n pargs.exit_error_opt(opt)\n if len(arg_list) == 3:\n get_transactions(int(arg_list[0]), int(arg_list[1]), arg_list[2] in (\"True\"))\n elif len(arg_list) == 2:\n get_transactions(int(arg_list[0]), int(arg_list[1]))\n elif len(arg_list) == 1:\n get_transactions(int(arg_list[0]))\n elif pargs.has_callback(opt):\n pargs.callback(opt, *arg_list)\n else:\n raise Exception(f\"not found matched opt{opt}\")\n logger.debug(\"end manage.main\")\n\nif __name__ == \"__main__\":\n run(len(sys.argv) - 1, sys.argv[1:])\n","repo_name":"palliums-developers/bvexchange","sub_path":"ethopt/ethtools.py","file_name":"ethtools.py","file_ext":"py","file_size_in_byte":13410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"31427763052","text":"from __future__ import annotations\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from scheduler import LoadGenerator\n from energy_model import EnergyModel\n from cpu import CPU, PerfDom\n\nimport math\nimport heapq\n\nfrom scheduler import Task, Clock\nfrom energy_model import Schedutil\nfrom profiler import Profiler\n\nclass EAS:\n def __init__(self, load_gen: LoadGenerator, cpus: list[CPU], em: EnergyModel, sched_tick_period_ms: int = 1) -> None:\n self._load_gen: LoadGenerator = load_gen\n self._em: EnergyModel = em\n\n self._clock = Clock() \n self.profiler = Profiler(self._clock)\n\n self._sched_tick_period: int = sched_tick_period_ms\n\n self._cpus: list[CPU] = cpus\n self._perf_domains_name: list[PerfDom] = []\n self._cpus_per_domain: dict[PerfDom, list[CPU]] = {}\n self._run_queues: dict[CPU, RunQueue] = {}\n for cpu in cpus:\n perf_dom = cpu.type\n\n if perf_dom not in self._perf_domains_name:\n self._perf_domains_name.append(perf_dom)\n self._cpus_per_domain[perf_dom] = []\n\n self._cpus_per_domain[cpu.type].append(cpu)\n self._run_queues[cpu] = RunQueue()\n\n cpu.start(self.profiler)\n\n self._idle_task = Task(-1, \"idle\", enforce=False)\n\n def run(self, time: int) -> None:\n while self._clock.time < time:\n # every 1000ms rebalance the load if CPU is over utilized\n if self._clock.time % 1000 == 0 and self._is_over_utilized():\n self._load_balancer()\n\n # pick the next task to execute on each CPU\n for cpu in self._cpus:\n queue: RunQueue = self._run_queues[cpu]\n\n # we assume new task could be comes at each scheduler tick\n # on each CPU\n # and those task are assumed to never sleep or being blocked\n new_task: Task | None = self._load_gen.gen()\n if new_task is not None:\n self.profiler.new_task()\n best_cpu: CPU = self._wake_up_balancer(cpu, new_task)\n self._run_queues[best_cpu].insert(new_task)\n\n # update P-States\n Schedutil.update(cpu, queue.cap)\n\n task: Task | None = queue.pop_smallest_vr()\n if task is None:\n task = self._idle_task\n \n cpu.execute_for(task, self._sched_tick_period)\n if task.name != \"idle\":\n if not task.terminated:\n queue.insert(task)\n elif task.name not in (\"energy\", \"balance\"):\n self.profiler.end_task()\n \n self._clock.inc_ms(self._sched_tick_period)\n\n # extremely simplefied compared to CFS implementation\n def _load_balancer(self) -> None:\n complexity: int = 0\n idle_cpu: CPU | None = None\n overloaded_cpu: tuple[CPU | None, int | float] = (None, -math.inf)\n for cpu in self._cpus:\n load: float = self._compute_load(cpu)\n if load == 0.0:\n idle_cpu = cpu\n elif overloaded_cpu[1] < load:\n overloaded_cpu = (cpu, load)\n\n complexity += len(self._cpus)\n\n if idle_cpu is not None:\n # assert(overloaded_cpu[0] is not None) was used during dev phase\n overloaded_runqueue: RunQueue = self._run_queues[overloaded_cpu[0]] # type: ignore\n idle_runqueue: RunQueue = self._run_queues[idle_cpu]\n task: Task | None = overloaded_runqueue.pop_highest_vr()\n if task is not None:\n idle_runqueue.insert(task)\n\n if task is not None:\n complexity += math.ceil(math.log2(overloaded_runqueue.size + 1) * 2)\n if idle_runqueue.size - 1 > 0:\n complexity += math.ceil(math.log2(idle_runqueue.size - 1))\n\n # simulate the load balancer\n # cpus[0] is responsible of the scheduling group\n self._run_queues[self._cpus[0]].insert_kernel_task(Task(100 * complexity, \"balance\"))\n\n def _is_over_utilized(self) -> bool:\n for cpu in self._cpus:\n if self._compute_load(cpu) > 80:\n return True\n return False\n\n def _wake_up_balancer(self, by_cpu: CPU, task: Task) -> CPU:\n if self._is_over_utilized():\n self.profiler.task_placed_by(\"balance\")\n best_cpu: CPU = by_cpu\n for cpu in self._cpus:\n if self._run_queues[cpu].cap == 0:\n best_cpu = cpu\n\n # simulate the wake up balancer\n self._run_queues[by_cpu].insert_kernel_task(Task(10 * len(self._cpus), \"balance\"))\n\n else:\n self.profiler.task_placed_by(\"energy\")\n best_cpu = self._find_energy_efficient_cpu(by_cpu, task)\n\n return best_cpu\n\n def _find_energy_efficient_cpu(self, by_cpu: CPU, task: Task) -> CPU:\n complexity: int = 0\n \n candidates: list[CPU] = []\n for domain in self._perf_domains_name:\n candidate: CPU = self._cpus_per_domain[domain][0]\n candidate_cap: int = self._run_queues[candidate].cap\n for cpu in self._cpus_per_domain[domain][1:]:\n capacity = self._run_queues[cpu].cap\n if capacity < candidate_cap:\n candidate = cpu\n candidate_cap = capacity\n candidates.append(candidate)\n complexity += len(self._cpus_per_domain[domain])\n\n best_cpu: CPU | None = None\n best_cpu_energy: float = math.inf\n landscape: dict[CPU, int] = {cpu: self._run_queues[cpu].cap for cpu in candidates}\n for candidate in candidates:\n landscape[candidate] += task.remaining_cycles\n energy, em_complexity = self._em.compute_energy(landscape)\n landscape[candidate] -= task.remaining_cycles\n if energy < best_cpu_energy:\n best_cpu = candidate\n best_cpu_energy = energy\n complexity += em_complexity \n\n # simulate the energy efficient wake-up balancer\n self._run_queues[by_cpu].insert_kernel_task(Task(100 * complexity, \"energy\"))\n\n # assert(best_cpu is not None) was used during dev phase\n return best_cpu # type: ignore\n\n def _compute_load(self, cpu: CPU) -> float:\n return self._run_queues[cpu].cap / cpu.max_capacity * 100\n\n\n### it was easier to implement heap queue instead of red black tree, but nothing change for our analyses ###\nclass _RunQueueNode():\n def __init__(self, task: Task):\n self._task: Task = task\n self._key: int = task.executed_cycles\n self._cap: int = task.remaining_cycles\n\n @property\n def key(self) -> int:\n return self._key\n\n @property\n def cap(self) -> int:\n return self._cap\n\n @property\n def task(self) -> Task:\n return self._task\n\n def __lt__(self, obj):\n return self.key < obj.key\n\n def __le__(self, obj):\n return self.key <= obj.key\n\n def __eq__(self, obj):\n return self.key == obj.key\n\n def __ne__(self, obj):\n return self.key != obj.key\n\n def __gt__(self, obj):\n return self.key > obj.key\n\n def __ge__(self, obj):\n return self.key >= obj.key\n\n\nclass RunQueue():\n def __init__(self):\n self._queue: list[_RunQueueNode] = []\n self._kernel_queue: list[_RunQueueNode] = []\n self._total_cap: int = 0\n\n @property\n def size(self) -> int:\n return len(self._queue)\n\n def pop_smallest_vr(self) -> None | Task:\n if len(self._kernel_queue) != 0:\n task_node: _RunQueueNode = self._kernel_queue.pop(0)\n elif self.size == 0:\n return None\n else:\n task_node: _RunQueueNode = heapq.heappop(self._queue)\n \n self._total_cap -= task_node.cap\n return task_node.task\n\n def pop_highest_vr(self) -> None | Task:\n if self.size == 0:\n return None\n index_max: int = max(range(len(self._queue)),\n key=self._queue.__getitem__)\n task_node: _RunQueueNode = self._queue[index_max]\n self._total_cap -= task_node.cap\n del self._queue[index_max]\n heapq.heapify(self._queue)\n return task_node.task\n\n @property\n def cap(self) -> int:\n return self._total_cap\n\n def insert(self, task: Task):\n task_node = _RunQueueNode(task)\n self._total_cap += task_node.cap\n heapq.heappush(self._queue, task_node)\n \n def insert_kernel_task(self, task: Task):\n task_node = _RunQueueNode(task)\n self._total_cap += task_node.cap\n self._kernel_queue.append(task_node)\n","repo_name":"EmixamPP/eas-simulator","sub_path":"scheduler/eas.py","file_name":"eas.py","file_ext":"py","file_size_in_byte":8824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"14844808650","text":"from connections.calculi.intuitionistic import *\nfrom connections.utils.primitives import *\nimport connections.utils.unification_d as d\n\n\nclass DConnectionState(IConnectionState):\n\n def __init__(self, matrix, domain):\n super().__init__(matrix)\n self.domain = domain\n\n def pre_unify(self,pre_1,pre_2,s):\n return d.pre_unify(pre_1.args, [], pre_2.args, s=s)\n \n def pre_unify_list(self,list,s):\n return d.pre_unify_list(list,s)\n\n # Don't append W\n def _pre_eq(self,lit_1,lit_2):\n if lit_2.prefix is None:\n lit_2.prefix = Function('string')\n if lit_1.prefix is None:\n lit_1.prefix = Function('string')\n pre_1, pre_2 = lit_1.prefix, lit_2.prefix\n return pre_1, pre_2\n\n\n # single prefix subsitution for all pairs (var,eigenvar) in classical substitution and (lit,lit) in classical connections\n def _admissible_pairs(self):\n if self.domain in 'constant':\n return []\n if self.domain == 'cumulative':\n equations = []\n for var, term in self.substitutions[-1].items():\n # loop over eigenvariables (given by \"f_skolem\" symbol)\n for eigen in self._find_eigenvariables(term):\n var_pre = Function('string',var.prefix.args[:len(eigen.prefix.args)])\n equations.append((var_pre, eigen.prefix))\n return equations\n if self.domain == 'varying':\n equations = []\n for var, term in self.substitutions[-1].items():\n # loop over eigenvariables (given by \"f_skolem\" symbol)\n for eigen in self._find_eigenvariables(term):\n equations.append((var.prefix, eigen.prefix))\n return equations","repo_name":"fredrrom/connections","sub_path":"connections/calculi/modal_d.py","file_name":"modal_d.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"41223962870","text":"#!/usr/bin/python\n\nclass Solution:\n class Goodness():\n def __init__(self, good_words):\n self._good_words_string = good_words\n self._good_words = good_words.split(\"_\")\n \n def get_goodness_level(self, review):\n level = 0\n review_words = review.split(\"_\")\n for w in self._good_words:\n if w in review_words:\n level += 1\n return level\n \n class ReviewNode():\n def __init__(self, index, review, dictionary):\n self.level = dictionary.get_goodness_level(review)\n self.index = index\n \n self.left = None\n self.right = None\n \n def insert(self, node, root=None):\n if root == None:\n root = node\n elif node.level <= root.level:\n if root.left == None:\n root.left = node\n else:\n self.insert(node, root.left)\n else:\n if root.right == None:\n root.right = node\n else:\n self.insert(node, root.right)\n \n return root\n \n def sort(self, root):\n if root == None:\n return\n \n yield from self.sort(root.right)\n \n yield root.index\n print(\"{} \".format(root.index))\n \n yield from self.sort(root.left)\n\n \n # @param A : string\n # @param B : list of strings\n # @return a list of integers\n def solve(self, A, B):\n goodness = Solution.Goodness(A)\n \n root = None\n for i in range(len(B)):\n node = Solution.ReviewNode(i, B[i], goodness)\n root = self.insert(node, root)\n \n return [ i for i in self.sort(root)]\n\n\nif __name__ == \"__main__\":\n A = \"cool_ice_wifi\"\n B = [ \"water_is_cool\", \"cold_ice_drink\", \"cool_wifi_speed\" ]\n\n sol = Solution()\n rev = sol.solve(A, B)\n\n print(rev)\n","repo_name":"iconoeugen/swe","sub_path":"algorithms/backtracking/backtracking_reviews_goodness.py","file_name":"backtracking_reviews_goodness.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"9592139892","text":"from builtins import object\nimport copy\nimport json\nimport time\n\nfrom cerberus import Validator\n\nfrom yahoo_panoptes.framework import const\nfrom yahoo_panoptes.framework.context import PanoptesContext\nfrom yahoo_panoptes.framework.exceptions import PanoptesBaseException\nfrom yahoo_panoptes.framework.resources import PanoptesResource\nfrom yahoo_panoptes.framework.utilities.key_value_store import PanoptesKeyValueStore\nfrom yahoo_panoptes.framework.validators import PanoptesValidators\n\n\nclass PanoptesEnrichmentException(PanoptesBaseException):\n \"\"\"\n The base class for all Panoptes Enrichment exceptions\n \"\"\"\n pass\n\n\nclass PanoptesEnrichmentCacheKeyValueStore(PanoptesKeyValueStore):\n \"\"\"\n A custom Key/Value store for Panoptes Enrichment Cache\n \"\"\"\n redis_group = const.ENRICHMENT_REDIS_GROUP\n\n def __init__(self, panoptes_context):\n super(PanoptesEnrichmentCacheKeyValueStore, self).__init__(\n panoptes_context, const.ENRICHMENT_PLUGIN_RESULTS_KEY_VALUE_NAMESPACE)\n\n\nclass PanoptesEnrichmentSchemaValidator(object):\n \"\"\"\n Schema validator base class based on Cerberus\n \"\"\"\n schema = {u'key': u'value'}\n\n def __init__(self):\n assert isinstance(self.schema, dict) and len(self.schema) > 0, \\\n u'schema must be a non empty Cerberus schema dict'\n self.__cerberus_validator = Validator(schema=self.schema)\n\n def validate(self, enrichment_set_data):\n \"\"\"\n Validates PanoptesEnrichmentSet object against defined schema\n\n Args:\n enrichment_set_data (PanoptesEnrichmentSet): PanoptesEnrichmentSet to validate\n Returns:\n bool\n \"\"\"\n assert isinstance(enrichment_set_data, PanoptesEnrichmentSet), \\\n u'element set must be an instance of PanoptesEnrichmentSet'\n schema = copy.deepcopy(self.schema)\n schema[enrichment_set_data.key] = schema.pop(u'enrichment_label')\n return self.__cerberus_validator.validate(document=enrichment_set_data._raw_data, schema=schema)\n\n\nclass PanoptesEnrichmentEncoder(json.JSONEncoder):\n \"\"\"\n Custom Json encoder to convert set to list during encoding\n \"\"\"\n # https://github.com/PyCQA/pylint/issues/414\n def default(self, o): # pylint: disable=E0202\n if isinstance(o, set):\n return list(o)\n if isinstance(o, PanoptesResource):\n return o.__dict__[u'_PanoptesResource__data']\n if isinstance(o, PanoptesEnrichmentSet):\n return o.__dict__[u'_PanoptesEnrichmentSet__data']\n if isinstance(o, PanoptesEnrichmentGroup):\n return o.__dict__[u'_PanoptesEnrichmentGroup__data']\n if isinstance(o, PanoptesEnrichmentGroupSet):\n return o.__dict__[u'_PanoptesEnrichmentGroupSet__data']\n if isinstance(o, PanoptesEnrichmentMultiGroupSet):\n return o.__dict__[u'_PanoptesEnrichmentMultiGroupSet__data']\n return json.JSONEncoder.default(self, o)\n\n\nclass PanoptesEnrichmentSet(object):\n \"\"\"\n Representation of a basic enrichment element\n\n A PanoptesEnrichmentSet hold key(label) and collection of enrichment info as its value\n\n Args:\n key (as defined in schema): label for enrichment element collection\n value (dict): enrichment collection\n\n Examples:\n An example enrichment set data structure\n\n {\n \"int_001\" : {\n \"speed\" : 1000,\n \"index\" : 1,\n \"status\" : \"up\"\n }\n }\n \"\"\"\n def __init__(self, key, value={None: None}):\n assert PanoptesValidators().valid_nonempty_string(key), u'enrichment key must be a string'\n assert isinstance(value, dict), u'enrichment value must be a dict'\n if value == {None: None}:\n value = {}\n self.__data = dict()\n self._key = key\n self.__data[self._key] = value\n\n @property\n def key(self):\n return self._key\n\n @property\n def value(self):\n return self.__data[self._key]\n\n @property\n def _raw_data(self):\n return self.__data\n\n def add(self, enrichment_key, enrichment_value):\n \"\"\"\n Adds enrichment key and value elements to PanoptesEnrichmentSet object\n\n Args:\n enrichment_key (as defined in schema): The enrichment element key\n enrichment_value (as defined in schema): The enrichment element value corresponding to the key\n\n Returns:\n None\n\n \"\"\"\n self.__data[self._key][enrichment_key] = enrichment_value\n\n def json(self):\n return json.dumps(self.__data, sort_keys=True)\n\n def __repr__(self):\n data = u','.join([\n key + u'[' + u','.join(\n u\"{}:{}\".format(inner_key, inner_value) for inner_key, inner_value\n in sorted(list(self.__data[key].items()))) + u']'\n for key, value in sorted(list(self.__data.items()))\n ])\n\n return u'{}[{}]'.format(self.__class__.__name__, data)\n\n def __hash__(self):\n return hash(self._key)\n\n def __len__(self):\n return len(self.__data[self._key])\n\n def __lt__(self, other):\n _self = u','.join([u'{}|{}'.format(key, value)\n for key, value in sorted(self.__data[self._key].items())])\n _other = u','.join([u'{}|{}'.format(key, value)\n for key, value in sorted(other.__data[other._key].items())])\n\n return _self < _other\n\n def __eq__(self, other):\n if not isinstance(other, PanoptesEnrichmentSet):\n return False\n return self._key == other._key\n\n\nclass PanoptesEnrichmentGroup(object):\n \"\"\"\n Representation of Enrichment Group\n\n Collection of enrichment elements(PanoptesEnrichmentSet) grouped by Enrichment key(namespace)\n\n Args:\n namespace (str): enrichment namespace\n schema_validator (PanoptesEnrichmentSchemaValidator): PanoptesEnrichmentSchemaValidator\n instance initialized with schema\n execute_frequency (int): Execute frequency of the plugin which produced this object\n enrichment_ttl (int): TTL value of the enrichment object\n\n Examples:\n An example PanoptesEnrichmentGroup data structure\n\n {\n \"namespace\" : \"interface\",\n \"data\" : [\n {\n \"value\" : {\n \"speed\" : 1000,\n \"status\" : \"up\",\n \"index\" : 1\n },\n \"key\" : \"int_001\"\n }\n ]\n }\n \"\"\"\n\n def __init__(self, namespace, schema_validator, enrichment_ttl, execute_frequency):\n assert PanoptesValidators().valid_nonempty_string(namespace), u'enrichment namespace must be a string'\n assert isinstance(schema_validator, PanoptesEnrichmentSchemaValidator), \\\n u'schema_validator must be an instance of PanoptesEnrichmentSchemaValidator'\n assert PanoptesValidators().valid_nonzero_integer(enrichment_ttl), \\\n u'enrichment_ttl must be a valid nonzero integer'\n assert PanoptesValidators().valid_nonzero_integer(execute_frequency), \\\n u'execute_frequency must be a valid nonzero integer'\n self.__data = dict()\n self.__data[u'metadata'] = dict()\n self.__data[u'namespace'] = namespace\n self.__data[u'data'] = set()\n self.__schema_validator = schema_validator\n self.__data[u'metadata'][u'_enrichment_group_creation_timestamp'] = time.time()\n self.__data[u'metadata'][u'_enrichment_ttl'] = enrichment_ttl\n self.__data[u'metadata'][u'_execute_frequency'] = execute_frequency\n\n @property\n def enrichment_schema(self):\n return self.__schema_validator.schema\n\n @property\n def validator(self):\n return self.__schema_validator\n\n @property\n def namespace(self):\n return self.__data[u'namespace']\n\n @property\n def data(self):\n return self.__data[u'data']\n\n @property\n def _raw_data(self):\n return self.__data\n\n @property\n def metadata(self):\n return self.__data[u'metadata']\n\n @property\n def enrichment_ttl(self):\n return self.__data[u'metadata'][u'_enrichment_ttl']\n\n @property\n def execute_frequency(self):\n return self.__data[u'metadata'][u'_execute_frequency']\n\n @property\n def enrichment_group_creation_timestamp(self):\n return self.__data[u'metadata'][u'_enrichment_group_creation_timestamp']\n\n def add_enrichment_set(self, enrichment_set):\n \"\"\"\n Adds enrichment_set(PanoptesEnrichmentSet) to create Enrichment Group\n\n Args:\n enrichment_set (PanoptesEnrichmentSet): Collection of enrichment elements(PanoptesEnrichmentSet)\n\n Returns:\n None\n \"\"\"\n assert isinstance(enrichment_set, PanoptesEnrichmentSet), \\\n u'enrichment set must be an instance of PanoptesEnrichmentSet'\n\n assert self.__schema_validator.validate(enrichment_set), \\\n u'schema validation failed for enrichment_set data'\n self.__data[u'data'].discard(enrichment_set)\n self.__data[u'data'].add(enrichment_set)\n\n def upsert_metadata(self, metadata_key, metadata_value):\n \"\"\"\n Adds metadata key / value pairs to PanoptesEnrichmentGroup\n\n Args:\n metadata_key (str): metadata key\n metadata_value (str or int or float): metadata value\n\n Returns:\n None\n \"\"\"\n assert PanoptesValidators().valid_nonempty_string(metadata_key), u'metadata_key must be a string'\n\n if metadata_key.startswith(u'_'):\n raise ValueError(u'Failed to update reserved metadata')\n\n assert \\\n PanoptesValidators().valid_nonempty_string(metadata_value) or \\\n PanoptesValidators().valid_number(metadata_value), u'metadata_value must be any of string / float / integer'\n\n self.__data[u'metadata'][metadata_key] = metadata_value\n\n def bulk_add_enrichment_set(self):\n pass\n\n def json(self):\n return json.dumps(self.__data, sort_keys=True, cls=PanoptesEnrichmentEncoder)\n\n def serialize_data(self):\n return json.dumps({enrichment_set.key: enrichment_set.value for enrichment_set in self.data}, sort_keys=True)\n\n def serialize(self):\n enrichment_serialize = dict()\n enrichment_serialize[u'data'] = {enrichment_set.key: enrichment_set.value for enrichment_set in self.data}\n enrichment_serialize[u'metadata'] = self.__data[u'metadata']\n\n # TODO: Log this instead of creating a new key. Also, don't accept bytes as inputs for enrichments\n return json.dumps(\n enrichment_serialize,\n sort_keys=True,\n default=lambda x: x.decode(u'ascii', u'ignore') + u'__decoded' if isinstance(x, bytes) else x\n )\n\n def __repr__(self):\n if len(self) is 0:\n return u'{}[namespace:{},enrichment_ttl:{},' \\\n u'execute_frequency:{},' \\\n u'enrichment_group_creation_timestamp:{}]'.format(self.__class__.__name__, self.namespace,\n self.enrichment_ttl, self.execute_frequency,\n self.enrichment_group_creation_timestamp)\n return u'{}[namespace:{},enrichment_ttl:{},' \\\n u'execute_frequency:{},' \\\n u'enrichment_group_creation_timestamp:{},{}]'.format(self.__class__.__name__, self.namespace,\n self.enrichment_ttl, self.execute_frequency,\n self.enrichment_group_creation_timestamp,\n u','.join(repr(enrichment) for enrichment\n in sorted(self.__data[u'data'])))\n\n def __len__(self):\n return len(self.__data[u'data'])\n\n def __hash__(self):\n return hash(self.namespace)\n\n def __lt__(self, other):\n return self.namespace < other.namespace\n\n def __eq__(self, other):\n if not isinstance(other, PanoptesEnrichmentGroup):\n return False\n return self.namespace == other.namespace\n\n\nclass PanoptesEnrichmentGroupSet(object):\n \"\"\"\n Representation of Enrichment Group Set\n\n Collection of enrichment group grouped by resource\n\n Args:\n resource (PanoptesResource): PanoptesResource object\n\n Example:\n An example PanoptesEnrichmentGroupSet data structure\n {\n \"resource\" : PanoptesResource_instance,\n \"enrichment\" : [\n {\n \"namespace\" : \"interface\",\n \"data\" : [\n {\n \"value\" : {\n \"index\" : 1,\n \"status\" : \"up\",\n \"speed\" : 1000\n },\n \"key\" : \"int_001\"\n }\n ]\n }\n ]\n }\n \"\"\"\n\n def __init__(self, resource):\n assert isinstance(resource, PanoptesResource), u'resource must be an instance of PanoptesResource'\n self.__data = dict()\n self.__data[u'resource'] = resource\n self.__data[u'enrichment_group_set_creation_timestamp'] = time.time()\n self.__data[u'enrichment'] = set()\n\n @property\n def resource(self):\n return self.__data[u'resource']\n\n @property\n def enrichment(self):\n return self.__data[u'enrichment']\n\n @property\n def enrichment_group_set_creation_timestamp(self):\n return self.__data[u'enrichment_group_set_creation_timestamp']\n\n @property\n def _raw_data(self):\n return self.__data\n\n def add_enrichment_group(self, enrichment_group):\n \"\"\"\n Adds enrichment_group(PanoptesEnrichmentGroup) to create enrichment group set\n\n Args:\n enrichment_group (PanoptesEnrichmentGroup): Enrichment elements grouped by key\n\n Returns:\n None\n \"\"\"\n assert isinstance(enrichment_group, PanoptesEnrichmentGroup), \\\n u'enrichment_group must be an instance of PanoptesEnrichmentGroup'\n assert len(enrichment_group.data) > 0, u'enrichment_group must hold at least one data set'\n self.__data[u'enrichment'].discard(enrichment_group)\n self.__data[u'enrichment'].add(enrichment_group)\n\n def bulk_add_enrichment_group(self):\n pass\n\n def json(self):\n return json.dumps(self.__data, sort_keys=True, cls=PanoptesEnrichmentEncoder)\n\n def __repr__(self):\n if len(self) is 0:\n return u\"{}[resource:{},enrichment_group_set_creation_timestamp:{}]\"\\\n .format(self.__class__.__name__, str(self.resource), self.enrichment_group_set_creation_timestamp)\n return u\"{}[resource:{},enrichment_group_set_creation_timestamp:{},{}]\"\\\n .format(self.__class__.__name__, str(self.resource), self.enrichment_group_set_creation_timestamp,\n u','.join(repr(enrichment_group) for enrichment_group in sorted(self.enrichment)))\n\n def __len__(self):\n return len(self.__data[u'enrichment'])\n\n def __hash__(self):\n namespaces_self = ''.join(sorted([item.namespace for item in self.enrichment]))\n return hash(self.resource.resource_id + namespaces_self)\n\n def __lt__(self, other):\n if not isinstance(other, PanoptesEnrichmentGroupSet):\n return False\n return self.resource < other.resource\n\n def __eq__(self, other):\n if not isinstance(other, PanoptesEnrichmentGroupSet):\n return False\n namespaces_other = ''.join(sorted([item.namespace for item in other.enrichment]))\n namespaces_self = ''.join(sorted([item.namespace for item in self.enrichment]))\n return self.resource.resource_id == other.resource.resource_id and namespaces_self == namespaces_other\n\n\nclass PanoptesEnrichmentMultiGroupSet(object):\n \"\"\"\n Collection of PanoptesEnrichmentGroupSet belongs to multiple Panoptes resources\n \"\"\"\n def __init__(self):\n self.__data = dict()\n self.__data[u'group_sets'] = set()\n\n def add_enrichment_group_set(self, enrichment_group_set):\n \"\"\"\n Adds enrichment_group_set(PanoptesEnrichmentGroupSet)\n\n Args:\n enrichment_group_set (PanoptesEnrichmentGroupSet): Enrichment group set of a Panoptes resource\n\n Returns:\n None\n \"\"\"\n assert isinstance(enrichment_group_set, PanoptesEnrichmentGroupSet), \\\n u'enrichment_group_set must be an instance of PanoptesEnrichmentGroupSet'\n assert len(enrichment_group_set) > 0, u'enrichment_group_set must hold at least one data set'\n self.__data[u'group_sets'].discard(enrichment_group_set)\n self.__data[u'group_sets'].add(enrichment_group_set)\n\n @property\n def enrichment_group_sets(self):\n return self.__data[u'group_sets']\n\n def __len__(self):\n return len(self.__data[u'group_sets'])\n\n def __repr__(self):\n return u\"{}[{}]\".format(self.__class__.__name__,\n u','.join(repr(enrichment_group_set) for enrichment_group_set in\n sorted(self.enrichment_group_sets)))\n\n def json(self):\n return json.dumps(self.__data, sort_keys=True, cls=PanoptesEnrichmentEncoder)\n\n\nclass PanoptesEnrichmentCacheError(PanoptesBaseException):\n \"\"\"\n The base class for all Panoptes Enrichment Cache errors\n \"\"\"\n pass\n\n\nclass PanoptesEnrichmentCache(object):\n \"\"\"\n Fetches enrichment from kv store and act as cache for polling plugins\n\n Args:\n panoptes_context (PanoptesContext): The PanoptesContext being used by the Plugin Agent\n plugin_conf (dict): Plugin conf dict\n resource (PanoptesResource): Resource object associated with plugin runner instance\n \"\"\"\n\n def __init__(self, panoptes_context, plugin_conf, resource):\n assert isinstance(panoptes_context, PanoptesContext), u'panoptes_context must be an instance of PanoptesContext'\n assert isinstance(resource, PanoptesResource), u'resource must be an instance of PanoptesResource'\n assert isinstance(plugin_conf, dict), u'plugin_conf value must be a dict'\n\n self._logger = panoptes_context.logger\n self._plugin_name = plugin_conf[u'Core'][u'name']\n self._panoptes_context = panoptes_context\n self._enrichment_conf = plugin_conf[u'enrichment']\n self._resource_id = resource.resource_id\n self._preload_conf = self._parse_conf()\n self._enrichment_data = dict()\n\n try:\n self._kv_store = PanoptesEnrichmentCacheKeyValueStore(panoptes_context)\n except Exception as e:\n raise e\n\n self._process_enrichment()\n\n self._logger.debug(u'Successfully created PanoptesEnrichmentCache enrichment_data {} for plugin {}'.\n format(self._enrichment_data, self._plugin_name))\n\n def get_enrichment(self, resource_id, namespace):\n \"\"\"\n Returns enrichment data for matching resource_id and namespace\n\n Args:\n resource_id (str): Panoptes resource id\n namespace (str): Enrichment namespace\n Returns:\n enrichment_data (dict): enrichment_data dict\n \"\"\"\n assert PanoptesValidators().valid_nonempty_string(resource_id), u'resource_id must be a string'\n assert PanoptesValidators().valid_nonempty_string(namespace), u'enrichment namespace must be a string'\n\n if resource_id == u'self':\n resource_id = self._resource_id\n\n try:\n return {key: value for key, value in list(self._enrichment_data[resource_id][namespace].items())}\n except KeyError:\n try:\n self._preload_data(resource_id, namespace)\n return {key: value for key, value in list(self._enrichment_data[resource_id][namespace].items())}\n except Exception as e:\n raise PanoptesEnrichmentCacheError(u'Failed to get data for resource {} namespace {} from enrichment '\n u'resource object: {} plugin_name: {}'\n .format(resource_id, namespace, repr(e), self._plugin_name))\n\n def get_enrichment_value(self, resource_id, namespace, enrichment_key):\n \"\"\"\n Returns enrichment value for matching resource_id, namespace and\n enrichment_key\n\n Args:\n resource_id (str): Panoptes resource id\n namespace (str): Enrichment namespace\n enrichment_key (str): Enrichment set key\n Returns:\n enrichment_set (dict): key, value pairs of enrichment\n \"\"\"\n assert PanoptesValidators().valid_nonempty_string(resource_id), u'resource_id must be a string'\n assert PanoptesValidators().valid_nonempty_string(namespace), u'enrichment namespace must be a string'\n assert PanoptesValidators().valid_nonempty_string(enrichment_key), u'enrichment_key must be a string'\n\n if resource_id == u'self':\n resource_id = self._resource_id\n\n try:\n return self._enrichment_data[resource_id][namespace][enrichment_key]\n except KeyError:\n try:\n self._preload_data(resource_id, namespace)\n return self._enrichment_data[resource_id][namespace][enrichment_key]\n except Exception as e:\n raise PanoptesEnrichmentCacheError(\n u'Failed to get data for resource {} namespace {} enrichment_key {} '\n u'from enrichment cache object: {} plugin_name: {}'.format(\n resource_id, namespace, enrichment_key, repr(e), self._plugin_name))\n\n def get_enrichment_keys(self, resource_id, namespace):\n \"\"\"\n Returns enrichment keys for matching resource_id and namespace\n\n Args:\n resource_id (str): Panoptes resource id\n namespace (str): Enrichment namespace\n Returns:\n enrichment_keys (list): enrichment keys(label)\n \"\"\"\n assert PanoptesValidators().valid_nonempty_string(resource_id), u'resource_id must be a string'\n assert PanoptesValidators().valid_nonempty_string(namespace), u'enrichment namespace must be a string'\n\n if resource_id == u'self':\n resource_id = self._resource_id\n\n try:\n return list(self._enrichment_data[resource_id][namespace].keys())\n except KeyError:\n try:\n self._preload_data(resource_id, namespace)\n return list(self._enrichment_data[resource_id][namespace].keys())\n except Exception as e:\n raise PanoptesEnrichmentCacheError(u'Failed to get data for resource {} namespace {} from enrichment '\n u'cache object: {} plugin_name'\n .format(resource_id, namespace, repr(e), self._plugin_name))\n\n def _process_enrichment(self):\n for resource, namespace in self._preload_conf:\n if resource == u'self':\n resource = self._resource_id\n\n if namespace == u'*':\n try:\n namespace_keys = self._kv_store.find_keys(resource + const.KV_NAMESPACE_DELIMITER + namespace)\n if namespace_keys:\n namespaces = [namespace_field.split(':')[-1] for namespace_field in namespace_keys]\n for normalized_namespace in namespaces:\n self._preload_data(resource, normalized_namespace)\n except Exception as e:\n self._logger.error(\n u'Error while scanning namespace pattern {} on KV store for plugin {} resource {}: {}'.format(\n namespace, self._plugin_name, resource, repr(e)))\n else:\n self._preload_data(resource, namespace)\n\n def _preload_data(self, resource, namespace):\n try:\n key = resource + const.KV_NAMESPACE_DELIMITER + namespace\n value = self._kv_store.get(key)\n if value:\n data = json.loads(value).get(u'data')\n self._enrichment_data.setdefault(resource, dict())\n self._enrichment_data[resource].update(**{namespace: data})\n self._logger.debug(u'Successfully populated enrichment for plugin {} resource {} namespace {} data {}'.\n format(self._plugin_name, resource, namespace, data))\n else:\n self._logger.error(\n u'No enrichment data found on KV store for plugin {} resource {} namespace {} using key {}'.format(\n self._plugin_name, resource, namespace, key))\n except Exception as e:\n raise IOError(\n u'Failed while pre-loading enrichment from KV store for plugin {} resource {} namespace {}: {}'.format(\n self._plugin_name, resource, namespace, repr(e)))\n\n def _parse_conf(self):\n try:\n return {(item.split(u':')[0].strip(), item.split(u':')[1].strip())\n for item in self._enrichment_conf.get(u'preload').split(u',')}\n except Exception as e:\n raise PanoptesEnrichmentCacheError(\n u'Failed while parsing preload enrichment configuration from plugin conf for '\n u'plugin {}: {}'.format(self._plugin_name, repr(e))\n )\n","repo_name":"yahoo/panoptes","sub_path":"yahoo_panoptes/framework/enrichment.py","file_name":"enrichment.py","file_ext":"py","file_size_in_byte":25634,"program_lang":"python","lang":"en","doc_type":"code","stars":100,"dataset":"github-code","pt":"33"} +{"seq_id":"15785993917","text":"\"\"\"\n参考链接:\nhttps://blog.csdn.net/foreverhot1019/article/details/78793816\n\"\"\"\nimport numpy as np\nimport cv2 as cv\n\n\ndef show_image(image, win_name='input image'):\n cv.namedWindow(win_name, cv.WINDOW_NORMAL)\n cv.imshow(win_name, image)\n cv.waitKey(0)\n cv.destroyAllWindows()\n return\n\n\ndef binary_image(gray):\n kernel = cv.getStructuringElement(cv.MORPH_RECT, (17, 1))\n tophat = cv.morphologyEx(gray, cv.MORPH_TOPHAT, kernel)\n show_image(tophat)\n\n gray_x = cv.Sobel(tophat, ddepth=cv.CV_32F, dx=1, dy=0, ksize=-1)\n gray_x = np.absolute(gray_x)\n min_value, max_value = np.min(gray_x), np.max(gray_x)\n gray_x = 255 * (gray_x - min_value) / (max_value - min_value)\n gray_x = gray_x.astype('uint8')\n\n gray_x = cv.morphologyEx(gray_x, cv.MORPH_CLOSE, kernel)\n _, binary = cv.threshold(gray_x, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)\n show_image(binary)\n\n return binary\n\n\ndef find_contours(binary):\n _, contours, _ = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)\n filtered_contours = list()\n for i, c in enumerate(contours):\n (x, y, w, h) = cv.boundingRect(c)\n ar = w / h\n\n if (ar > 1.5 and ar < 4.0):\n if (w > 55 and w < 80) and (h > 15 and h < 30):\n filtered_contours.append((x, y, w, h))\n filtered_contours = sorted(filtered_contours, key=lambda x: x[0])\n return filtered_contours\n\n\ndef show_rectangle(image, filtered_contours):\n for x, y, w, h in filtered_contours:\n cv.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)\n show_image(image)\n return\n\n\ndef demo():\n image_path = '../dataset/data/bank_card/card_ 5.png'\n image = cv.imread(image_path)\n image = cv.resize(image, dsize=(450, 280))\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n\n binary = binary_image(gray)\n filtered_contours = find_contours(binary)\n\n print(filtered_contours)\n show_rectangle(image, filtered_contours)\n return\n\n\nif __name__ == '__main__':\n demo()\n","repo_name":"tianxing1994/OpenCV","sub_path":"练习实例/银行卡号码检测.py","file_name":"银行卡号码检测.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"33"} +{"seq_id":"72925620255","text":"from app.models import db, Note\nfrom datetime import datetime\n\ndef seed_notes():\n note1 = Note(\n title='Demo note',\n description='example note for testing',\n content='I need to create seeder data in order to test my backend routes and state',\n user_id=1,\n notebook_id=1,\n created_at=datetime.utcnow(),\n updated_at=datetime.utcnow()\n )\n note2 = Note(\n title='Demo note 2 (INSIDE NOTEBOOK 1)',\n description='example note for testing 2',\n content='I need to create seeder data in order to test my backend routes and state 2',\n notebook_id=1,\n user_id=1,\n created_at=datetime.utcnow(),\n updated_at=datetime.utcnow()\n )\n\n note3 = Note(\n title='Demo note 3 (INSIDE NOTEBOOK 2)',\n description='example note for testing',\n content='I need to create seeder data in order to test my backend routes and state 3',\n notebook_id=1,\n user_id=1,\n created_at=datetime.utcnow(),\n updated_at=datetime.utcnow()\n )\n\n note4 = Note(\n title='Demo note 4',\n description='example note for testing 4',\n content='I need to create seeder data in order to test my backend routes and state 4',\n user_id=2,\n notebook_id=2,\n created_at=datetime.utcnow(),\n updated_at=datetime.utcnow()\n )\n\n db.session.add(note1)\n db.session.add(note2)\n db.session.add(note3)\n db.session.add(note4)\n db.session.commit()\n\n\n\ndef undo_notes():\n db.session.execute('TRUNCATE notes RESTART IDENTITY CASCADE')\n db.session.commit()","repo_name":"AnthonyRo1/Everynote","sub_path":"app/seeds/notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"12488866295","text":"import dolfin\nimport fixtures\nimport pulse\n\nimport pulse_adjoint\n\n\ndef test_create_reduced_functional():\n\n start_control = 1.0\n target_control = 2.0\n target_pressure = 0.5\n\n problem, control = fixtures.create_problem(\"R_0\", control_value=start_control)\n problem2, control2 = fixtures.create_problem(\"R_0\", control_value=target_control)\n\n pressure_data = [target_pressure]\n\n pulse.iterate.iterate(problem2, problem2.bcs.neumann[0].traction, target_pressure)\n u, p = dolfin.split(problem2.state)\n\n volume_data = [problem2.geometry.cavity_volume(u=u)]\n\n # Create volume observersion\n endo = problem.geometry.markers[\"ENDO\"][0]\n volume_model = pulse_adjoint.model_observations.VolumeObservation(\n problem.geometry.mesh, problem.geometry.ds(endo)\n )\n volume_target = pulse_adjoint.OptimizationTarget(volume_data, volume_model)\n\n pressure_obs = pulse_adjoint.model_observations.BoundaryObservation(\n problem.bcs.neumann[0], pressure_data\n )\n\n assimilator = pulse_adjoint.Assimilator(\n problem, targets=[volume_target], bcs=pressure_obs, control=control\n )\n\n rd = assimilator.create_reduced_functional()\n assert abs(rd(target_control)) < 1e-12\n\n\nif __name__ == \"__main__\":\n test_create_reduced_functional()\n","repo_name":"ComputationalPhysiology/pulse_adjoint","sub_path":"tests/test_reduced_functional.py","file_name":"test_reduced_functional.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"916085492","text":"\"\"\"CD Chat client program\"\"\"\nimport logging\nimport socket\nimport selectors\nfrom .protocol import CDProto, CDProtoBadFormat\nimport sys\nimport fcntl\nimport os\nimport json\nimport time\nlogging.basicConfig(filename=f\"{sys.argv[0]}.log\", level=logging.DEBUG)\n\n\nclass Client:\n \"\"\"Chat Client process.\"\"\"\n \n def __init__(self, name: str = \"Foo\"):\n \"\"\"Initializes chat client.\"\"\"\n #cliente a tem um nome de atributo que vai ser o user no protocolo\n #atributos\n self.name=name\n self.sel=selectors.DefaultSelector()\n self.protocolo=CDProto()\n self.channel=None\n self.socket=\"\"\n\n\n def receberServidor(self,socket,mask):\n \"\"\"Aqui vai ser lido o valor do servidor\"\"\"\n msg=self.protocolo.recv_msg(socket)\n logging.debug(\"received: %s\",msg)\n if (hasattr(msg, 'channel')):\n print(\"{}-> {}\".format(msg.__getattribute__(\"channel\"),msg.__getattribute__(\"message\")))\n else:\n print(\"{}\".format(msg.__getattribute__(\"message\")))\n\n\n def ler_input(self,input,mask):\n \"\"\"Aqui vai ser lido o valor de input\"\"\"\n \n msg=input.read().strip() # retirar o \\n com o strip\n #criar mensagem\n if (msg == 'exit'): #apagar \n self.sel.unregister(self.socket)\n self.socket.close()\n self.sel.unregister(input)\n sys.exit(0)\n\n elif (msg[0:5] == '/join'):\n msg=msg[6:]\n juntar=self.protocolo.join(msg)\n self.protocolo.send_msg(self.socket,juntar.__dict__)\n self.channel=msg\n\n else : #mensagem normal\n if (self.channel == None):\n msg_Prot=self.protocolo.message(msg)\n print(msg_Prot)\n self.protocolo.send_msg(self.socket,msg_Prot.__dict__)\n \n else:\n msg_Prot=self.protocolo.message(msg,self.channel)\n self.protocolo.send_msg(self.socket,msg_Prot.__dict__)\n \n\n def connect(self):\n \"\"\"Connect to chat server and setup stdin flags.\"\"\"\n #aqui vou ter que ligar ao RegisterMessager indicando-lhe o name \n sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n sock.connect(('localhost', 1234))\n self.socket=sock\n #ir buscar o atributo do name \n msg=self.protocolo.register(self.name) \n \n self.protocolo.send_msg(sock,msg.__dict__)\n \n # comandos para fazer o cliente nao bloquear\n orig_fl = fcntl.fcntl(sys.stdin, fcntl.F_GETFL)\n fcntl.fcntl(sys.stdin, fcntl.F_SETFL, orig_fl | os.O_NONBLOCK)\n #colocar o seletor a ler ou a receber \n self.sel.register(sys.stdin, selectors.EVENT_READ,self.ler_input)\n self.sel.register(sock, selectors.EVENT_READ,self.receberServidor)\n\n \n\n def loop(self):\n \"\"\"Loop indefinetely.\"\"\"\n while True: \n sys.stdout.write('')\n sys.stdout.flush()\n for key, mask in self.sel.select():\n callback = key.data\n callback(key.fileobj, mask)\n \n","repo_name":"alexandreserras/CD","sub_path":"guião1/src/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"14019075483","text":"import discord\nfrom emoji import emojize as emo\n\nfrom transformers import BertTokenizer\nfrom transformers import BertForSequenceClassification\n\nimport torch\nfrom torch.utils.data import TensorDataset, DataLoader, SequentialSampler\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport json\nimport requests\nimport random\nfrom datetime import datetime\nimport spacy\n\nfrom geopy.geocoders import Nominatim\n\n#-----\n#model\n#-----\n\nprint('get the model ready...')\n\nlabel_dict = {'bye': 0, 'cloud': 1, 'general_weather': 2, 'greeting': 3, 'rain': 4, 'sun_hours': 5, 'temperature': 6, 'unknown': 7, 'wind': 8}\n\n\n\nlabel_dict_inverse = {v: k for k, v in label_dict.items()}\n\nbert = BertForSequenceClassification.from_pretrained(\"bert-base-uncased\",\n num_labels=len(label_dict),\n output_attentions=False,\n output_hidden_states=False)\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\n#print(dir_path)\ndevice_location = 'cuda' if torch.cuda.is_available() else 'cpu'\n\nbert.load_state_dict(torch.load(f'{dir_path}/BERT.model', map_location=torch.device(device_location)))\n\ntokenizer = BertTokenizer.from_pretrained('bert-base-uncased',\n do_lower_case=True)\ndevice = torch.device(device_location)\n\n#-----------\n#entity recognition\n#-----------\n\nnlp = spacy.load(\"en_core_web_lg\")\n\n#---------\n#functions\n#---------\n\n\ndef get_intent(string):\n question = [string]\n\n data = {'Question': question}\n df = pd.DataFrame(data=data)\n value_to_predict = df.Question.values\n\n encoded_data = tokenizer.batch_encode_plus(\n value_to_predict,\n add_special_tokens=True,\n return_attention_mask=True,\n pad_to_max_length=True,\n max_length=256,\n return_tensors='pt'\n )\n\n input_id = encoded_data['input_ids']\n attention_mask = encoded_data['attention_mask']\n value_to_predict_tensor = TensorDataset(input_id, attention_mask)\n\n dataloader_prediction = DataLoader(value_to_predict_tensor,\n sampler=SequentialSampler(value_to_predict_tensor),\n batch_size=1)\n bert.eval()\n\n prediction = []\n\n for batch in dataloader_prediction:\n batch = tuple(b.to(device) for b in batch)\n\n inputs = {'input_ids': batch[0],\n 'attention_mask': batch[1]\n }\n\n with torch.no_grad():\n outputs = bert(**inputs)\n\n logits = outputs[0]\n logits = logits.detach().cpu().numpy()\n prediction.append(logits)\n\n prediction = np.concatenate(prediction, axis=0)\n\n prediction_flat = np.argmax(prediction, axis=1).flatten()\n\n intent = prediction_flat[0]\n #print(prediction_flat[0])\n #print(type(prediction_flat[0]))\n return intent\n\n\ndef entity_recognition(string):\n doc = nlp(string)\n location = ''\n time = ''\n for ent in doc.ents:\n label = ent.label_\n content = ent.text\n if label == 'GPE':\n location = content\n elif label == 'DATE':\n time = content\n if location == '':\n location = 'Mannheim'\n\n return location, time\n\n\ndef get_weather(city_name):\n api_key = \"1977d0c01a9cead345257efcc246e9ae\"\n part = 'minutely'\n\n address = city_name\n geolocator = Nominatim(user_agent=\"Your_Name\")\n location = geolocator.geocode(address)\n lat = location.latitude\n lon = location.longitude\n\n response = requests.get(f'https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude={part}&appid={api_key}')\n data = json.loads(response.text)\n return data\n\n\ndef get_general_weather(location, time):\n if location == '':\n city_name = 'Mannheim'\n else:\n city_name = location\n\n weather = get_weather(city_name)\n try:\n alerts = weather ['alerts']\n except KeyError:\n alerts = ''\n\n if time == '' or time == 'today':\n data = weather['daily'][0]\n elif time == 'tomorrow':\n data = weather['daily'][1]\n else:\n data = weather['daily'][1]\n\n weather_data = {'temp_morn' : int(float(data['feels_like']['morn']) - 273.15),\n 'temp_eve' : int(float(data['feels_like']['eve']) - 273.15),\n 'temp_night' : int(float(data['feels_like']['night']) - 273.15),\n 'temp_day' : int(float(data['temp']['day']) - 273.15),\n 'temp_min' : int(float(data['temp']['min']) - 273.15),\n 'temp_max' : int(float(data['temp']['max']) - 273.15),\n 'temp_now': int(float(weather['current']['feels_like']) - 273.15),\n 'rain_prob' : int(float(data['pop']) * 100),\n 'clouds' : data['clouds'],\n 'wind' : data['wind_speed']}\n return weather_data, alerts\n\n\ndef get_rain(location, time):\n if location == '':\n city_name = 'Mannheim'\n else:\n city_name = location\n\n weather = get_weather(city_name)\n\n if time == '' or time == 'current':\n data = weather['current']\n if \"rain\" in data:\n rain = 'yes'\n rain_prob = 100\n else:\n rain = 'no'\n rain_prob = 0\n\n elif time == 'today':\n data = weather['hourly']\n\n prob_list = []\n hours = 7\n for hour in range(hours):\n prob = data[hour]['pop']\n prob_list.append(int(prob * 100))\n\n if (100 in prob_list):\n rain = 'yes'\n rain_prob = 100\n else:\n mean_prob = sum(prob_list) / len(prob_list)\n\n if mean_prob < 33:\n rain = 'no'\n rain_prob = mean_prob\n elif mean_prob >= 33 and mean_prob < 66:\n rain = 'maybe'\n rain_prob = mean_prob\n elif mean_prob >= 66:\n rain = 'yes'\n rain_prob = mean_prob\n\n elif time == 'tomorrow':\n prob = weather['daily'][1]['pop']\n if prob < 33:\n rain = 'no'\n rain_prob = prob\n elif prob >= 33 and prob < 66:\n rain = 'maybe'\n rain_prob = prob\n elif prob >= 66:\n rain = 'yes'\n rain_prob = prob\n\n else:\n rain = 'maybe'\n rain_prob = 50\n\n\n return rain, rain_prob\n\n\ndef get_temperature(location, time):\n if location == '':\n city_name = 'Mannheim'\n\n else:\n city_name = location\n\n weather = get_weather(city_name)\n\n if time == '':\n temp = int(weather['current']['temp'] - 273.15)\n\n elif time == 'today':\n temp = weather['daily'][0]['feels_like']\n\n elif time == 'tomorrow':\n temp = weather['daily'][1]['feels_like']\n\n else:\n temp = weather['daily'][1]['feels_like']\n\n return temp\n\ndef get_sun_hours(location, time):\n if location == '':\n city_name = 'Mannheim'\n else:\n city_name = location\n\n weather = get_weather(city_name)\n if time == '' or time == 'current':\n sunrise = pd.to_datetime(int(weather['current']['sunrise']), unit='s')\n sunset = pd.to_datetime(int(weather['current']['sunset']), unit='s')\n elif time == 'today':\n sunrise = pd.to_datetime(int(weather['daily'][0]['sunrise']), unit='s')\n sunset = pd.to_datetime(int(weather['daily'][0]['sunset']), unit='s')\n elif time == 'tomorrow':\n sunrise = pd.to_datetime(int(weather['daily'][1]['sunrise']), unit='s')\n sunset = pd.to_datetime(int(weather['daily'][1]['sunset']), unit='s')\n else:\n sunrise = pd.to_datetime(int(weather['daily'][0]['sunrise']), unit='s')\n sunset = pd.to_datetime(int(weather['daily'][0]['sunset']), unit='s')\n return sunrise, sunset, city_name\n\n#-----------\n#discord bot\n#-----------\n\nprint('starting the bot...')\n\n\n# usually implemented in an .env file\ndiscord_token = 'OTE1OTI1ODgyMzc0MzQwNjM4.Yaiscw.dDy4ShZak3_-L2WQZCtIO077Xoc'\ndiscord_server = '915925218504106004'\n# end of .env file\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n print(f'{client.user.name} has connected to Discord!')\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n\n content = message.content\n print(content)\n print(type(content))\n if content != '':\n channel = getattr(message, 'channel')\n\n intent = get_intent(content)\n\n# intent: Bye\n if intent == 0:\n bye_emoji = u'\\U0001F44B'\n responses = [f'Bye, have a nice day. {bye_emoji}',\n f'Bye bye {bye_emoji}',\n f'Farewell traveler {bye_emoji}']\n response = random.choice(responses)\n\n# intent cloud\n elif intent == 1:\n location, time = entity_recognition(content)\n\n data, alerts = get_general_weather(location, time)\n\n sun_emoji = u'\\U00002600'\n cloud_emoji = u'\\U00002601'\n cloud_and_sun_emoji = u'\\U000026C5'\n\n if data['clouds'] < 33:\n responses = [f'{sun_emoji} It is sunny in {location.capitalize()}',\n f'{sun_emoji} Take your sunglasses out. In {location.capitalize()} it is blue sky',\n f'{sun_emoji} The sky is blue in {location.capitalize()}.'\n ]\n elif data['clouds'] >= 33 and data['clouds'] < 66:\n responses = [f'{cloud_and_sun_emoji} A little bit from both sides in {location.capitalize()}.',\n f'{cloud_and_sun_emoji} Partly sunny, partly cloudy in {location.capitalize()}.',\n f'{cloud_and_sun_emoji} In {location.capitalize()} it is not really sunny but not really cloudy either.'\n ]\n else:\n responses = [f'{cloud_emoji} No sun today in {location.capitalize()}.',\n f'{cloud_emoji} Clouds, clouds and more clouds in {location.capitalize()}.',\n f'{cloud_emoji} In {location.capitalize()} it is super cloudy.'\n ]\n\n response = random.choice(responses)\n\n# intent general_weather\n elif intent == 2:\n location, time = entity_recognition(content)\n\n sun_emoji = u'\\U00002600'\n cloud_emoji = u'\\U00002601'\n cloud_and_sun_emoji = u'\\U000026C5'\n thermo_emoji = u'\\U0001F321'\n little_rain_emoji = u'\\U0001F326'\n rain_emoji = u'\\U0001F327'\n wind_emoji = u'\\U0001F32C'\n\n if time == '':\n time = 'today'\n data, alerts = get_general_weather(location, time)\n #response beginning\n #temperature\n string = f\"{time.capitalize()} the temperature in {location.capitalize()} ranges between {data['temp_min']}°C and {data['temp_max']}°C. {thermo_emoji}\"\n\n if time == 'today':\n string += f\"\\nRight now the temperature is {data['temp_now']}C°. {thermo_emoji}\"\n\n # cloudyness\n string += f\"\\n{time.capitalize()} \"\n if data['clouds'] < 33:\n string += f\"it is sunny. {sun_emoji}\"\n elif data['clouds'] >= 33 and data['clouds'] < 66:\n string += f\"it is partly sunny and cloudy. {cloud_and_sun_emoji}\"\n else:\n string += f\"it is very cloudy. {cloud_emoji}\"\n\n # rain\n string += f\"\\nFurthermore the probability for rain is {data['rain_prob']}%, so \"\n if data['rain_prob'] < 33:\n string += f\"it will not rain {time}. {sun_emoji}\"\n elif data['rain_prob'] >= 33 and data['rain_prob'] < 66:\n string += f\"it might rain {time}. {little_rain_emoji}\"\n else:\n string += f\"it will rain {time}. {rain_emoji}\"\n # wind\n string += f\"\\nThe wind is {data['wind']} km/h fast. {wind_emoji}\"\n\n response = string\n\n# intent greeting\n elif intent == 3:\n hello_emoji = u'\\U0001F44B'\n responses = [f'Hi there {hello_emoji}',\n f'Hello {hello_emoji}',\n f'Good day, sir. {hello_emoji}',\n f'Hello, what can I do for you? {hello_emoji}',\n f'Hey {hello_emoji}',\n f'Salute {hello_emoji}',\n f'Hello, my friend {hello_emoji}']\n response = random.choice(responses)\n\n# intent rain\n elif intent == 4:\n location, time = entity_recognition(content)\n rain, rain_prob = get_rain(location, time)\n\n if time == '':\n time = 'today'\n\n sun_emoji = u'\\U00002600'\n unbrella_emoji = u'\\U00002614'\n little_rain_emoji = u'\\U0001F326'\n rain_emoji = u'\\U0001F327'\n rain_coat_emoji = u'\\U0001F9E5'\n closed_umrella_emoji = u'\\U0001F302'\n\n if rain == 'yes':\n responses = [f'The rain-probability for {time} in {location.capitalize()} is {rain_prob}%, you should take an umbrella. {unbrella_emoji}',\n f'The rain-probability for {time} in {location.capitalize()} is {rain_prob}%. {rain_emoji}',\n f'The rain-probability for {time} in {location.capitalize()} is {rain_prob}%, take a raincoat. {rain_coat_emoji}'\n ]\n\n elif rain == 'no':\n responses = [f'The rain-probability for {time} in {location.capitalize()} is {rain_prob}%. You can safely leave your umbrella at home. {closed_umrella_emoji}',\n f'The rain-probability for {time} in {location.capitalize()} is {rain_prob}%. {sun_emoji}',\n f\"The rain-probability for {time} in {location.capitalize()} is {rain_prob}%. You don't need a raincoat. {sun_emoji}\",\n f\"Keep calm, no rain {time}! {sun_emoji}\"\n ]\n\n elif rain == 'maybe':\n responses = [f'In {location.capitalize()}? Maybe yes, maybe no. Could be both. {little_rain_emoji}',\n f'In {location.capitalize()}? Maybe. Better keep your umbrella ready. {unbrella_emoji}',\n f'It might rain in {location.capitalize()} {time}, the probability is {rain_prob}%. {little_rain_emoji}'\n ]\n\n response = random.choice(responses)\n\n# intent sun_hours\n elif intent == 5:\n location, time = entity_recognition(content)\n sunrise, sunset, city_name = get_sun_hours(location, time)\n #print(sunrise)\n #print(sunset)\n sunrise = str(sunrise)[11:]\n sunset = str(sunset)[11:]\n\n sunrise_emoji = u'\\U0001F305'\n sunset_amoji = u'\\U0001F307'\n\n responses = [f'{sunrise_emoji} In {location.capitalize()} sunrise will be at {sunrise} UTC. \\n{sunset_amoji} Sunset will be at {sunset} UTC.',\n f'{time.capitalize()} the sun in {location} will rise {sunrise_emoji} at {sunrise} and set {sunset_amoji} at {sunset} UTC.'\n f'{sunrise_emoji} The sun will rise in the morning at {sunrise} \\n{sunset_amoji} and set in the evening at {sunset} UTC.',\n f\"Why the hell are you asking, you nerd. You'll stay at home anyway. But if you really want to know ask again.\"]\n response = random.choice(responses)\n\n# intent temperature\n elif intent == 6:\n location, time = entity_recognition(content)\n temp = get_temperature(location, time)\n\n thermo_emoji = u'\\U0001F321'\n\n if time == '':\n responses = [f'{thermo_emoji} Right now the temperature is {temp}°C',\n f'{thermo_emoji} In {location} the temperature is {temp}°C',\n f'{thermo_emoji} Outside it is {temp}°C']\n\n elif time == 'today':\n avg_temperature = int(((temp['morn'] - 273.15) + (temp['day'] - 273.15) + (temp['eve'] - 273.15) +\n (temp['night'] - 273.15))/4)\n temp_day = int(temp['day'] - 273.15)\n temp_morn = int(temp['morn'] - 273.15)\n temp_eve = int(temp['eve'] - 273.15)\n temp_night = int(temp['night'] - 273.15)\n responses = [f\"{thermo_emoji} Today the average temperature is {avg_temperature}°C\",\n f\"{thermo_emoji} In the morning it is {temp_morn}°C \\n{thermo_emoji} During the day it is {temp_day}°C \\n{thermo_emoji} In the evening it is {temp_eve}°C \\n{thermo_emoji} In the night it is {temp_night}°C\",\n f\"{thermo_emoji} Today the temperature will rise up to {temp_day}°C\"]\n\n elif time == 'tomorrow':\n avg_temperature = int(((temp['morn'] - 273.15) + (temp['day'] - 273.15) + (temp['eve'] - 273.15) +\n (temp['night'] - 273.15)) / 4)\n temp_day = int(temp['day'] - 273.15)\n temp_morn = int(temp['morn'] - 273.15)\n temp_eve = int(temp['eve'] - 273.15)\n temp_night = int(temp['night'] - 273.15)\n responses = [f\"{thermo_emoji} Tomorrow the average temperature is {avg_temperature}°C\",\n f\"{thermo_emoji} Tomorrow in the morning it will be {temp_morn}°C \\n{thermo_emoji} During the day it will be {temp_day}°C \\n{thermo_emoji} In the evening it will be {temp_eve}°C \\n{thermo_emoji} In the night it will be {temp_night}°C\",\n f\"{thermo_emoji} Tomorrow the temperature will rise up to {temp_day}°C\"]\n\n response = random.choice(responses)\n\n# intent unknown\n elif intent == 7:\n\n exploding_head_emoji = u'\\U0001F92F'\n skull_emoji = u'\\U0001F480'\n nerd_emoji = u'\\U0001F913'\n monokle_emoji = u'\\U0001F9D0'\n robot_emoji = u'\\U0001F916'\n\n responses = [f\"{label_dict_inverse.get(intent)}, sorry can't help you! {monokle_emoji}\",\n f\"Sorry, I don't know what you mean, please try again {skull_emoji}\",\n f\"BEEP BOOP, I am a robot and can tell you only about the weather {robot_emoji}\",\n f\"Help = No, Try again soon. {robot_emoji}\",\n f\"I don't really feel like answering you right now {nerd_emoji}\",\n f\"Me and Google know everything, for this question you should consult Google. {nerd_emoji}\",\n f\"Sorry I am too underpaid for this shit! {exploding_head_emoji}\",\n f\"Shit I don't know. {exploding_head_emoji}\",\n f\"Bother Siri with this your stuff. {skull_emoji}\"]\n response = random.choice(responses)\n\n# intent windy\n elif intent == 8:\n location, time = entity_recognition(content)\n data, alerts = get_general_weather(location, time)\n wind = data['wind']\n\n wind_emoji = u'\\U0001F32C'\n tornado_emoji = u'\\U0001F32A'\n no_wind_emoji = u'\\U0001F32B'\n\n\n if time == '':\n time = 'right now'\n print(wind)\n if wind <= 3:\n responses = [f'{no_wind_emoji} There is no wind in {location.capitalize()}. The wind speed is {wind}km/h',\n f'{no_wind_emoji} No wind in {location.capitalize()} {time}.',\n f'{no_wind_emoji} There is no wind in {location.capitalize()}.']\n elif wind <= 10:\n responses = [f'{wind_emoji} It is a soft breeze in {location.capitalize()}. The wind speed is {wind}km/h.',\n f'{wind_emoji} There is a soft breeze in {location.capitalize()} {time}.',\n f'{no_wind_emoji} A nice chilly breeze outside.']\n\n elif wind > 10:\n responses = [f'{tornado_emoji} It is windy. The wind speed is {wind}km/h.',\n f'{tornado_emoji} It is a very windy in {location.capitalize()} {time}.',\n f'{tornado_emoji} Maybe there is a hurrican in {location.capitalize()} {time}, because the wind speed is {wind}km/h.']\n\n response = random.choice(responses)\n\n await channel.send(response)\n\n\n\n\nclient.run(discord_token)","repo_name":"yannik-cyber/nlp_weatherman","sub_path":"discord_bot.py","file_name":"discord_bot.py","file_ext":"py","file_size_in_byte":20649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"41292323751","text":"from emailTest113 import Create_Email\nfrom dbfunc import Database_Connect, Query_Call\nimport smtplib\n\n\nif __name__ == '__main__':\n\n database = 'mydb.employee'\n cursor = Database_Connect('localhost', 'mydb', 'root', 'rabel1986')\n result = Query_Call(cursor, database)\n\n for obj in result:\n data = obj[0]\n print(obj)\n message = Create_Email(data)\n\n try:\n smtp_host = smtplib.SMTP(\"smtp.office365.com\", 587)\n smtp_host.ehlo()\n smtp_host.starttls()\n smtp_host.login(\"dominicandaddy_nyc@hotmail.com\", 'rdc_23?')\n smtp_host.sendmail(\"dominicandaddy_nyc@hotmail.com\", \"rabeldelcastillo23@gmail.com\", message.as_string())\n smtp_host.quit()\n\n print(\"Success\")\n except:\n print(\"Failed\")\n","repo_name":"rabeld1986/webApps","sub_path":"Extract_Comparison.py","file_name":"Extract_Comparison.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"948233677","text":"class Solution:\n def searchInsert(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n lens = len(nums)\n if(lens == 0): return 0\n\n for i,n in enumerate(nums):\n if(n >= target):\n return i\n\n return lens\n\ninput_list = [3,12,14,17]\nob1 = Solution()\nprint(ob1.searchInsert(input_list, 15))","repo_name":"Olixpin/Altschool-LeetCode-Algorithm","sub_path":"Tope/Day4/searchInsert.py","file_name":"searchInsert.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"33"} +{"seq_id":"22432214575","text":"\"\"\"\nWrite a Python function to check whether a string is pangram or not. (Assume the string passed in does not have any punctuation)\n\nNote : Pangrams are words or sentences containing every letter of the alphabet at least once.\nFor example : \"The quick brown fox jumps over the lazy dog\"\n\nHint: You may want to use .replace() method to get rid of spaces.\n\nHint: Look at the string module\n\nHint: In case you want to use set comparisons\n\nimport string\n\ndef ispangram(str1, alphabet=string.ascii_lowercase):\n pass\nispangram(\"The quick brown fox jumps over the lazy dog\")\nTrue\nstring.ascii_lowercase\n'abcdefghijklmnopqrstuvwxyz'\n\n\nimport string\n\ndef ispangram(str1, alphabet=string.ascii_lowercase):\n # Create a set of the alphabet\n alphaset = set(alphabet)\n\n # Remove spaces from str1\n str1 = str1.replace(\" \",'')\n\n # Lowercase all strings in the passed in string\n # Recall we assume no punctuation\n str1 = str1.lower()\n\n # Grab all unique letters in the string as a set\n str1 = set(str1)\n\n # Now check that the alpahbet set is same as string set\n return str1 == alphaset\n\n\"\"\"\nimport string\ndef ispangram(str1, alphabet=string.ascii_lowercase):\n\n str1 = str1.replace(\" \",\"\")\n st = str1.lower()\n sorted_list = list(set(st))\n sorted_list.sort()\n s = \"\".join(sorted_list)\n if s == alphabet:\n return True\n\n\n\nprint(ispangram(\"The quick brown fox jumps over the lazy dog\"))\n\n\n","repo_name":"saikumarlaishetty/Practise","sub_path":"Practise/HerotoZero/Projects 1-3/pangrams.py","file_name":"pangrams.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"5757757306","text":"\n\ndef format_to_json(author_GUID, author_name, reviewer_GUID, reviewer_name, question, options, hint, correct_answer, option_count):\n '''\n This function formatts the data into JSON dictionary\n List Of Parameters\n author_GUID, - String\n author_name, - String\n reviewer_GUID, - String\n reviewer_name, - String\n question, - LaTex Formatted String\n options, - LaTex Formatted String list\n hint, - String\n correct_answer, LaTex Formatted String\n option_count - Integer\n '''\n data = {};\n data={\"content\" : question, \"answer\":[], \"hint\": hint, \"credits\": {\n \"author\": { \"id\": author_GUID, \"name\": author_name},\n \"reviewer\": { \"id\": reviewer_GUID, \"name\": reviewer_name}\n }};\n\n for i in range(option_count):\n answer_dict = {}\n answer_dict[\"id\"] = i+1;\n answer_dict[\"value\"] = (options[i]);\n if(options[i] == correct_answer):\n answer_dict[\"is_key\"] = True\n data[\"answer\"].append(answer_dict) \n\n return data \n\n","repo_name":"myself-karthick/Aptitude-Question-Generator","sub_path":"JSON_Data_Formatter.py","file_name":"JSON_Data_Formatter.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"30267942572","text":"\"\"\"\nsvm --- LIBSVM\nhttps://blog.csdn.net/River_J777/article/details/107469726\n\"\"\"\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom libsvm.svmutil import *\n\n\ndef get_data(file_name):\n \"\"\"\n 读取数据\n :param file_name: 数据文件\n :return: y, x\n \"\"\"\n label_y, data_x = svm_read_problem(file_name)\n return label_y, data_x\n\n\ndef svm_linear(data_x, label_y):\n \"\"\"\n svm线性核模型训练\n :param data_x: 数据属性\n :param label_y: 标签\n :return: 训练好的模型\n \"\"\"\n print(\"model:\")\n # 线性核\n model = svm_train(label_y, data_x, '-t 0 -c 100')\n svm_save_model('Linear.model', model)\n return model\n\n\ndef svm_gauss(data_x, label_y):\n \"\"\"\n svm高斯核模型训练\n :param data_x: 数据属性\n :param label_y: 标签\n :return: 训练好的模型\n \"\"\"\n print(\"model:\")\n # 高斯核\n model = svm_train(label_y, data_x, '-t 2 -c 100')\n svm_save_model('Gauss.model', model)\n return model\n\n\ndef plot(data_x, label_y, model):\n \"\"\"\n 绘制分类图\n :param data_x: 数据属性\n :param label_y: 标签\n :param model: 训练好的模型\n :return: null\n \"\"\"\n x_np = np.asarray([[xi[1], xi[2]] for xi in data_x])\n # print(x_np)\n\n n, m = 200, 200 # 横纵各采样多少个值\n x1_min, x2_min = np.min(x_np, axis=0) # 列最小值\n x1_max, x2_max = np.max(x_np, axis=0) # 列最大值\n\n t1 = np.linspace(x1_min, x1_max, n) # 在min-max间线性采样\n t2 = np.linspace(x2_min, x2_max, m)\n\n x1, x2 = np.meshgrid(t1, t2) # 生成网格采样点\n x_show = np.stack((x1.flat, x2.flat), axis=1) # 测试点\n\n print(\"predict:\")\n y_fake = np.zeros((n * m,))\n y_predict, _, _ = svm_predict(y_fake, x_show, model)\n # print(y_predict)\n\n # 绘制分类图\n cm = mpl.colors.ListedColormap(['#A0A0FF', '#FFA0A0'])\n plt.pcolormesh(x1, x2, np.array(y_predict).reshape(x1.shape), cmap=cm)\n plt.scatter(x_np[:, 0], x_np[:, 1], c=label_y, s=3, marker='o')\n plt.xlabel(\"x1\")\n plt.ylabel(\"x2\")\n plt.title(\"svm\")\n plt.show()\n\n\nif __name__ == '__main__':\n y, x = get_data('db/data_6_2.txt')\n model_linear = svm_linear(x, y)\n model_gauss = svm_gauss(x, y)\n plot(x, y, model_linear)\n plot(x, y, model_gauss)\n","repo_name":"akumondo/machine-learning","sub_path":"homework05/h6_2svm.py","file_name":"h6_2svm.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"8251987181","text":"#trabalhando com arquivos\n\n'''\narq = open('meu_arquivo.txt','w')\narq.write('novo\\n')\narq.write('outra linha')\narq.close()\n'''\n\n'''\nwith para não necessita usar o close obrigatoriamente, pois o mesmo já\nfecha o arquivo, tanto para escrever quanto para lê.\nwith 'meu_arquivo.txt' as arq:\n for linha in arq.readlines():\n print(linha)\n''' \n\narq = open('meu_arquivo.txt','r')\nfor linha in arq.readlines():\n print(linha)\n \narq.close()\n\ndicio ={}\narq = open('dados.txt','r')\nfor linha in arq.readlines:\n dados = linha[:-1].split(',')\n chave = dicio[0]\n chave = dicio[1]\n valor = int(dados[1])\n dicio[chave] = valor\n arq.close()\n \nprint(dicio)\n","repo_name":"IsraelLima25/Curso-Python","sub_path":"Aula3/arquivo.py","file_name":"arquivo.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"75362998175","text":"#!/usr/bin/python3\nimport random\nnumber = random.randint(-10000, 10000)\nif number < 0:\n digit = ((number * -1) % 10) * -1\nelse:\n digit = number % 10\n\nif digit > 5:\n words = \"greater than 5\"\nelif digit == 0:\n words = \"0\"\nelif digit < 6 and digit != 0:\n words = \"less than 6 and not 0\"\n\nprint(\"Last digit of {:d} is {:d} and is {:s}\".format(number, digit, words))\n","repo_name":"dhreyes/holbertonschool-higher_level_programming","sub_path":"0x01-python-if_else_loops_functions/1-last_digit.py","file_name":"1-last_digit.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"25066846447","text":"import re\nimport gmpy2\n\n# Combination of logic used in prime-gap project as well as\n# prime-gap-list and prime-gap-record-server\n\n# Standard form | m * P# / d +- a\nMPDA_RE_1 = re.compile(r\"^(\\d+)\\*\\(?(\\d+)#\\)?/(\\d+)([+-]\\d+)$\")\n# primorial d | m * P# / d# +- a\nMPDA_RE_2 = re.compile(r\"^(\\d+)\\*(\\d+)#/(\\d+)#([+-]\\d+)$\")\n# two component d | m * P# / (d1 * d2) +- a\nMPDDA_RE_1 = re.compile(r\"^(\\d+)\\*(\\d+)#/\\((\\d+)\\*(\\d+)\\)([+-]\\d+)$\")\n# two comp primorial d | m * P# / (d# * d2) +- a\nMPDDA_RE_2 = re.compile(r\"^(\\d+)\\*(\\d+)#/\\((\\d+)#\\*(\\d+)\\)([+-]\\d+)$\")\n# No m | P# / d +- a\nPDA_RE_1 = re.compile(r\"^\\(?(\\d+)#\\)?/(\\d+)([+-]\\d+)$\")\n# No m, primorial d | P# / d# +- a\nPDA_RE_2 = re.compile(r\"^\\(?(\\d+)#\\)?/(\\d+)#([+-]\\d+)$\")\n# No d | M * P# +- a\nMPA_RE_1 = re.compile(r\"^(\\d+)\\*(\\d+)#([+-]\\d+)$\")\n# No m, no d | P# +- a\nPA_RE_1 = re.compile(r\"^(\\d+)#([+-]\\d+)$\")\n\n# power form | b ^ p +- a\nPOWER_BPA_RE_1 = re.compile(r\"^(\\d+)\\^(\\d+)([+-]\\d+)$\")\n# power form | m * b ^ p +- a\nPOWER_BPA_RE_2 = re.compile(r\"^(\\d+)\\*(\\d+)\\^(\\d+)([+-]\\d+)$\")\n\n\ndef primorial(k):\n # TODO assert k is actually prime\n return int(gmpy2.primorial(k))\n\n\ndef parse(num_str):\n # Remove all spaces\n num_str = re.sub(r\"\\s+\", \"\", num_str)\n\n if num_str.isdigit():\n return int(num_str)\n\n match = parse_primorial_standard_form(num_str)\n if match is not None:\n m, p, d, a = match\n P = primorial(p)\n K, rem = divmod(P, d)\n if rem != 0:\n return None\n return m * K + a\n\n num_match = POWER_BPA_RE_1.match(num_str)\n if num_match:\n b, p, a = map(int, num_match.groups())\n if b <= 0:\n # Order of operations is hard\n return None\n return b ** p + a\n\n num_match = POWER_BPA_RE_2.match(num_str)\n if num_match:\n m, b, p, a = map(int, num_match.groups())\n if b <= 0:\n # Order of operations is hard\n return None\n return m * b ** p + a\n return None\n\n\ndef parse_primorial_standard_form(num_str):\n '''Return (m, P, d, a) => m * P#/d + a, (with a < 0)'''\n\n # Remove all spaces\n num_str = re.sub(r\"\\s+\", \"\", num_str)\n\n # The most cannonical form IMHO\n match = MPDA_RE_1.match(num_str)\n if match:\n m, p, d, a = map(int, match.groups())\n return (m, p, d, a)\n\n match = MPDA_RE_2.match(num_str)\n if match:\n m, p, dp, a = map(int, match.groups())\n D = primorial(dp)\n return (m, p, D, a)\n\n match = MPDDA_RE_1.match(num_str)\n if match:\n m, p, d1, d2, a = map(int, match.groups())\n D = d1 * d2\n return (m, p, D, a)\n\n match = MPDDA_RE_2.match(num_str)\n if match:\n m, p, d1, d2, a = map(int, match.groups())\n D = primorial(d1) * d2\n return (m, p, D, a)\n\n match = PDA_RE_1.match(num_str)\n if match:\n p, d, a = map(int, match.groups())\n return (1, p, d, a)\n\n match = PDA_RE_2.match(num_str)\n if match:\n p, dp, a = map(int, match.groups())\n D = primorial(dp)\n return (1, p, D, a)\n\n match = MPA_RE_1.match(num_str)\n if match:\n m, p, a = map(int, match.groups())\n return (m, p, 1, a)\n\n match = PA_RE_1.match(num_str)\n if match:\n p, a = map(int, match.groups())\n return (1, p, 1, a)\n\n return None\n","repo_name":"sethtroisi/prime-gap-verify","sub_path":"primegapverify/parsenumber.py","file_name":"parsenumber.py","file_ext":"py","file_size_in_byte":3399,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"34"} +{"seq_id":"25564520570","text":"#!/usr/bin/python\n# This programme takes as input a number of string hex strings, trys all 256 keys for a single key\n# XOR on each input string and returns the most likely plaintext out of all inputs and keys.\n\nfrom matasano.util.converters import *\nfrom matasano.set1.c3 import *\n\n# Takes a byte string and returns the most likely plaintext and key.\ndef decryptsinglexor(input1):\n\n byte_input = hex_to_bytestr(input1) #Changes input to bytes\n potential_keys = []\n\n for k in range (0,256):\n potential_keys.append(chr(k))\n\n for k in potential_keys:\n decrypted = decrypt(k,byte_input)\n if not valid_characters(decrypted):\n potential_keys.remove(k)\n\n #print('\\n Keys which return invalid decryptions filtered out.')\n #print ('Current potential keys:', potential_keys)\n #print ('Current number of potential keys:', len(potential_keys))\n\n candidate_plaintext={}\n\n for k in potential_keys:\n candidate_plaintext[k]=decrypt(k,byte_input)\n\n Score={}\n\n for k in potential_keys:\n Score[k]=score_string(candidate_plaintext[k])\n\n key=max(Score, key=Score.get)\n\n #print(candidate_plaintext[key])\n #print('Key: ', chr(key))\n #return candidate_plaintext\n return(key, candidate_plaintext[key])\n\nif __name__ == '__main__':\n\n # Takes the file and converts it into a list\n text_file = open(\"matasano/set1/strings.txt\");\n inputlist = text_file.read().splitlines();\n\n\n plaintextscores = {}\n # A dictionary keeping track of the keys and the plaintexts\n\n #For each value in the input list, this enters into the dictionary the most likely plaintext\n # along with the plaintext score.\n for input in inputlist:\n (working_key, working_plaintext) = decryptsinglexor(input)\n working_score = score_string(working_plaintext)\n #print(\"Working key:\", working_key)\n #print (\"Working plaintext:\", working_plaintext)\n #print (\"Working score:\", working_score)\n plaintextscores[working_plaintext] = working_score\n\n # To pring the dictionary listing all the plaintexts and their scores\n # print (\"This is the dictionary:\", plaintextscores)\n\n # This searches the dictionary for the highest plaintext score and sets it equal to maxscore\n maxscore = max(plaintextscores.values())\n # print (\"Max score:\", maxscore)\n\n # This defines the winning plaintext to be the plaintext corresponding to the\n # highest plaintext score (maxscore) in the dictionary\n winning_plaintext = [x for x,y in plaintextscores.items() if y ==maxscore]\n\n\n print (\"And the winning plaintext is...\", winning_plaintext[0])\n","repo_name":"TheLunchtimeAttack/matasano-challenges","sub_path":"python/matasano/set1/c4.py","file_name":"c4.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"34"} +{"seq_id":"36773005568","text":"import math\nimport torch\nfrom torch import nn\nfrom torch.nn import init\nimport torch as T\nimport torch.nn.functional as F\nfrom models.modules.S4 import S4Block\nfrom models.utils import reverse\n\n\nclass S4DWrapper(nn.Module):\n def __init__(self, config):\n super(S4DWrapper, self).__init__()\n self.config = config\n self.hidden_dim = config[\"hidden_size\"]\n self.norm = config[\"norm\"]\n self.dropout = config[\"s4_dropout\"]\n self.prenorm = config[\"prenorm\"]\n\n self.S4DBlock = S4Block(d_model=2 * self.hidden_dim,\n bidirectional=False,\n mode=\"diag\",\n init=\"diag-inv\",\n disc=\"bilinear\",\n final_act=None,\n transposed=False,\n freeze_B=False,\n dropout=self.dropout,\n tie_dropout=True,\n lr=min(1e-3, config[\"lr\"]))\n\n self.GLU = nn.Sequential(nn.Linear(2 * self.hidden_dim, 2 * self.hidden_dim),\n nn.GLU())\n if self.norm == \"batch\":\n self.NT = nn.BatchNorm1d(self.hidden_dim)\n elif self.norm == \"skip\":\n pass\n else:\n self.NT = nn.LayerNorm(self.hidden_dim)\n\n def normalize(self, state):\n if self.norm == \"batch\":\n return self.NT(state.permute(0, 2, 1).contiguous()).permute(0, 2, 1).contiguous()\n elif self.norm == \"skip\":\n return state\n else:\n return self.NT(state)\n\n def forward(self, input, input_mask):\n N, S, D = input.size()\n input_mask = input_mask.view(N, S, 1)\n\n state = input\n res = input.clone()\n\n if self.prenorm:\n state = self.normalize(state)\n\n lengths = T.sum(input_mask, dim=1).view(N)\n\n fstate = state.clone()\n bstate = state.clone()\n\n count_zeros = T.sum(1 - input_mask, dim=1).view(N).long()\n count_zeros_end = count_zeros + S\n\n reverse_bstate = reverse(bstate, count_zeros, count_zeros_end)\n state = T.cat([fstate, reverse_bstate], dim=-1)\n\n state, _ = self.S4DBlock(x=state, lengths=lengths)\n assert state.size() == (N, S, 2 * D)\n\n fstate = state[..., 0:D]\n reverse_bstate = state[..., D:]\n bstate = reverse(reverse_bstate, count_zeros, count_zeros_end)\n state = T.cat([fstate, bstate], dim=-1)\n\n assert state.size() == (N, S, 2 * D)\n\n state = self.GLU(state)\n assert state.size() == (N, S, D)\n\n state = state + res\n if not self.prenorm:\n state = self.normalize(state)\n assert state.size() == (N, S, D)\n\n global_state = None\n aux_loss = None\n\n return {\"sequence\": state,\n \"global_state\": global_state,\n \"input_mask\": input_mask,\n \"aux_loss\": aux_loss}","repo_name":"JRC1995/BeamRecursionFamily","sub_path":"models/encoders/S4DWrapper.py","file_name":"S4DWrapper.py","file_ext":"py","file_size_in_byte":3029,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"34"} +{"seq_id":"19342851853","text":"# -*- coding:UTF-8 -*-\r\n\r\n\r\nimport logging\r\nimport time, os, sys\r\nimport pytest\r\n\r\nfrom ixnetwork_restpy import Files\r\nfrom common.reboot import logger\r\nfrom common.ixia.ixia_helpers import *\r\nfrom common.helpers.assertions import pytest_assert\r\n\r\n\r\n\"\"\"\r\nTO UPDATE\r\n\"\"\"\r\npytestmark = [pytest.mark.disable_loganalyzer]\r\ndef test_ixia_demo_warm_reboot(ixiahost,testbed, duthost):\r\n \r\n ###############################################################\r\n # STEP1: 准备预置条件\r\n ###############################################################\r\n \r\n #1.1 и®ѕзЅ®е…Ёе±Ђз»“жћњпјЊй»�认为True, 如果中间检测点不通过,将该值更新为False\r\n result = True \r\n \r\n #1.2 设置测试仪表IxNetwork配置文件名称,建议和测试例函数同名\r\n configFile = os.path.join(os.path.dirname(__file__), sys._getframe().f_code.co_name + '.ixncfg')\r\n #logger.info(configFile)\r\n \r\n #1.4 获取拓扑连接信息,获得intf, vlanid, е…¶дё­intfз”ЁдєЋй…ЌзЅ®DUT, vlanid用于更新测试仪表配置文д»��\r\n logger_msg(u'获取拓扑连接信息。')\r\n intf, vlanid = get_connection_info(testbed)\r\n\r\n #1.5 е€›е»єIxia session, иї”е›ћsession句柄和测试环境中要使用的端口信息\r\n logger_msg(u'е€›е»є Ixia Session IPгЂ‚') \r\n session, portList = ixiahost \r\n \r\n \r\n ###############################################################\r\n # STEP2: 测试仪表相关操作\r\n ###############################################################\r\n \r\n #2.1: еЉ иЅЅд»ЄиЎЁй…ЌзЅ®ж–‡д»¶\r\n logger_msg(u'еЉ иЅЅй…ЌзЅ®ж–‡д»¶гЂ‚')\r\n load_config(session, configFile)\r\n \r\n #2.2: й…ЌзЅ®license server\r\n logger_msg(u'й…ЌзЅ®License serverдїЎжЃЇгЂ‚')\r\n licenseInfo = get_ixia_license(testbed, duthost)\r\n config_license_server(session, licenseInfo)\r\n \r\n \r\n #2.3: еЌ з”Ёз«ЇеЏЈ\r\n logger_msg(u'иїћжЋҐжњєжЎ†пјЊејЂе§‹жЉўеЌ з«ЇеЏЈ%s' % portList)\r\n reserve_port(session, portList)\r\n \r\n #2.4: 开启协议仿真进行测试\r\n logger_msg(u'测试仪开启ARPеє”з­”пјЊдё»еЉЁеЏ‘йЂЃARP请求。')\r\n logger_msg(u'е»єз«‹BGPй‚»е±…е…ізі», еЏ‘еёѓBGPи·Їз”±')\r\n start_protocols(session)\r\n #time.sleep(30)\r\n \r\n \r\n ###############################################################\r\n # STEP3: 检测协议状态\r\n ###############################################################\r\n #Step3: иѕ“е‡єеЌЏи®®зЉ¶жЂЃдїЎжЃЇ\r\n protocolStatistics = get_statistics(session, stat_view_name='Protocols Summary')\r\n logger_msg('\\n\\nProtocol STATS: {}\\n\\n'.format(protocolStatistics))\r\n \r\n bgpStatistics = get_statistics(session, stat_view_name='BGP Peer Per Port')\r\n logger_msg('\\n\\nBGP STATS: {}\\n\\n'.format(bgpStatistics))\r\n \r\n for rowNumber,protocolStat in enumerate(protocolStatistics.Rows):\r\n logger_msg('\\n\\nnProtocol STATS: {}\\n\\n'.format(protocolStat))\r\n if protocolStat['Sessions Down'] == '0':\r\n logger_msg(u'ж‰Ђжњ‰BGP Peerе·Із»Џе…ЁйѓЁе€°иѕѕEstablishedзЉ¶жЂЃ')\r\n else:\r\n result = False\r\n \r\n ###############################################################\r\n # STEP4: 测试仪表进行流量验证\r\n ###############################################################\r\n #4.1: 测试仪表发送流量\r\n logger_msg(u'Ixia测试仪表下发流量配置,发送路由验证流量。')\r\n start_traffic(session)\r\n time.sleep(10)\r\n\r\n #4.2:еђ‘dutеЏ‘йЂЃwarm reboot命令\r\n logger_msg(u'设备进行warm rebootж“ЌдЅњ')\r\n duthost.shell('sudo config save -y')\r\n duthost.shell('nohup warm-reboot >/dev/null 2>&1 &')\r\n #logger_msg(u'ез­‰е300з§)\r\n time.sleep(120)\r\n \r\n #4.3:检查BGPзЉ¶жЂЃ\r\n protocolSummary = session.StatViewAssistant('Protocols Summary')\r\n protocolSummary.CheckCondition('Sessions Not Started', protocolSummary.EQUAL, 0)\r\n protocolSummary.CheckCondition('Sessions Down', protocolSummary.EQUAL, 0)\r\n logger_msg(u'ж‰Ђжњ‰BGP Peerе·Із»ЏжЃўе¤ЌEstablishedзЉ¶жЂЃ')\r\n \r\n #4.4: 测试仪表停止流量\r\n logger_msg(u'Ixia测试仪表停止流量。')\r\n stop_traffic(session)\r\n \r\n #4.5: 获取流量统计结果,并打印收发端口,收发报文数, дёўеЊ…ж—¶й•ї\r\n logger_msg(u'Ixia测试仪表根据需求按照Flowз»џи®Ўж–№ејЏе®ље€¶з»џи®Ўз»“жћњгЂ‚')\r\n flowStatistics = get_traffic_statistics(session, \"Flow Statistics\")\r\n for rowNumber,flowStat in enumerate(flowStatistics.Rows):\r\n logger_msg('\\n\\nSTATS: {}\\n\\n'.format(flowStat))\r\n logger_msg('\\nRow:{} TxPort:{} RxPort:{} TxFrames:{} RxFrames:{} Packet Loss Duration (ms):{}\\n'.format(\r\n rowNumber, flowStat['Tx Port'], flowStat['Rx Port'],\r\n flowStat['Tx Frames'], flowStat['Rx Frames'], flowStat['Packet Loss Duration (ms)']))\r\n \r\n \r\n #4.5: 查看设备warm rebootж”¶ж•›ж—¶й—ґ\r\n logger.info('Packet Loss Duration (ms)пјљ' + flowStat['Packet Loss Duration (ms)'])\r\n \r\n stop_protocols(session)\r\n \r\n ###############################################################\r\n # STEP5: 设置最终结果,判断测试例ж�Їеђ¦йЂљиї‡\r\n ###############################################################\r\n pytest_assert(result == True, 'Test case test_ixia_demo failed')\r\n\r\n\r\n","repo_name":"stayyule/sonic-test","sub_path":"tests/ixia/test_ixia_demo_warm_reboot.py","file_name":"test_ixia_demo_warm_reboot.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"34"} +{"seq_id":"1360589339","text":"\"\"\"\nProblem Link: https://leetcode.com/problems/binary-tree-right-side-view/\n\nGiven a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you \ncan see ordered from top to bottom.\n\nExample:\n\nInput: [1,2,3,null,5,null,4]\nOutput: [1, 3, 4]\nExplanation:\n\n 1 <---\n / \\\n2 3 <---\n \\ \\\n 5 4 <---\n\"\"\"\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 res = []\n \n def helper(root, level):\n if not root:\n return\n \n if level >= len(res):\n res.append(root.val)\n helper(root.right, level+1)\n helper(root.left, level+1)\n \n helper(root, 0)\n return res\n\n\nclass Solution1:\n def rightSideView(self, root: TreeNode) -> List[int]:\n if not root:\n return\n \n res, queue = [], [root]\n \n while queue:\n new_level = []\n temp_val = None\n \n for node in queue:\n if node.left:\n new_level.append(node.left)\n if node.right:\n new_level.append(node.right)\n \n res.append(queue[-1].val)\n queue = new_level if new_level else None\n \n return res","repo_name":"anantkaushik/leetcode","sub_path":"199-binary-tree-right-side-view.py","file_name":"199-binary-tree-right-side-view.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"34"} +{"seq_id":"27631465466","text":"from project.band_members.guitarist import Guitarist\nfrom project.band_members.drummer import Drummer\nfrom project.band_members.singer import Singer\nfrom project.band import Band\nfrom project.concert import Concert\n\n\nclass ConcertTrackerApp:\n def __init__(self):\n self.bands = []\n self.musicians = []\n self.concerts = []\n\n def create_musician(self, musician_type: str, name: str, age: int):\n if musician_type not in [\"Guitarist\", \"Drummer\", \"Singer\"]:\n raise ValueError(\"Invalid musician type!\")\n\n for musician in self.musicians:\n if musician.name == name:\n raise Exception(f\"{name} is already a musician!\")\n\n musician = None\n if musician_type == \"Guitarist\":\n musician = Guitarist(name, age)\n elif musician_type == \"Drummer\":\n musician = Drummer(name, age)\n elif musician_type == \"Singer\":\n musician = Singer(name, age)\n\n self.musicians.append(musician)\n return f\"{name} is now a {musician_type}.\"\n\n def create_band(self, name: str):\n for band in self.bands:\n if band.name == name:\n raise Exception(f\"{name} band is already created!\")\n\n band = Band(name)\n self.bands.append(band)\n return f\"{name} was created.\"\n\n def create_concert(self, genre: str, audience: int, ticket_price: float, expenses: float, place: str):\n for concert in self.concerts:\n if concert.place == place:\n raise Exception(f\"{place} is already registered for {concert.genre} concert!\")\n\n concert = Concert(genre, audience, ticket_price, expenses, place)\n self.concerts.append(concert)\n return f\"{genre} concert in {place} was added.\"\n\n def add_musician_to_band(self, musician_name: str, band_name: str):\n musician = None\n for m in self.musicians:\n if m.name == musician_name:\n musician = m\n break\n if musician is None:\n raise Exception(f\"{musician_name} isn't a musician!\")\n\n band = None\n for b in self.bands:\n if b.name == band_name:\n band = b\n break\n if band is None:\n raise Exception(f\"{band_name} isn't a band!\")\n\n band.add_member(musician)\n return f\"{musician_name} was added to {band_name}.\"\n\n def remove_musician_from_band(self, musician_name: str, band_name: str):\n band = None\n for b in self.bands:\n if b.name == band_name:\n band = b\n break\n if band is None:\n raise Exception(f\"{band_name} isn't a band!\")\n\n musician = None\n for m in band.members:\n if m.name == musician_name:\n musician = m\n break\n if musician is None:\n raise Exception(f\"{musician_name} isn't a member of {band_name}!\")\n\n band.remove_member(musician)\n return f\"{musician_name} was removed from {band_name}.\"\n\n def start_concert(self, concert_place: str, band_name: str) -> str:\n # Check if the band has at least one member of each type\n has_guitarist = False\n has_drummer = False\n has_singer = False\n for band in self.bands:\n if band.name == band_name:\n for member in band.members:\n if isinstance(member, Guitarist):\n has_guitarist = True\n elif isinstance(member, Drummer):\n has_drummer = True\n elif isinstance(member, Singer):\n has_singer = True\n if not has_guitarist or not has_drummer or not has_singer:\n raise Exception(f\"{band_name} can't start the concert because it doesn't have enough members!\")\n\n # Find the concert and band objects\n concert = None\n for c in self.concerts:\n if c.place == concert_place:\n concert = c\n break\n if concert is None:\n raise Exception(f\"No concert found in {concert_place}!\")\n\n band = None\n for b in self.bands:\n if b.name == band_name:\n band = b\n break\n if band is None:\n raise Exception(f\"No band found with name {band_name}!\")\n\n # Check if the band has the required skills to play at the concert\n if concert.genre == \"Rock\":\n for member in band.members:\n if isinstance(member, Guitarist) and not member.can_play_rock():\n raise Exception(f\"The {band_name} band is not ready to play at the concert!\")\n elif isinstance(member, Drummer) and not member.can_play_drums_with_sticks():\n raise Exception(f\"The {band_name} band is not ready to play at the concert!\")\n elif isinstance(member, Singer) and not member.can_sing_high_notes():\n raise Exception(f\"The {band_name} band is not ready to play at the concert!\")\n elif concert.genre == \"Metal\":\n for member in band.members:\n if isinstance(member, Guitarist) and not member.can_play_metal():\n raise Exception(f\"The {band_name} band is not ready to play at the concert!\")\n elif isinstance(member, Drummer) and not member.can_play_drums_with_sticks():\n raise Exception(f\"The {band_name} band is not ready to play at the concert!\")\n elif isinstance(member, Singer) and not member.can_sing_low_notes():\n raise Exception(f\"The {band_name} band is not ready to play at the concert!\")\n elif concert.genre == \"Jazz\":\n for member in band.members:\n if isinstance(member, Guitarist) and not member.can_play_jazz():\n raise Exception(f\"The {band_name} band is not ready to play at the concert!\")\n elif isinstance(member, Drummer) and not member.can_play_drums_with_brushes():\n raise Exception(f\"The {band_name} band is not ready to play at the concert!\")\n elif isinstance(member, Singer) and not (member.can_sing_high_notes() and member.can_sing_low_notes()):\n raise Exception(f\"The {band_name} band is not ready to play at the concert!\")\n\n profit = round((concert.audience * concert.ticket_price) - concert.expenses, 2)\n band.earn_profit(profit)\n\n return f\"{band_name} gained {profit}$ from the {concert.genre} concert in {concert_place}.\"\n\n","repo_name":"AygyunS/Python","sub_path":"SoftUni/OOP/Exams/19-Dec-22/1-2.StructureFunc/project/convert_tracker_app.py","file_name":"convert_tracker_app.py","file_ext":"py","file_size_in_byte":6600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"70317003298","text":"class stack :\n def __init__ (self, list = None) :\n if list == None :\n self.items = []\n else :\n self.items = list\n self.sizes = 0\n \n def __str__(self):\n s = \"stack of \" + str(self.size()) + ' items : '\n for ele in self.items:\n s+='\\n' + str(ele) + ' '\n\n return s\n \n def pop(self):\n if not self.isEmpty():\n self.sizes -= 1\n return self.items.pop()\n else :\n print(\"Stack is empty !!!\")\n\n def peek(self):\n return self.items[-1]\n\n def push (self,data):\n self.items.append(data)\n self.sizes += 1\n\n def isEmpty(self):\n return self.items==[]\n\n def size(self):\n return self.sizes\n\ns=stack()\n\ns.push('a')\n\ns.pop()\ns.pop()\n\ns.push('b')\ns.push('c')\nprint(s.isEmpty())\n\nprint(s.size())\nprint(s.items)\n\n\n","repo_name":"KerkaiwanMam/OBJECT-ORIENTED-DATA-STRUCTURES","sub_path":"HW03 Stack/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"8612156846","text":"import unittest\nimport logging\n# import hashlib\n# import hmac\n# import struct\nfrom itertools import imap\nfrom itertools import izip\nfrom hashlib import sha256\nimport random\nimport array\n\nfrom chumcrypt import ChumCipher\nfrom chumcrypt import SecretBox\nfrom chumcrypt import utils\n\n\n# logging.basicConfig(level=logging.ERROR)\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(': ***ChumCipher*** :')\n\n\nclass Test_SecretBox(unittest.TestCase):\n\n def _inc_one_random_byte(self, s):\n a = array.array('B', s)\n i = random.randint(0, len(a) - 1)\n a[i] = (a[i] + 1) % 0xff\n return a.tostring()\n\n def _get_multilayer_cipher(self, keys, msg):\n '''\n Chain len(keys) ChumCiphers on top of each other.\n Return the outmost cipher object.\n '''\n n = len(keys)\n nonsense = [sha256(key).digest() for key in keys]\n ciphers = []\n i = 0\n for (key, nonce) in izip(keys, nonsense):\n if i > 0:\n msg = ciphers[i - 1]\n ciphers += [ChumCipher(key, nonce, msg)]\n return ciphers[-1]\n\n def test_multilayer_cipher(self):\n '''\n Create a list of keys and two equal multi-layered ciphers from these\n keys.\n Send one message through both chains and finally validate integrity.\n Perform XOR-schism...\n '''\n msg = 'Welcome! how did you find your way in here?'\n keys = [utils.random(32) for _ in xrange(100)]\n m1 = self._get_multilayer_cipher(keys, msg)\n ciphertext = m1.read(len(msg))\n m2 = self._get_multilayer_cipher(keys, ciphertext)\n assert m2.read(len(msg)) == msg\n print(msg)\n\n def _recursive_boxes(self, keygen, n):\n orig_msg = 'Hello there, you again?!'\n boxes = []\n keys = [k for k in keygen]\n packages = []\n p = None\n #\n # Create n packages where package[n-1] equals the plaintext\n # of package[n].\n #\n for i in xrange(n):\n box = SecretBox(keys[i])\n if i == 0:\n msg = orig_msg\n else:\n msg = packages[i-1]\n p = box.encrypt(msg)\n packages.append(p)\n #\n # Decrypt each package p in packages. That is, n decrypt operations\n # for the first package, (n-1) for the second and so forth.\n # Assert success after each completed package series.\n #\n keys.reverse()\n packages.reverse()\n for i in xrange(len(packages)):\n p = packages[i]\n for key in keys[i:]:\n #\n # For each package, assert minor change causes HMAC validation\n # failure and thus an AssertionException.\n #\n box = SecretBox(key)\n try:\n q = self._inc_one_random_byte(p)\n box.decrypt(q)\n except AssertionError:\n pass\n else:\n raise Exception('Seal broken! more vet bills..')\n p = SecretBox(key).decrypt(p)\n assert p == orig_msg\n assert p == orig_msg\n print(p)\n\n def test_recursive_boxes(self):\n n = 20\n keygen = imap(lambda i: sha256(str(i)).digest(), xrange(n))\n self._recursive_boxes(keygen, n)\n\n def test_vary_msg_size(self):\n box = SecretBox(utils.gen_key())\n for i in xrange(100):\n msg = 'y' * i\n assert box.decrypt(box.encrypt(msg)) == msg\n\n\n\n\nclass Test_ChumCipher(unittest.TestCase):\n\n def test_longer_irregular_read_lengths(self):\n key = 'a' * 32\n nonce = 'n' * 16\n cc = ChumCipher(key, nonce)\n n = 0\n while n < 2**12:\n assert len(cc._read_chum(n)) == n\n n += 31337\n\n\nclass Test_SecretBox_Naive(unittest.TestCase):\n\n def test_basics(self):\n key = utils.gen_key()\n box = SecretBox(key)\n nonce = utils.random(16)\n package = box.encrypt('P' * 32, 'N' * 16)\n pt = box.decrypt(package)\n assert pt == 'P' * 32\n for i in xrange(100):\n plaintext = utils.random(i)\n nonce = 'N' * 16\n package = box.encrypt(plaintext, nonce)\n assert plaintext == box.decrypt(package)\n\n def test_seal(self):\n key = 'K' * 32\n box = SecretBox(key)\n msg = 'hello chum'\n smsg = box.seal(msg)\n assert box.unseal(smsg) == msg\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"kristerhedfors/chumcrypt","sub_path":"test_chumcrypt.py","file_name":"test_chumcrypt.py","file_ext":"py","file_size_in_byte":4554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"31418100455","text":"#File: investment_adupree_extracredit.py\n#Description:Computes the future investment value though compound interest\n#Author:Alex DuPree\n#Date: 10/06/2017\n#Compiler: 3.4.1\n\n#Poll user for initial investment value, monthly rate, and number of years\ninvestment = float(input(\"Initial investment amount? \"))\nrate = float(input(\"Monthly rate as a percentage? \"))\nyears = float(input(\"Number of years to be compounded? \"))\n#Uses compound interest formula to find future invest value\nfuture_investment = investment * (1 + (rate/100))**(years*12)\n#Prints final investment value to display\nprint(\"An investment of {} USD at a monthly rate of {}% over {} year(s) will be {} USD\".format(investment, rate, years, future_investment))\n \n","repo_name":"AlexanderJDupree/CS160","sub_path":"week_1/investment_adupree_extracredit.py","file_name":"investment_adupree_extracredit.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"11121574324","text":"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport utils.func as func\n\nimport numpy as np\n\nimport math\nfrom torch.utils.data import DataLoader, random_split\n\nfrom sklearn.preprocessing import StandardScaler\n\n\n\n\nclass OT_Dataset(torch.utils.data.Dataset):\n 'Characterizes a dataset for PyTorch'\n def __init__(self, datasets):\n 'Initialization'\n self.datasets = datasets\n\n def __len__(self):\n 'Denotes the total number of samples'\n return len(self.datasets[0])\n\n def __getitem__(self, index):\n 'Generates one sample of data'\n # Select sample and label\n X = [self.datasets[0][index][0][0], self.datasets[1][index][0][1]]\n y = self.datasets[0][index][1]\n return X, y\n\nclass Pseudoset(torch.utils.data.Dataset):\n 'Characterizes a dataset for PyTorch'\n def __init__(self, datasets, targets):\n 'Initialization'\n self.datasets = datasets\n self.targets = targets\n\n def __len__(self):\n 'Denotes the total number of samples'\n return len(self.targets)\n\n def __getitem__(self, index):\n 'Generates one sample of data'\n # Select sample and label\n X_training_set = self.datasets[np.random.choice([0,1])][index][0]\n\n \n X_pseudo_set = self.datasets[-1][index][0]\n\n X = [X_training_set, X_pseudo_set]\n\n\n y = self.targets[index]\n\n return X, y\n\n\nclass Dataset(torch.utils.data.Dataset):\n 'Characterizes a dataset for PyTorch'\n def __init__(self, data_list, targets):\n 'Initialization'\n self.targets = targets\n self.data_list = data_list\n\n def __len__(self):\n 'Denotes the total number of samples'\n return len(self.targets)\n\n def __getitem__(self, index):\n 'Generates one sample of data'\n # Select sample and label\n X = [d[index][0] for d in self.data_list]\n y = self.targets[index]\n return X, y\n\n\n# from https://discuss.pytorch.org/t/how-can-i-replace-the-forward-method-of-a-predefined-torchvision-model-with-my-customized-forward-function/54224/7\nclass CustomNet(nn.Module):\n def __init__(self, original, scalar_means = None, scalar_stds=None):\n super().__init__()\n\n self.scalar_means = scalar_means\n self.scalar_stds = scalar_stds\n\n self.features = nn.ModuleList(original.children())[:-1]\n\n self.features = nn.Sequential(*self.features)\n in_features = original.fc.in_features\n\n self.fc0 = nn.Linear(in_features, 256)\n self.fc0_bn = nn.BatchNorm1d(256, eps = 1e-2)\n self.fc1 = nn.Linear(256, 7)\n self.fc1_bn = nn.BatchNorm1d(7, eps = 1e-2)\n \n # initialize all fc layers to xavier\n for m in self.modules():\n if isinstance(m, nn.Linear):\n torch.nn.init.xavier_normal_(m.weight, gain = 1)\n\n def forward(self, input_imgs):\n\n output = self.features(input_imgs)\n\n if self.scalar_means is not None and self.scalar_stds is not None:\n output = func.feature_wise_scaling(output, self.scalar_means, self.scalar_stds)\n output = output.view(input_imgs.size(0), -1)\n embs = output\n\n output = self.fc0_bn(F.relu(self.fc0(output)))\n output = self.fc1_bn(F.relu(self.fc1(output)))\n \n return embs, output\n\n\n\ndef get_feature_loaders(data_dict, batch_size, train_names, valid_name=None, test_name=None, verbose=True):\n\n data, l = func.dict_to_data(data_dict, train_names) \n dataset = Dataset(data, l)\n if verbose: print(f'Training on {train_names}')\n # Get validation\n if valid_name=='split':\n if verbose: print('Validation on trainingset split')\n r = 0.8\n train, val = random_split(dataset, [math.floor(r*len(dataset)), math.ceil((1-r)*len(dataset))])\n elif valid_name:\n if verbose: print(f'Validation on {valid_name}')\n train = dataset\n data, l = func.dict_to_data(data_dict, valid_name) \n val = Dataset(data, l)\n else:\n if verbose: print('No validation')\n val = None\n train = dataset\n \n #Get testing\n if test_name=='split':\n if verbose: print('Testing on validation set split')\n r = 0.5\n val, test = random_split(val, [math.floor(r*len(val)), math.ceil((1-r)*len(val))])\n elif test_name:\n if verbose: print(f'Testing on {test_name}')\n data, l = func.dict_to_data(data_dict, test_name) \n test = Dataset(data, l)\n else:\n if verbose: print('No testing')\n test = None\n train = dataset\n \n\n datasets = [train, val, test]\n\n train_loader, valid_loader, test_loader = [DataLoader(d, batch_size=batch_size, shuffle=True, num_workers=0) if d else d for d in datasets]\n\n return train_loader, valid_loader, test_loader, datasets\n\n\n\n\ndef get_image_loaders(datasets, batch_size, train_names, valid_name=None, test_name=None, verbose=True, shuffle=True, ot_order=False):\n \n data, l = func.bootstrap(datasets, train_names)\n dataset = Dataset(data, l)\n if verbose: print(f'Training on {train_names}')\n # Get validation\n if valid_name=='split':\n if verbose: print('Validation on trainingset split')\n r = 0.8\n train, val = random_split(dataset, [math.floor(r*len(dataset)), math.ceil((1-r)*len(dataset))])\n elif valid_name:\n if verbose: print(f'Validation on {valid_name}')\n train = dataset\n data, l = func.bootstrap(datasets, valid_name)\n val = Dataset(data, l)\n else:\n if verbose: print('No validation')\n val = None\n train = dataset\n \n #Get testing\n if test_name=='split':\n if verbose: print('Testing on validation set split')\n r = 0.5\n val, test = random_split(val, [math.floor(r*len(val)), math.ceil((1-r)*len(val))])\n elif test_name:\n if verbose: print(f'Testing on {test_name}')\n data, l = func.bootstrap(datasets, test_name)\n test = Dataset(data, l)\n else:\n if verbose: print('No testing')\n test = None\n train = dataset\n \n datasets = [train, val]\n train_loader, valid_loader = [DataLoader(d, batch_size=batch_size, shuffle=shuffle, num_workers=0) if d else d for d in datasets]\n test_loader = DataLoader(test, batch_size=batch_size, shuffle=False, num_workers=0)\n\n\n\n return train_loader, valid_loader, test_loader, datasets\n\n\ndef valid_split(dataset, r, batch_size, shuffle):\n r = 0.8\n train, val = random_split(dataset, [math.floor(r*len(dataset)), math.ceil((1-r)*len(dataset))]) \n \n return [DataLoader(d, batch_size=batch_size, shuffle=shuffle, num_workers=0) for d in [train, val]]\n","repo_name":"sanderkohnstamm/Thesis","sub_path":"utils/torchy.py","file_name":"torchy.py","file_ext":"py","file_size_in_byte":6706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"28904155571","text":"\nimport argparse\nimport codecs\nimport json\nimport os\nfrom multiprocessing import Pool\n\nimport numpy as np\nimport re\n# Get a counter for the iterations\nfrom tqdm import tqdm\ntqdm.monitor_interval = 0\nfrom collections import Counter\nprint(\"Loaded libraries...\")\nimport nltk\nfrom nltk.corpus import stopwords\nimport spacy\nnlp = spacy.load('en_core_web_lg')\n\nSTOP_WORDS = set(\n \"\"\"\na about above across after afterwards again against all almost alone along\nalready also although always am among amongst amount an and another any anyhow\nanyone anything anyway anywhere are around as at\nback be became because become becomes becoming been before beforehand behind\nbeing below beside besides between beyond both bottom but by\ncall can cannot ca could\ndid do does doing done down due during\neach eight either eleven else elsewhere empty enough even ever every\neveryone everything everywhere except\nfew fifteen fifty first five for former formerly forty four from front full\nfurther\nget give go\nhad has have he hence her here hereafter hereby herein hereupon hers herself\nhim himself his how however hundred\ni if in indeed into is it its itself\nkeep\nlast latter latterly least less\njust\nmade make many may me meanwhile might mine more moreover most mostly move much\nmust my myself\nname namely neither never nevertheless next nine no nobody none noone nor not\nnothing now nowhere\nof off often on once one only onto or other others otherwise our ours ourselves\nout over own\npart per perhaps please put\nquite\nrather re really regarding\nsame say see seem seemed seeming seems serious several she should show side\nsince six sixty so some somehow someone something sometime sometimes somewhere\nstill such\ntake ten than that the their them themselves then thence there thereafter\nthereby therefore therein thereupon these they third this those though three\nthrough throughout thru thus to together too top toward towards twelve twenty\ntwo\nunder until up unless upon us used using\nvarious very very via was we well were what whatever when whence whenever where\nwhereafter whereas whereby wherein whereupon wherever whether which while\nwhither who whoever whole whom whose why will with within without would\nyet you your yours yourself yourselves\n\"\"\".split()\n)\n\nstopwords_spacy = nlp.Defaults.stop_words\n\nnltk.download('stopwords')\nsws = stopwords.words('english') + [\"get\", \"take\", \"n’t\", '\"', \"ca\", \"nt\", \"'s\", \"got\", \"still\", \"...\", \":\", '\"', \"wo\",\n \"everything\", \"amp;#x200b\", \"_\", \"..\", 'am', \"'m\", \"'ve\", \"are\", \"is\", \"'s\", \".\", \"n't\", \",\",\n \"*\", \"feel\", \"much\", \"pretty\", \"also\", \"even\", \")\", \"(\", \"want\", \"?\", \"/\", \"na\", \"'re\", \"-\", \"%\"]\n\nSTOP_WORDS.update({\"like\", \"going\", \"say\", \"took\", \"new\", \"tic\", \"lol\"})\n\nsws = list(set(sws + list(STOP_WORDS)))\n\n\nparser = argparse.ArgumentParser(\n description=\"Builds an extractive summary from a json prediction.\")\n\nparser.add_argument('-dataset', type=str,\n default='/disk1/sajad/datasets/medical/mental-reddit-reduced/sets/train-final.json',\n help=\"\"\"Path of the dataset file\"\"\")\n\nparser.add_argument('-output', type=str,\n\t\t\t\t\tdefault='/disk1/sajad/datasets/medical/mental-reddit-reduced/sets/with-annotated/train-annotated-mental.json',\n help=\"\"\"Path of the output files\"\"\")\n\n\nparser.add_argument('-prune', type=int, default=-1,\n help=\"Prune to that number of words.\")\nparser.add_argument('-num_examples', type=int, default=100000,\n help=\"Prune to that number of examples.\")\n\nopt = parser.parse_args()\n\n\ndef get_tokens(txt):\n out_tokens = []\n doc = nlp(txt)\n for sent in doc.sents:\n for word in sent:\n # out_tokens.append((word.text, word.lemma_))\n out_tokens.append(word.text)\n return out_tokens\n\n\ndef compile_substring(start, end, split):\n if start == end:\n return split[start]\n return \" \".join(split[start:end+1])\n\ndef format_json(s):\n return json.dumps({'sentence':s})+\"\\n\"\n\ndef splits(s, num=2000):\n # tokenize the source\n if num != -1:\n # return s.split()[:num]\n return get_tokens(s)[:num]\n else:\n # return s.split()\n return get_tokens(s)\n\n\ndef check_mental_ontology(counter, t, substring):\n # if substring == 'panic attack':\n # print('2')\n # import pdb;\n # pdb.set_trace()\n # print(f'c({counter}) -s ({substring})')\n matches_from_ont = set()\n for j, tt in enumerate(t):\n minor_counter = counter\n\n substring_found = True\n if len(tt.split()) > minor_counter:\n while minor_counter > -1:\n try:\n if substring.split()[minor_counter].lower() == tt.split()[minor_counter].lower():\n matches_from_ont.add(tt.lower())\n # if substring == 'panic attack':\n # import pdb;pdb.set_trace()\n minor_counter -= 1\n continue\n else:\n substring_found = False\n break\n except:\n continue\n else:\n substring_found = False\n\n if substring_found:\n return True, substring in list(matches_from_ont)\n else:\n continue\n\n return False, substring in list(matches_from_ont)\n\ndef make_BIO_tgt_mental(s, t):\n # t should be an array or str\n # tsplit = t.split()\n ssplit = s#.split()\n startix = 0\n endix = 0\n matches = []\n matchstrings = Counter()\n loop_counter = 0\n t = [tt for tt in t if len(tt.strip()) > 0]\n ssplit = [s for s in ssplit if len(s.strip()) > 0]\n prev_partial_match = False\n while endix < len(ssplit):\n # last check is to make sure that phrases at end can be copied\n searchstring = compile_substring(startix, endix, ssplit)\n\n\n assert loop_counter == len(searchstring.split()) - 1, \"Loop counter shouldn't be 1 less than search query's length\"\n\n partial_match, exact_match = check_mental_ontology(loop_counter, t, searchstring)\n\n if exact_match:\n loop_counter = 0\n full_string = compile_substring(startix, endix, ssplit)\n matches.extend([\"1\"] * (endix - startix + 1))\n matchstrings[full_string] += 1\n endix += 1\n startix = endix\n\n elif (partial_match) and endix < len(ssplit)-1:\n # if searchstring in t and endix < len(ssplit)-1 and searchstring == 'panic attack':\n endix += 1\n loop_counter += 1\n prev_partial_match = True\n\n else:\n # if searchstring == 'a panic':\n # import pdb;pdb.set_trace()\n\n loop_counter = 0\n # only phrases, not words\n # uncomment the -1 if you only want phrases > len 1\n # if startix >= endix:#-1:\n if not prev_partial_match:\n matches.extend([\"0\"] * (endix - startix + 1))\n endix += 1\n prev_partial_match = False\n else:\n matches.extend([\"0\"] * (endix - startix))\n endix = endix\n prev_partial_match = False\n\n\n startix = endix\n\n return matches\n\ndef make_BIO_tgt(s, t, mental_retrieve=False):\n # t should be an array or str\n # tsplit = t.split()\n ssplit = s#.split()\n\n startix = 0\n endix = 0\n matches = []\n matchstrings = Counter()\n while endix < len(ssplit):\n # last check is to make sure that phrases at end can be copied\n searchstring = compile_substring(startix, endix, ssplit)\n\n if searchstring in t and endix < len(ssplit)-1:\n endix += 1\n\n else:\n # only phrases, not words\n # uncomment the -1 if you only want phrases > len 1\n if startix >= endix:#-1:\n matches.extend([\"0\"] * (endix-startix + 1))\n endix += 1\n else:\n # First one has to be 2 if you want phrases not words\n full_string = compile_substring(startix, endix-1, ssplit)\n matches.extend([\"1\"]*(endix-startix))\n matchstrings[full_string] +=1\n\n startix = endix\n\n return matches\n\n\ndef retrieve_mental_string():\n out_str = []\n with open('mental_illnesses.txt') as fR:\n for l in fR:\n out_str += [l.strip()]\n\n return out_str\n\ndef _mp_labelizer(instance):\n idd, ssplits, t, mental_ds = instance\n # tgt = make_BIO_tgt(ssplits, t)\n tgt_mental = make_BIO_tgt_mental(ssplits, mental_ds)\n return idd, ssplits, None, tgt_mental\n\ndef main():\n lcounter = 0\n max_total = opt.num_examples\n\n DS_PATH = opt.dataset\n SOURCE_PATH = 'src.txt'\n TARGET_PATH = 'tgt.txt'\n ID_PATH = 'id.txt'\n\n NEW_TARGET_PATH = opt.output + \".txt\"\n PRED_SRC_PATH = opt.output + \".pred.txt\"\n PRED_TGT_PATH = opt.output + \".src.txt\"\n\n # SOURCE_PATH and TARGET_PATH should be created here and will be removed at the end\n json_ents = {}\n idd = 0\n with codecs.open(SOURCE_PATH, 'w', \"utf-8\") as fWS, codecs.open(TARGET_PATH, 'w', \"utf-8\") as fWT, codecs.open(ID_PATH, 'w', 'utf-8') as fWI:\n with open(DS_PATH) as fR:\n for l in fR:\n ent = json.loads(l.strip())\n src = ent['src']\n tldr = ent['tldr']\n id = idd\n json_ents[str(id)] = ent\n fWS.write(src)\n fWS.write('\\n')\n fWT.write(tldr)\n fWT.write('\\n')\n fWI.write(str(id))\n fWI.write('\\n')\n idd+=1\n\n\n with codecs.open(SOURCE_PATH, 'r', \"utf-8\") as sfile:\n for ix, l in enumerate(sfile):\n lcounter += 1\n if lcounter >= max_total:\n break\n\n sfile = codecs.open(SOURCE_PATH, 'r', \"utf-8\")\n tfile = codecs.open(TARGET_PATH, 'r', \"utf-8\")\n ifile = codecs.open(ID_PATH, 'r', \"utf-8\")\n outf = codecs.open(NEW_TARGET_PATH, 'w', \"utf-8\", buffering=1)\n outf_tgt_src = codecs.open(PRED_SRC_PATH, 'w', \"utf-8\", buffering=1)\n outf_tgt_tgt = codecs.open(PRED_TGT_PATH, 'w', \"utf-8\", buffering=1)\n\n\n actual_lines = 0\n mental_ilnesses_string = retrieve_mental_string()\n splits_to_be_processed = []\n for ix, (s, t, id) in tqdm(enumerate(zip(sfile, tfile, ifile)), total=lcounter):\n ssplit = splits(s, num=opt.prune)\n # Skip empty lines\n\n if len(ssplit) < 2 or len(t.split()) < 2:\n continue\n else:\n actual_lines += 1\n # Build the target\n\n splits_to_be_processed.append((id, ssplit, t, mental_ilnesses_string))\n\n # ssplit = ['I', 'got', 'a', 'panic', 'attack', 'recently', '.', \"Also\", \"I\", \"have\", \"adhd\"]\n # import pdb;pdb.set_trace()\n\n pool = Pool(2)\n for labels in tqdm(pool.imap_unordered(_mp_labelizer, splits_to_be_processed), total=len(splits_to_be_processed)):\n id, ssplit, tgt, tgt_mental = labels\n\n # tgt = [int(t) + int(tm) for t, tm in zip(tgt, tgt_mental)]\n # tgt_par = [(s,t) for s,t in zip(ssplit, tgt_mental.split())]\n # Format for allennlp\n tgt = tgt_mental\n\n annotations = []\n seen_tokens_len = 0\n sstring = ' '.join(ssplit)\n for j, (token, tag) in enumerate(zip(ssplit, tgt)):\n if (tag == 1 or tag==2) and token.lower() not in sws:\n annotations.append(\n {\n 'start': seen_tokens_len,\n 'end': seen_tokens_len + len(token),\n 'text': token,\n 'label': tag,\n }\n )\n\n seen_tokens_len += len(token)+1\n\n # import pdb;pdb.set_trace()\n json_ents[id.strip()]['src'] = sstring.strip()\n json_ents[id.strip()]['annotations'] = {}\n json_ents[id.strip()]['annotations'] = annotations\n # for token, tag in zip(ssplit, tgt.split()):\n # outf.write(token+\"###\"+tag + \" \")\n\n sfile.close()\n tfile.close()\n outf.close()\n outf_tgt_src.close()\n outf_tgt_tgt.close()\n os.remove(SOURCE_PATH)\n os.remove(TARGET_PATH)\n\n # writing new and updated json ents...\n with open(opt.output, mode='w') as fW:\n for key, ins in json_ents.items():\n json.dump(ins, fW)\n fW.write('\\n')\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"sajastu/graph_preprocessor","sub_path":"preprocess_copy.py","file_name":"preprocess_copy.py","file_ext":"py","file_size_in_byte":12500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"23299903814","text":"from django.urls import path\nfrom .views import (\n index,\n login,\n about,\n news,\n contact,\n destinations,\n elements\n)\nurlpatterns = [\n path('',index, name=\"home\" ),\n path('login/',login, name=\"login\" ),\n path('about/',about, name=\"about\" ),\n path('news/',news, name=\"news\" ),\n path('destinations/',destinations, name=\"destinations\" ),\n path('elements/',elements, name=\"elements\" ),\n path('contact/',contact, name=\"contact\" ),\n]\n","repo_name":"pyravi/ROYALHOUSETRAVELS","sub_path":"web/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"42497064645","text":"from abc import ABCMeta, abstractmethod\n\nimport torch\n\nfrom .core import collect_leaves\nfrom .types import Linear, BatchNorm, ConvolutionTranspose\n\n\nclass Canonizer(metaclass=ABCMeta):\n '''Canonizer Base class.\n Canonizers modify modules temporarily such that certain attribution rules can properly be applied.\n '''\n @abstractmethod\n def apply(self, root_module):\n '''Apply this canonizer recursively on all applicable modules.\n\n Parameters\n ----------\n root_module: :py:obj:`torch.nn.Module`\n Root module to which to apply the canonizers.\n\n Returns\n -------\n list\n A list of all applied instances of this class.\n '''\n return []\n\n @abstractmethod\n def register(self):\n '''Apply the changes of this canonizer.'''\n\n @abstractmethod\n def remove(self):\n '''Revert the changes introduces by this canonizer.'''\n\n def copy(self):\n '''Return a copy of this instance.'''\n return self.__class__()\n\n\nclass MergeBatchNorm(Canonizer):\n '''Abstract Canonizer to merge the parameters of batch norms into linear modules.'''\n linear_type = (\n Linear,\n )\n batch_norm_type = (\n BatchNorm,\n )\n\n def __init__(self):\n super().__init__()\n self.linears = None\n self.batch_norm = None\n\n self.linear_params = None\n self.batch_norm_params = None\n\n def register(self, linears, batch_norm):\n '''Store the parameters of the linear modules and the batch norm module and apply the merge.\n\n Parameters\n ----------\n linear: list of :py:obj:`torch.nn.Module`\n List of linear layer with mandatory attributes `weight` and `bias`.\n batch_norm: :py:obj:`torch.nn.Module`\n Batch Normalization module with mandatory attributes\n `running_mean`, `running_var`, `weight`, `bias` and `eps`\n '''\n self.linears = linears\n self.batch_norm = batch_norm\n\n self.linear_params = [(linear.weight, linear.bias) for linear in linears]\n\n self.batch_norm_params = {\n key: getattr(self.batch_norm, key) for key in ('weight', 'bias', 'running_mean', 'running_var', 'eps')\n }\n\n self.merge_batch_norm(self.linears, self.batch_norm)\n\n def remove(self):\n '''Undo the merge by reverting the parameters of both the linear and the batch norm modules to the state before\n the merge.\n '''\n for linear, (weight, bias) in zip(self.linears, self.linear_params):\n object.__setattr__(linear, 'weight', weight)\n object.__setattr__(linear, 'bias', bias)\n\n for key, value in self.batch_norm_params.items():\n object.__setattr__(self.batch_norm, key, value)\n\n @staticmethod\n def merge_batch_norm(modules, batch_norm):\n '''Update parameters of a linear layer to additionally include a Batch Normalization operation and update the\n batch normalization layer to instead compute the identity.\n\n Parameters\n ----------\n modules: list of :py:obj:`torch.nn.Module`\n Linear layers with mandatory attributes `weight` and `bias`.\n batch_norm: :py:obj:`torch.nn.Module`\n Batch Normalization module with mandatory attributes `running_mean`, `running_var`, `weight`, `bias` and\n `eps`\n '''\n denominator = (batch_norm.running_var + batch_norm.eps) ** .5\n scale = batch_norm.weight / denominator\n\n for module in modules:\n if module.bias is None:\n object.__setattr__(\n module, 'bias', torch.zeros(1, device=module.weight.device, dtype=module.weight.dtype)\n )\n\n index = (slice(None), *((None,) * (module.weight.ndim - 1)))\n if isinstance(module, ConvolutionTranspose):\n index = index[1::-1] + index[2:]\n\n # merge batch_norm into linear layer\n object.__setattr__(module, 'weight', module.weight * scale[index])\n object.__setattr__(module, 'bias', (module.bias - batch_norm.running_mean) * scale + batch_norm.bias)\n\n # change batch_norm parameters to produce identity\n for key, func in zip(\n ('running_mean', 'running_var', 'bias', 'weight', 'eps'),\n (*(torch.zeros_like, torch.ones_like) * 2, lambda _: 0.)\n ):\n object.__setattr__(batch_norm, key, func(getattr(batch_norm, key)))\n\n\nclass SequentialMergeBatchNorm(MergeBatchNorm):\n '''Canonizer to merge the parameters of all batch norms that appear sequentially right after a linear module.\n\n Note\n ----\n SequentialMergeBatchNorm traverses the tree of children of the provided module depth-first and in-order.\n This means that child-modules must be assigned to their parent module in the order they are visited in the forward\n pass to correctly identify adjacent modules.\n This also means that activation functions must be assigned in their module-form as a child to their parent-module\n to properly detect when there is an activation function between linear and batch-norm modules.\n\n '''\n def apply(self, root_module):\n '''Finds a batch norm following right after a linear layer, and creates a copy of this instance to merge\n them by fusing the batch norm parameters into the linear layer and reducing the batch norm to the identity.\n\n Parameters\n ----------\n root_module: :py:obj:`torch.nn.Module`\n A module of which the leaves will be searched and if a batch norm is found right after a linear layer, will\n be merged.\n\n Returns\n -------\n instances: list\n A list of instances of this class which modified the appropriate leaves.\n '''\n instances = []\n last_leaf = None\n for leaf in collect_leaves(root_module):\n if isinstance(last_leaf, self.linear_type) and isinstance(leaf, self.batch_norm_type):\n instance = self.copy()\n instance.register((last_leaf,), leaf)\n instances.append(instance)\n last_leaf = leaf\n\n return instances\n\n\nclass NamedMergeBatchNorm(MergeBatchNorm):\n '''Canonizer to merge the parameters of all batch norms into linear modules, specified by their respective names.\n\n Parameters\n ----------\n name_map: list[tuple[string], string]\n List of which linear layer names belong to which batch norm name.\n '''\n def __init__(self, name_map):\n super().__init__()\n self.name_map = name_map\n\n def apply(self, root_module):\n '''Create appropriate merges given by the name map.\n\n Parameters\n ----------\n root_module: :py:obj:`torch.nn.Module`\n Root module for which underlying modules will be merged.\n\n Returns\n -------\n instances: list\n A list of merge instances.\n '''\n instances = []\n lookup = dict(root_module.named_modules())\n\n for linear_names, batch_norm_name in self.name_map:\n instance = self.copy()\n instance.register([lookup[name] for name in linear_names], lookup[batch_norm_name])\n instances.append(instance)\n\n return instances\n\n def copy(self):\n return self.__class__(self.name_map)\n\n\nclass AttributeCanonizer(Canonizer):\n '''Canonizer to set an attribute of module instances.\n Note that the use of this Canonizer removes previously set attributes after removal.\n\n Parameters\n ----------\n attribute_map: Function\n A function that returns either None, if not applicable, or a dict with keys describing which attributes to\n overload for a module. The function signature is (name: string, module: type) -> None or\n dict.\n '''\n def __init__(self, attribute_map):\n self.attribute_map = attribute_map\n self.attribute_keys = None\n self.module = None\n\n def apply(self, root_module):\n '''Overload the attributes for all applicable modules.\n\n Parameters\n ----------\n root_module: :py:obj:`torch.nn.Module`\n Root module for which underlying modules will have their attributes overloaded.\n\n Returns\n -------\n instances : list of :py:obj:`Canonizer`\n The applied canonizer instances, which may be removed by calling `.remove`.\n '''\n instances = []\n for name, module in root_module.named_modules():\n attributes = self.attribute_map(name, module)\n if attributes is not None:\n instance = self.copy()\n instance.register(module, attributes)\n instances.append(instance)\n return instances\n\n def register(self, module, attributes):\n '''Overload the module's attributes.\n\n Parameters\n ---------\n module : :py:obj:`torch.nn.Module`\n The module of which the attributes will be overloaded.\n attributes : dict\n The attributes which to overload for the module.\n '''\n self.attribute_keys = list(attributes)\n self.module = module\n for key, value in attributes.items():\n setattr(module, key, value)\n\n def remove(self):\n '''Remove the overloaded attributes. Note that functions are descriptors, and therefore not direct attributes\n of instance, which is why deleting instance attributes with the same name reverts them to the original\n function.\n '''\n for key in self.attribute_keys:\n delattr(self.module, key)\n\n def copy(self):\n '''Copy this Canonizer.\n\n Returns\n -------\n :py:obj:`Canonizer`\n A copy of this Canonizer.\n '''\n return AttributeCanonizer(self.attribute_map)\n\n\nclass CompositeCanonizer(Canonizer):\n '''A Composite of Canonizers, which applies all supplied canonizers.\n\n Parameters\n ----------\n canonizers : list of :py:obj:`Canonizer`\n Canonizers of which to build a Composite of.\n '''\n def __init__(self, canonizers):\n self.canonizers = canonizers\n\n def apply(self, root_module):\n '''Apply call canonizers.\n\n Parameters\n ----------\n root_module: :py:obj:`torch.nn.Module`\n Root module for which underlying modules will have canonizers applied.\n\n Returns\n -------\n instances : list of :py:obj:`Canonizer`\n The applied canonizer instances, which may be removed by calling `.remove`.\n '''\n instances = []\n for canonizer in self.canonizers:\n instances += canonizer.apply(root_module)\n return instances\n\n def register(self):\n '''Register this Canonizer. Nothing to do for a CompositeCanonizer.'''\n\n def remove(self):\n '''Remove this Canonizer. Nothing to do for a CompositeCanonizer.'''\n","repo_name":"chr5tphr/zennit","sub_path":"src/zennit/canonizers.py","file_name":"canonizers.py","file_ext":"py","file_size_in_byte":10959,"program_lang":"python","lang":"en","doc_type":"code","stars":159,"dataset":"github-code","pt":"34"} +{"seq_id":"41074237523","text":"import contextlib\nimport os\n\n\ndef loads(ini_str, strict=True):\n ret = {}\n for line in ini_str.splitlines():\n key, val = line.split('=', 1)\n key = key.strip()\n val = val.strip()\n if strict and key in ret:\n raise ValueError('Multiple entries present for key \"%s\"' % key)\n ret[key] = val\n\n return ret\n\n\ndef load(fp):\n return loads(fp.read())\n\n\ndef dumps(obj):\n ret = ''\n for k, v in sorted(obj.items()):\n ret += '%s = %s\\n' % (k, str(v))\n return ret\n\n\ndef dump(obj, fp):\n fp.write(dumps(obj))\n\n\n@contextlib.contextmanager\ndef update_ini_file(ini_file_path):\n \"\"\"Load and update the contents of an ini file.\n\n Args:\n ini_file_path: A string containing the absolute path of the ini file.\n Yields:\n The contents of the file, as a dict\n \"\"\"\n if os.path.exists(ini_file_path):\n with open(ini_file_path) as ini_file:\n ini_contents = load(ini_file)\n else:\n ini_contents = {}\n\n yield ini_contents\n\n with open(ini_file_path, 'w') as ini_file:\n dump(ini_contents, ini_file)\n","repo_name":"WaterfoxCo/Waterfox","sub_path":"third_party/libwebrtc/build/android/pylib/local/emulator/ini.py","file_name":"ini.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":3159,"dataset":"github-code","pt":"34"} +{"seq_id":"20523436363","text":"import json\nimport os\nimport copy\nimport zipfile\nfrom tqdm import tqdm\nimport re\nfrom convlab2.util.file_util import read_zipped_json, write_zipped_json\nfrom pprint import pprint\n\ndescriptions = {\n \"uber_lyft\": {\n \"uber_lyft\": \"order a car for a ride inside a city\",\n \"location.from\": \"pickup location\",\n \"location.to\": \"destination of the ride\",\n \"type.ride\": \"type of ride\",\n \"num.people\": \"number of people\",\n \"price.estimate\": \"estimated cost of the ride\",\n \"duration.estimate\": \"estimated duration of the ride\",\n \"time.pickup\": \"time of pickup\",\n \"time.dropoff\": \"time of dropoff\",\n },\n \"movie_ticket\": {\n \"movie_ticket\": \"book movie tickets for a film\",\n \"name.movie\": \"name of the movie\",\n \"name.theater\": \"name of the theater\",\n \"num.tickets\": \"number of tickets\",\n \"time.start\": \"start time of the movie\",\n \"location.theater\": \"location of the theater\",\n \"price.ticket\": \"price of the ticket\",\n \"type.screening\": \"type of the screening\",\n \"time.end\": \"end time of the movie\",\n \"time.duration\": \"duration of the movie\",\n },\n \"restaurant_reservation\": {\n \"restaurant_reservation\": \"searching for a restaurant and make reservation\",\n \"name.restaurant\": \"name of the restaurant\",\n \"name.reservation\": \"name of the person who make the reservation\",\n \"num.guests\": \"number of guests\",\n \"time.reservation\": \"time of the reservation\",\n \"type.seating\": \"type of the seating\",\n \"location.restaurant\": \"location of the restaurant\",\n },\n \"coffee_ordering\": {\n \"coffee_ordering\": \"order a coffee drink from either Starbucks or Peets for pick up\",\n \"location.store\": \"location of the coffee store\",\n \"name.drink\": \"name of the drink\",\n \"size.drink\": \"size of the drink\",\n \"num.drink\": \"number of drinks\",\n \"type.milk\": \"type of the milk\",\n \"preference\": \"user preference of the drink\",\n },\n \"pizza_ordering\": {\n \"pizza_ordering\": \"order a pizza\",\n \"name.store\": \"name of the pizza store\",\n \"name.pizza\": \"name of the pizza\",\n \"size.pizza\": \"size of the pizza\",\n \"type.topping\": \"type of the topping\",\n \"type.crust\": \"type of the crust\",\n \"preference\": \"user preference of the pizza\",\n \"location.store\": \"location of the pizza store\",\n },\n \"auto_repair\": {\n \"auto_repair\": \"set up an auto repair appointment with a repair shop\",\n \"name.store\": \"name of the repair store\",\n \"name.customer\": \"name of the customer\",\n \"date.appt\": \"date of the appointment\",\n \"time.appt\": \"time of the appointment\",\n \"reason.appt\": \"reason of the appointment\",\n \"name.vehicle\": \"name of the vehicle\",\n \"year.vehicle\": \"year of the vehicle\",\n \"location.store\": \"location of the repair store\",\n },\n \"flights\": {\n \"flights\": \"find a round trip or multi-city flights\",\n \"type\": \"type of the flight\",\n \"destination1\": \"the first destination city of the trip\",\n \"destination2\": \"the second destination city of the trip\",\n \"origin\": \"the origin city of the trip\",\n \"date.depart_origin\": \"date of departure from origin\",\n \"date.depart_intermediate\": \"date of departure from intermediate\",\n \"date.return\": \"date of return\",\n \"time_of_day\": \"time of the flight\",\n \"seating_class\": \"seat type (first class, business class, economy class, etc.\",\n \"seat_location\": \"location of the seat\",\n \"stops\": \"non-stop, layovers, etc.\",\n \"price_range\": \"price range of the flight\",\n \"num.pax\": \"number of people\",\n \"luggage\": \"luggage information\",\n \"total_fare\": \"total cost of the trip\",\n \"other_description\": \"other description of the flight\",\n \"from\": \"departure of the flight\",\n \"to\": \"destination of the flight\",\n \"airline\": \"airline of the flight\",\n \"flight_number\": \"the number of the flight\",\n \"date\": \"date of the flight\",\n \"from.time\": \"departure time of the flight\",\n \"to.time\": \"arrival time of the flight\",\n \"stops.location\": \"location of the stop\",\n \"fare\": \"cost of the flight\",\n },\n \"food_order\": {\n \"food_order\": \"order take-out for a particular cuisine choice\",\n \"name.item\": \"name of the item\",\n \"other_description.item\": \"other description of the item\",\n \"type.retrieval\": \"type of the retrieval method\",\n \"total_price\": \"total price\",\n \"time.pickup\": \"pick up time\",\n \"num.people\": \"number of people\",\n \"name.restaurant\": \"name of the restaurant\",\n \"type.food\": \"type of food\",\n \"type.meal\": \"type of meal\",\n \"location.restaurant\": \"location of the restaurant\",\n \"rating.restaurant\": \"rating of the restaurant\",\n \"price_range\": \"price range of the food\",\n },\n \"hotel\": {\n \"hotel\": \"find a hotel using typical preferences\",\n \"name.hotel\": \"name of the hotel\",\n \"location.hotel\": \"location of the hotel\",\n \"sub_location.hotel\": \"rough location of the hotel\",\n \"star_rating\": \"star rating of the hotel\",\n \"customer_rating\": \"customer rating of the hotel\",\n \"price_range\": \"price range of the hotel\",\n \"amenity\": \"amenity of the hotel\",\n \"num.beds\": \"number of beds to book\",\n \"type.bed\": \"type of the bed\",\n \"num.rooms\": \"number of rooms to book\",\n \"check-in_date\": \"check-in date\",\n \"check-out_date\": \"check-out date\",\n \"date_range\": \"date range of the reservation\",\n \"num.guests\": \"number of guests\",\n \"type.room\": \"type of the room\",\n \"price_per_night\": \"price per night\",\n \"total_fare\": \"total fare\",\n \"location\": \"location of the hotel\",\n },\n \"movie\": {\n \"movie\": \"find a movie to watch in theaters or using a streaming service at home\",\n \"name.movie\": \"name of the movie\",\n \"genre\": \"genre of the movie\",\n \"name.theater\": \"name of the theater\",\n \"location.theater\": \"location of the theater\",\n \"time.start\": \"start time of the movie\",\n \"time.end\": \"end time of the movie\",\n \"price.ticket\": \"price of the ticket\",\n \"price.streaming\": \"price of the streaming\",\n \"type.screening\": \"type of the screening\",\n \"audience_rating\": \"audience rating\",\n \"movie_rating\": \"film rating\",\n \"release_date\": \"release date of the movie\",\n \"runtime\": \"running time of the movie\",\n \"real_person\": \"name of actors, directors, etc.\",\n \"character\": \"name of character in the movie\",\n \"streaming_service\": \"streaming service that provide the movie\",\n \"num.tickets\": \"number of tickets\",\n \"seating\": \"type of seating\",\n },\n \"music\": {\n \"music\": \"find several tracks to play and then comment on each one\",\n \"name.track\": \"name of the track\",\n \"name.artist\": \"name of the artist\",\n \"name.album\": \"name of the album\",\n \"name.genre\": \"music genre\",\n \"type.music\": \"rough type of the music\",\n \"describes_track\": \"description of a track to find\",\n \"describes_artist\": \"description of a artist to find\",\n \"describes_album\": \"description of an album to find\",\n \"describes_genre\": \"description of a genre to find\",\n \"describes_type.music\": \"description of the music type\",\n },\n \"restaurant\": {\n \"restaurant\": \"ask for recommendations for a particular type of cuisine\",\n \"name.restaurant\": \"name of the restaurant\",\n \"location\": \"location of the restaurant\",\n \"sub-location\": \"rough location of the restaurant\",\n \"type.food\": \"the cuisine of the restaurant\",\n \"menu_item\": \"item in the menu\",\n \"type.meal\": \"type of meal\",\n \"rating\": \"rating of the restaurant\",\n \"price_range\": \"price range of the restaurant\",\n \"business_hours\": \"business hours of the restaurant\",\n \"name.reservation\": \"name of the person who make the reservation\",\n \"num.guests\": \"number of guests\",\n \"time.reservation\": \"time of the reservation\",\n \"date.reservation\": \"date of the reservation\",\n \"type.seating\": \"type of the seating\",\n },\n \"sport\": {\n \"sport\": \"discuss facts and stats about players, teams, games, etc. in EPL, MLB, MLS, NBA, NFL\",\n \"name.team\": \"name of the team\",\n \"record.team\": \"record of the team (number of wins and losses)\",\n \"record.games_ahead\": \"number of games ahead\",\n \"record.games_back\": \"number of games behind\",\n \"place.team\": \"ranking of the team\",\n \"result.match\": \"result of the match\",\n \"score.match\": \"score of the match\",\n \"date.match\": \"date of the match\",\n \"day.match\": \"day of the match\",\n \"time.match\": \"time of the match\",\n \"name.player\": \"name of the player\",\n \"position.player\": \"position of the player\",\n \"record.player\": \"record of the player\",\n \"name.non_player\": \"name of non-palyer such as the manager, coach\",\n \"venue\": \"venue of the match take place\",\n }\n}\n\n\ndef normalize_domain_name(domain):\n if domain == 'auto':\n return 'auto_repair'\n elif domain == 'pizza':\n return 'pizza_ordering'\n elif domain == 'coffee':\n return 'coffee_ordering'\n elif domain == 'uber':\n return 'uber_lyft'\n elif domain == 'restaurant':\n return 'restaurant_reservation'\n elif domain == 'movie':\n return 'movie_ticket'\n elif domain == 'flights':\n return 'flights'\n elif domain == 'food-ordering':\n return 'food_order'\n elif domain == 'hotels':\n return 'hotel'\n elif domain == 'movies':\n return 'movie'\n elif domain == 'music':\n return 'music'\n elif domain == 'restaurant-search':\n return 'restaurant'\n elif domain == 'sports':\n return 'sport'\n assert 0\n\n\ndef format_turns(ori_turns):\n new_turns = []\n previous_speaker = None\n utt_idx = 0\n for i, turn in enumerate(ori_turns):\n speaker = 'system' if turn['speaker'] == 'ASSISTANT' else 'user'\n turn['speaker'] = speaker\n if utt_idx == 0 and speaker == 'system':\n continue\n if turn['text'] == '(deleted)':\n continue\n if not previous_speaker:\n assert speaker != previous_speaker\n if speaker != previous_speaker:\n previous_speaker = speaker\n new_turns.append(copy.deepcopy(turn))\n utt_idx += 1\n else:\n # continuous speaking\n last_turn = new_turns[-1]\n # if ori_turns[i-1]['text'] == turn['text']:\n # # skip repeat turn\n # continue\n if turn['text'] in ori_turns[i-1]['text']:\n continue\n index_shift = len(last_turn['text']) + 1\n last_turn['text'] += ' '+turn['text']\n if 'segments' in turn:\n last_turn.setdefault('segments', [])\n for segment in turn['segments']:\n segment['start_index'] += index_shift\n segment['end_index'] += index_shift\n last_turn['segments'] += turn['segments']\n if new_turns and new_turns[-1]['speaker'] == 'system':\n new_turns = new_turns[:-1]\n return new_turns\n\n\ndef log_ontology(acts, ontology, ori_ontology):\n for item in acts:\n intent, domain, slot, value = item['intent'], item['domain'], item['slot'], item['value']\n if domain not in ontology['domains']:\n ontology['domains'][domain] = {'description': \"\", 'slots': {}}\n if slot not in ontology['domains'][domain]['slots']:\n ontology['domains'][domain]['slots'][slot] = {\n 'description': '',\n 'is_categorical': False,\n 'possible_values': [],\n 'count': 1\n }\n else:\n ontology['domains'][domain]['slots'][slot]['count'] += 1\n ontology['domains'][domain]['slots'][slot]['in original ontology'] = slot in ori_ontology[domain]\n if intent is not None and intent not in ontology['intents']:\n ontology['intents'][intent] = {\n \"description\": ''\n }\n\n\ndef preprocess():\n self_dir = os.path.dirname(os.path.abspath(__file__))\n processed_dialogue = []\n ontology = {'domains': {},\n 'intents': {},\n 'binary_dialogue_act': [],\n 'state': {}}\n original_zipped_path = os.path.join(self_dir, 'original_data.zip')\n new_dir = os.path.join(self_dir, 'original_data')\n if not os.path.exists(os.path.join(self_dir, 'data.zip')) or not os.path.exists(os.path.join(self_dir, 'ontology.json')):\n print('unzip to', new_dir)\n print('This may take several minutes')\n archive = zipfile.ZipFile(original_zipped_path, 'r')\n archive.extractall(self_dir)\n files = [\n ('TM-1-2019/woz-dialogs.json', 'TM-1-2019/ontology.json'),\n ('TM-1-2019/self-dialogs.json', 'TM-1-2019/ontology.json'),\n ('TM-2-2020/data/flights.json', 'TM-2-2020/ontology/flights.json'),\n ('TM-2-2020/data/food-ordering.json', 'TM-2-2020/ontology/food-ordering.json'),\n ('TM-2-2020/data/hotels.json', 'TM-2-2020/ontology/hotels.json'),\n ('TM-2-2020/data/movies.json', 'TM-2-2020/ontology/movies.json'),\n ('TM-2-2020/data/music.json', 'TM-2-2020/ontology/music.json'),\n ('TM-2-2020/data/restaurant-search.json', 'TM-2-2020/ontology/restaurant-search.json'),\n ('TM-2-2020/data/sports.json', 'TM-2-2020/ontology/sports.json')\n ]\n idx_count = 1\n total = 0\n\n for filename, ontology_filename in files:\n data = json.load(open(os.path.join(new_dir, filename)))\n ori_ontology = {}\n if 'TM-1' in filename:\n for domain, item in json.load(open(os.path.join(new_dir, ontology_filename))).items():\n ori_ontology[item[\"id\"]] = {}\n for slot in item[\"required\"] + item[\"optional\"]:\n ori_ontology[item[\"id\"]][slot] = 0\n else:\n domain = normalize_domain_name(filename.split('/')[-1].split('.')[0])\n ori_ontology[domain] = {}\n for _, item in json.load(open(os.path.join(new_dir, ontology_filename))).items():\n for group in item:\n for anno in group[\"annotations\"]:\n ori_ontology[domain][anno] = 0\n for d in ori_ontology:\n if d not in ontology['domains']:\n ontology['domains'][d] = {'description': descriptions[d][d], 'slots': {}}\n for s in ori_ontology[d]:\n if s not in ontology['domains'][d]['slots']:\n ontology['domains'][d]['slots'][s] = {\n 'description': descriptions[d][s],\n 'is_categorical': False,\n 'possible_values': [],\n 'count': 0,\n 'in original ontology': True\n }\n # pprint(ori_ontology)\n for ori_sess in tqdm(data, desc='processing taskmaster-{}'.format(filename)):\n total += 1\n turns = format_turns(ori_sess['utterances'])\n if not turns:\n continue\n if 'TM-2' in filename:\n dial_domain = normalize_domain_name(filename.split('/')[-1].split('.')[0])\n else:\n dial_domain = normalize_domain_name(ori_sess['instruction_id'].split('-', 1)[0])\n dialogue = {\n \"dataset\": \"taskmaster\",\n \"data_split\": \"train\",\n \"dialogue_id\": 'taskmaster_' + str(idx_count),\n \"original_id\": ori_sess['conversation_id'],\n \"instruction_id\": ori_sess['instruction_id'],\n \"domains\": [\n dial_domain\n ],\n \"turns\": []\n }\n idx_count += 1\n assert turns[0]['speaker'] == 'user' and turns[-1]['speaker'] == 'user', print(turns)\n for utt_idx, uttr in enumerate(turns):\n speaker = uttr['speaker']\n turn = {\n 'speaker': speaker,\n 'utterance': uttr['text'],\n 'utt_idx': utt_idx,\n 'dialogue_act': {\n 'binary': [],\n 'categorical': [],\n 'non-categorical': [],\n },\n }\n if speaker == 'user':\n turn['state'] = {}\n turn['state_update'] = {'categorical': [], 'non-categorical': []}\n\n if 'segments' in uttr:\n for segment in uttr['segments']:\n for item in segment['annotations']:\n # domain = item['name'].split('.', 1)[0]\n domain = dial_domain\n\n # if domain != item['name'].split('.', 1)[0]:\n # print(domain, item['name'].split('.', 1), dialogue[\"original_id\"])\n # assert domain in item['name'].split('.', 1)[0]\n\n # if item['name'].split('.', 1)[0] != domain:\n # print(domain, item['name'].split('.', 1), dialogue[\"original_id\"])\n slot = item['name'].split('.', 1)[-1]\n if slot.endswith('.accept') or slot.endswith('.reject'):\n slot = slot[:-7]\n if slot not in ori_ontology[domain]:\n # print(domain, item['name'].split('.', 1), dialogue[\"original_id\"])\n continue\n # if domain in ori_ontology:\n # ori_ontology[domain][slot] += 1\n # else:\n # print(domain, item['name'].split('.', 1), dialogue[\"original_id\"])\n # assert domain in ori_ontology, print(domain, item['name'].split('.', 1), dialogue[\"original_id\"])\n\n if not segment['text']:\n print(slot)\n print(segment)\n print()\n assert turn['utterance'][segment['start_index']:segment['end_index']] == segment['text']\n turn['dialogue_act']['non-categorical'].append({\n 'intent': 'inform',\n 'domain': domain,\n 'slot': slot,\n 'value': segment['text'].lower(),\n 'start': segment['start_index'],\n 'end': segment['end_index']\n })\n log_ontology(turn['dialogue_act']['non-categorical'], ontology, ori_ontology)\n dialogue['turns'].append(turn)\n processed_dialogue.append(dialogue)\n # pprint(ori_ontology)\n # save ontology json\n json.dump(ontology, open(os.path.join(self_dir, 'ontology.json'), 'w'), indent=2)\n json.dump(processed_dialogue, open('data.json', 'w'), indent=2)\n write_zipped_json(os.path.join(self_dir, 'data.zip'), 'data.json')\n os.remove('data.json')\n else:\n # read from file\n processed_dialogue = read_zipped_json(os.path.join(self_dir, 'data.zip'), 'data.json')\n ontology = json.load(open(os.path.join(self_dir, 'ontology.json')))\n return processed_dialogue, ontology\n\nif __name__ == '__main__':\n preprocess()\n","repo_name":"thu-coai/ConvLab-2","sub_path":"data/unified_datasets/taskmaster/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":20395,"program_lang":"python","lang":"en","doc_type":"code","stars":429,"dataset":"github-code","pt":"34"} +{"seq_id":"72780768416","text":"\"\"\"\n출처: https://www.acmicpc.net/problem/10814\n\"\"\"\n\nif __name__ == '__main__':\n size = int(input())\n persons = []\n for i in range(size):\n age, name = map(str, input().split())\n persons.append((i, int(age), name))\n\n for idx, age, name in sorted(persons, key=lambda x: (x[1], x[0])):\n print(age, name)","repo_name":"bum12ark/algorithm","sub_path":"python/baekjoon/step/12-sortation/sort-by-age.py","file_name":"sort-by-age.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"34"} +{"seq_id":"12811279122","text":"from src.Database.CourseSectionMapper import CourseSectionMapper\nfrom src.Entities.CourseSection import CourseSection\n\n\nclass CourseSectionFactory():\n \"\"\"\n singleton\n responsibility is to create a single creation point\n for course section objects\n\n course section mapper will take care of the details of\n loading the data from the database (including composing\n objects) from db\n\n all the factory does is call the correct method on the\n mapper and piece the data together to deliver a\n course section object\n \"\"\"\n\n __instance = None\n\n @staticmethod\n def getInstance():\n \"\"\" Static access method. \"\"\"\n if CourseSectionFactory.__instance == None:\n CourseSectionFactory()\n return CourseSectionFactory.__instance\n\n def __init__(self):\n \"\"\" Virtually private constructor. \"\"\"\n if CourseSectionFactory.__instance != None:\n raise Exception(\"This class is a singleton!\")\n else:\n CourseSectionFactory.__instance = self\n\n def build_course_sections(self, course_section_data):\n \"\"\"\n course_section_data is list of dicts in which key-val pairs correspond to\n kwargs in build course section\n \"\"\"\n return [self.build_course_section(**row) for row in course_section_data]\n\n def build_course_section(self, *,\n course_id: str, department: str, quarter: str,\n section_number: str, **kwargs):\n \"\"\"\n kwargs are here to allow other objects to use this method without\n knowing the specific arguments - instead they can just toss\n whatever comes back from the database\n \"\"\"\n course_section_mappper = CourseSectionMapper.getInstance()\n course_section_data = course_section_mappper.load(\n course_id=course_id, section_number=section_number,\n department=department, quarter=quarter)\n\n # needs to be done because course_section_data contains\n # keys that are not parameters to course_section\n course_section_kwargs = {\n 'section_number': course_section_data['section_number'],\n 'enrollment_open': course_section_data['enrollment_open'],\n 'capacity': course_section_data['capacity'],\n 'quarter': course_section_data['quarter'],\n 'state': course_section_data['state'],\n 'instructor_permission_required': course_section_data['instructor_permission_required'],\n 'course': course_section_data['course'],\n 'data': {\n 'timeslot_id': course_section_data['timeslot'],\n 'instructor_id': course_section_data['instructor_id']\n }\n }\n\n course_section = CourseSection(**course_section_kwargs)\n\n return course_section\n","repo_name":"noahpselman/oop","sub_path":"src/Factories/CourseSectionFactory.py","file_name":"CourseSectionFactory.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"2824974103","text":"# coding=UTF-8\n\nfrom numpy import *\n\n#k均值聚类算法的三个支持函数 其一 加载数据函数\ndef loadDataSet(fileName): # general function to parse tab -delimited floats 通用函数 解析 制表符 分隔的浮点\n dataMat = [] # assume last column is target value假定最后一列为目标值\n fr = open(fileName)\n for line in fr.readlines():\n curLine = line.strip().split('\\t')\n fltLine = map(float, curLine) # map all elements to float() 将每一行的数据映射成float型 ???????\n dataMat.append(fltLine)\n return dataMat\n\n#k均值聚类算法的三个支持函数 其二 计算欧氏距离\ndef distEclud(vecA, vecB): #计算两个点(行向量)之间的距离\n return sqrt(sum(power(vecA - vecB, 2))) # la.norm(vecA-vecB)\n\n#k均值聚类算法的三个支持函数 其三 根据数据集随机生成k个质心\ndef randCent(dataSet, k):\n n = shape(dataSet)[1] #列的数目:表示点的属性个数\n centroids = mat(zeros((k, n))) # create centroid mat 创建质心矩阵\n for j in range(n): # create random cluster centers, within bounds of each dimension 在每个维度的界限内,创建随机簇中心 (每一次循环创建随机质心的一个属性量)\n minJ = min(dataSet[:, j]) #求J列(J属性)的最小值\n rangeJ = float(max(dataSet[:, j]) - minJ)\n centroids[:, j] = mat(minJ + rangeJ * random.rand(k, 1)) #random.rand(k, 1)产生一个k行1列的数组,即产生一个属性J的随机值,K行表示,有K个点\n return centroids #返回含k个点坐标的点矩阵(n维) K个随机质心\n\n\n########################## 第一个例子 k均值聚类算法 #######################################\ndef kMeans(dataSet, k, distMeas=distEclud, createCent=randCent): #数据集 K个质心 默认距离函数 默认k个随机点生成函数\n m = shape(dataSet)[0] #行数即数据集点的数目\n clusterAssment = mat(zeros((m, 2))) # create mat to assign data points 创建一个和数据集一样长的矩阵用来存储该数据的两个信息(存储数据的分类 和 该数据与所属簇心的距离平方)\n # to a centroid, also holds SSE of each point 对质心来说,同事也存放每个点的SSE值(距离)\n centroids = createCent(dataSet, k) # centroids 质心 调用函数创建随机质心\n clusterChanged = True # 表示 flag\n num = 0\n while clusterChanged:\n num += 1\n #print num, num, num, num, num, num, num, num, num, num #用于测试程序便利的次数\n #print 'asddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd'\n clusterChanged = False\n for i in range(m): #\n #print '对每一个数据点i对每一个数据点i对每一个数据点i对每一个数据点i %d' % i\n # for each data point assign it to the closest centroid 将每一个数据点分配给最近的质心\n minDist = inf #inf 表示正无穷大 -inf 表示负无穷大\n minIndex = -1\n for j in range(k): #\n #print '对每个随机簇心j对每个随机簇心j对每个随机簇心j对每个随机簇心j对每个随机簇心j :%d ' % j\n distJI = distMeas(centroids[j, :], dataSet[i, :]) #计算数据点i到簇心j之间的距离\n if distJI < minDist:\n minDist = distJI\n minIndex = j #找到离数据点最近簇心J 和 距离平方minDist\n if clusterAssment[i, 0] != minIndex: clusterChanged = True\n #在两次for循环中,只要出现了一次点i的簇类发生变化就要再执行一次while##########要重点理解这句话!!!!!!!!\n #直到所有的点不需要分配时\n #如果这个点的需要重新分配簇心J的话,继续下一个点的分配?????这样理解?吗 直到所有的点都分配好了簇心\n clusterAssment[i, :] = minIndex, minDist ** 2 #存放该点的簇心类别和误差(距离平方)\n #for循环之后已经找到了所有点所属的类别和与中心的误差\n #print \"\\ncentroids 输出当前使用的 随机生成的K个质心:\\n\", centroids #打印质心 书上为什么要把这句话放在这里呢???????没道理啊\n #执行一次上面的while程序之后,会给每个点分配一个簇类,执行下面的while程序用全部的点计算此时的各个簇心。\n # 第二次while循环时用更新后的簇心来给每一个点分簇类,直至某一次while循环中所有的点的簇类都没有被更新/纠正。\n # (因为第一次给所有点分的簇类通常存在不合理的,所以程序还会有第二次while循环)\n for cent in range(k): # recalculate centroids 重新计算质心\n ptsInClust = dataSet[nonzero(clusterAssment[:, 0].A == cent)[0]] #!!!!!! .A是将前面的转换成数组(这样就可以读取数组的行列的大小了,矩阵是不能直接读取大小的)\n #认真分析上面这句,== 是一个判断语句,成立则为1,否则为0,在利用nonezero()[0]找到clusterAssment的第一列为cent的行的下标。\n #dataSet[行下标列表]就可以提取出其中属于cent类的行样本(点)。\n #在类簇评估矩阵的第0列(即簇类)的所有行找到是cent类的数据 # get all the point in this cluster 获取这个簇的所有点\n centroids[cent, :] = mean(ptsInClust, axis=0) # assign centroid to mean  按列求和,直接想象成将数据按列亚索成一行,最后的到一个行向量,再存放在centroids质心中\n return centroids, clusterAssment #返回k个 簇中心点的坐标(k行n列的矩阵) 簇评估分配结果(m行2列 列0存放类,列1 存放该点与该簇心的距离平方)\n\n\n#########################    第二个例子 二分k-均值聚类算法 ###############################################\ndef biKmeans(dataSet, k, distMeas=distEclud):\n m = shape(dataSet)[0]\n clusterAssment = mat(zeros((m,2)))\n centroid0 = mean(dataSet, axis=0).tolist()[0]#这里的0如何理解?????#dataSet是一个m维数组(元组),menan之后是一个1维数组,.tolist()之后是列表\n centList =[centroid0] #这个[列表]是什么意思?????? #create a list with one centroid 列表存放质心的坐标\n for j in range(m): #calc initial Error 计算每一个点到质心的距离平方 并存放在1列中\n clusterAssment[j,1] = distMeas(mat(centroid0), dataSet[j,:])**2\n while (len(centList) < k): #将质心存放在列表cenList中 质心的数量小于k说明还需要继续划分(刚开始的时候只有一个簇心)\n lowestSSE = inf #假设无穷大\n for i in range(len(centList)): #遍历每一个簇心\n ptsInCurrCluster = dataSet[nonzero(clusterAssment[:,0].A==i)[0],:] #提取出簇心为i的数据 get the data points currently in cluster i\n centroidMat, splitClustAss = kMeans(ptsInCurrCluster, 2, distMeas) #将簇心i二分二分二分二分二分二分二分二分\n sseSplit = sum(splitClustAss[:,1])#compare the SSE to the currrent minimum  计算簇心i二分之后的两个簇的SSE之后\n sseNotSplit = sum(clusterAssment[nonzero(clusterAssment[:,0].A!=i)[0],1]) #计算不是簇心i的SSE (因为这些簇心没有改变过所以直接使用之前计算出的值就能使用)\n #print \"sseSplit, and notSplit SSE : \",sseSplit,sseNotSplit\n if (sseSplit + sseNotSplit) < lowestSSE: #寻找某个簇心i。使的按这个簇心二分之后能够使 SSE最小\n bestCentToSplit = i #存储簇心的i\n bestNewCents = centroidMat #存储新生成的两个簇心\n bestClustAss = splitClustAss.copy() #存储新生成的簇心i的所有数据的评估矩阵\n lowestSSE = sseSplit + sseNotSplit\n bestClustAss[nonzero(bestClustAss[:,0].A == 1)[0],0] = len(centList) #change 1 to 3,4, or whatever 给新生成的簇心点i的类别存放为 len(centList)\n bestClustAss[nonzero(bestClustAss[:,0].A == 0)[0],0] = bestCentToSplit #将不变动的那部分簇心的点类 存放为i\n #print 'the bestCentToSplit is: ',bestCentToSplit\n #print 'the len of bestClustAss is: ', len(bestClustAss)\n centList[bestCentToSplit] = bestNewCents[0,:].tolist()[0] #replace a centroid with two best centroids\n centList.append(bestNewCents[1,:].tolist()[0]) #原来的簇心已经划分成两个簇心了,将新生成的一个簇心替代原来的那个簇心,再将新生成的簇心添加到 簇心列表中去\n clusterAssment[nonzero(clusterAssment[:,0].A == bestCentToSplit)[0],:]= bestClustAss #reassign new clusters, and SSE 更新变种的那部分点所属的簇心和距离平方\n return mat(centList), clusterAssment\n\n\n\n","repo_name":"yangzhaonan18/MLinAction","sub_path":"kMeans0613/kMeans.py","file_name":"kMeans.py","file_ext":"py","file_size_in_byte":9200,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"27511125707","text":"\nimport csv\nfrom collections import Counter\n\nprint(\"****File_To_Dict****\")\nprint(\"1.Read the file as dict\")\nprint(\"2.Write to it\")\nprint(\"3. view by name\")\nprint(\"4.Exit\")\nwhile True:\n choice=int(input(\"enter choice:\"))\n\n if choice==1:\n\n file = open(\"Test.txt\", 'r')\n dict = {}\n\n for line in file:\n x = line.split(\",\")\n a = x[0]\n b = x[1]\n # c=len(b)-1\n # b=b[0:c]\n\n dict[a] = b\n\n print(dict)\n\n elif choice==2:\n file=open(\"Test.txt\",\"a\")\n\n write1=input(\"enter what to append:\")\n file.writelines(\"\\n\")\n\n file.writelines(write1)\n print(\"content added\")\n\n file.close()\n\n\n\n elif choice==3:\n\n\n nme=input(\"hose occupation you want to view?\")\n occu=dict.get(nme,\"b\")\n print(occu)\n\n elif choice==4:\n break\n\n else:\n print(\"wrong choice\")\n\n\n\n \n\n\n\n\n","repo_name":"vrindabhatia999/Python_Projects","sub_path":"Files_to_dictioanary/Dict_File.py","file_name":"Dict_File.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"34"} +{"seq_id":"8914055409","text":"import joblib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom scipy.cluster.hierarchy import dendrogram\n\nfrom .rutilities import install_r_package\n\n\ndef _hclust_to_scipy_linkage(result, plot=True):\n \"\"\"Turn R hclust result obj into scipy linkage matrix format\"\"\"\n # in hclust merge matrix, negative value is for singleton\n raw_linkage = pd.DataFrame(np.array(result[0]))\n nobs = raw_linkage.shape[0] + 1\n raw_linkage[2] = np.array(result[1])\n raw_linkage.index = raw_linkage.index + nobs\n\n # in hclust merge matrix, positive value is for non-singleton\n scipy_linkage = raw_linkage.copy()\n scipy_linkage[raw_linkage.iloc[:, :2] < 0] += nobs\n scipy_linkage[raw_linkage.iloc[:, :2] > 0] += nobs - 1\n total_obs = nobs\n # add the 4th col: number of singleton\n cluster_dict = {}\n labels = list(range(total_obs))\n for cur_cluster_id, (left, right, _) in scipy_linkage.iterrows():\n left = int(left)\n right = int(right)\n cluster_dict[cur_cluster_id] = {\"left\": set(), \"right\": set()}\n if (left < total_obs) and (right < total_obs):\n left = labels[left]\n right = labels[right]\n # merge of 2 original observations\n cluster_dict[cur_cluster_id][\"left\"].add(left)\n cluster_dict[cur_cluster_id][\"right\"].add(right)\n else:\n # left and/or right are cluster\n if left < total_obs:\n left = labels[left]\n cluster_dict[cur_cluster_id][\"left\"].add(left)\n else:\n # node are cluster\n cluster_dict[cur_cluster_id][\"left\"].update(cluster_dict[left][\"left\"])\n cluster_dict[cur_cluster_id][\"left\"].update(cluster_dict[left][\"right\"])\n if right < total_obs:\n right = labels[right]\n cluster_dict[cur_cluster_id][\"right\"].add(right)\n else:\n # node are cluster\n cluster_dict[cur_cluster_id][\"right\"].update(cluster_dict[right][\"left\"])\n cluster_dict[cur_cluster_id][\"right\"].update(cluster_dict[right][\"right\"])\n cur_cluster_id += 1\n\n cluster_records = {}\n for cluster, _sub_dict in cluster_dict.items():\n total_n = len(_sub_dict[\"left\"]) + len(_sub_dict[\"right\"])\n cluster_records[cluster] = total_n\n scipy_linkage[3] = pd.Series(cluster_records)\n\n # dendrogram\n orders = list(result[2])\n labels = list(result[3])\n # correct order of the final dendrogram\n r_order = [labels[i - 1] for i in orders]\n dendro = dendrogram(scipy_linkage.values, no_plot=True)\n python_order = pd.Series({a: b for a, b in zip(dendro[\"leaves\"], r_order)}).sort_index().tolist()\n # python_order = [i[1:] for i in python_order]\n if plot:\n fig, ax = plt.subplots(dpi=300)\n dendro = dendrogram(scipy_linkage.values, labels=tuple(python_order), no_plot=False, ax=ax)\n ax.xaxis.set_tick_params(rotation=90)\n else:\n dendro = dendrogram(scipy_linkage.values, labels=tuple(python_order), no_plot=True)\n return scipy_linkage, python_order, dendro\n\n\nclass Dendrogram:\n def __init__(self, nboot=1000, method_dist=\"correlation\", method_hclust=\"average\", n_jobs=-1):\n self.nboot = nboot\n self.method_dist = method_dist\n self.method_hclust = method_hclust\n self.n_jobs = n_jobs\n\n self.linkage = None\n self.label_order = None\n self.dendrogram = None\n self.edge_stats = None\n\n def fit(self, data):\n \"\"\"\n Fit the dendrogram model.\n\n Parameters\n ----------\n data\n The data is in obs-by-var form, row is obs.\n \"\"\"\n try:\n import rpy2.robjects as ro\n from rpy2.robjects import pandas2ri\n from rpy2.robjects.conversion import localconverter\n from rpy2.robjects.packages import importr\n except ImportError:\n raise ImportError(\n \"Got rpy2 import error, please make sure R, rpy2 and their dependencies are installed. \"\n \"If not, use conda or mamba to install rpy2\"\n )\n importr(\"base\")\n install_r_package(\"pvclust\")\n pvclust = importr(\"pvclust\")\n with localconverter(ro.default_converter + pandas2ri.converter):\n # The data is in obs-by-var form, row is obs. Transpose for R.\n r_df = ro.conversion.py2rpy(data.T)\n if self.n_jobs == -1:\n self.n_jobs = True\n result = pvclust.pvclust(\n r_df,\n nboot=self.nboot,\n method_dist=self.method_dist,\n method_hclust=self.method_hclust,\n parallel=self.n_jobs,\n )\n # dendrogram info\n hclust = result[0]\n linkage, label_order, dendro = _hclust_to_scipy_linkage(hclust, plot=False)\n self.linkage = linkage\n self.label_order = label_order\n self.dendrogram = dendro\n # scores of edges by pvclust bootstrap\n edge_stats = pd.DataFrame(result[1], index=result[1].colnames).T\n edge_stats.index = linkage.index\n child_dict = {}\n # pvclust edge stat is only for parents, here turn it into child basis\n for parent, (left, right, *_) in linkage.iterrows():\n child_dict[int(left)] = edge_stats.loc[parent]\n child_dict[int(right)] = edge_stats.loc[parent]\n self.edge_stats = pd.DataFrame(child_dict).T.sort_index()\n return\n\n def save(self, output_path):\n joblib.dump(self, output_path)\n","repo_name":"lhqing/ALLCools","sub_path":"ALLCools/clustering/pvclust.py","file_name":"pvclust.py","file_ext":"py","file_size_in_byte":5578,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"34"} +{"seq_id":"73577844898","text":"import socket\n\n\ndef socket_check(ipaddr):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n # s = socket.socket()\n s.settimeout(20)\n s.connect(ipaddr[1])\n s.shutdown(2)\n msg = ipaddr[0] + \" http://\" + str(ipaddr[1][0]) + \":\" + str(ipaddr[1][1]) + \" is healthy!\"\n print(msg)\n return True\n except Exception as e:\n msg = ipaddr[0] + \" http://\" + str(ipaddr[1][0]) + \":\" + str(ipaddr[1][1]) + \" is unhealthy!\"\n print(msg, e)\n return False\n","repo_name":"Chaliive/MyDevOps","sub_path":"有用的python方法/socket_check.py","file_name":"socket_check.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"40652962003","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nfrom marionette_harness import parameterized\nfrom telemetry_harness.testcase import TelemetryTestCase\n\n\nclass TestShutdownPingsSucced(TelemetryTestCase):\n \"\"\"Test Firefox shutdown pings.\"\"\"\n\n def tearDown(self):\n super(TestShutdownPingsSucced, self).tearDown()\n\n # We need a fresh profile next run in order that the \"new-profile\" and\n # \"first-shutdown\" pings are sent.\n self.marionette.profile = None\n\n @parameterized(\"pingsender1\", pingsender_version=b\"1.0\")\n @parameterized(\"pingsender2\", pingsender_version=b\"2.0\")\n def test_shutdown_pings_succeed(self, pingsender_version=b\"\"):\n \"\"\"Test that known Firefox shutdown pings are received, with the correct\n X-PingSender-Version headers.\"\"\"\n\n pingsender2_enabled = {b\"1.0\": False, b\"2.0\": True}[pingsender_version]\n self.marionette.set_pref(\n \"toolkit.telemetry.shutdownPingSender.backgroundtask.enabled\",\n pingsender2_enabled,\n )\n\n # Map ping type to expected X-PingSender-Version header. Not all pings\n # will be sent via pingsender, so they might have an empty (binary)\n # string version.\n ping_types = {\n \"event\": pingsender_version,\n \"first-shutdown\": pingsender_version,\n \"main\": b\"\",\n \"new-profile\": pingsender_version,\n }\n\n # We don't need the browser after this, but the harness expects a\n # running browser to clean up, so we `restart_browser` rather than\n # `quit_browser`.\n pings = self.wait_for_pings(\n self.restart_browser,\n lambda p: p[\"type\"] in ping_types.keys(),\n len(ping_types),\n )\n\n self.assertEqual(len(pings), len(ping_types))\n self.assertEqual(set(ping_types.keys()), set(p[\"type\"] for p in pings))\n\n self.assertEqual(\n ping_types, dict((p[\"type\"], p[\"X-PingSender-Version\"]) for p in pings)\n )\n","repo_name":"WaterfoxCo/Waterfox","sub_path":"toolkit/components/telemetry/tests/marionette/tests/client/test_shutdown_pings_succeed.py","file_name":"test_shutdown_pings_succeed.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","stars":3159,"dataset":"github-code","pt":"34"} +{"seq_id":"12342769847","text":"import re\nimport os\nimport sys\nimport json\nimport copy\nimport time\nimport shutil\nimport random\nimport itertools\n\nfrom km.templates.io_attributes import io_attributes\nfrom km.templates.memory_attributes import memory_attributes\nfrom km.templates.switch_attributes import switch_attributes\nfrom km.templates.compute_attributes import compute_attributes\n\n\nrouting_keywords = [ 'LPRT', 'MPRT', 'SSDT', 'MSDT' ]\n\n# ----------------------------------------------------------------------------------------------------------------------\n\nclass Config():\n\n def create_attributes(self, type_attributes):\n attributes = copy.deepcopy(type_attributes)\n\n #\n # Create the Location data.\n #\n if '/redfish.v1.Chassis.1' in attributes:\n chassis = attributes['/redfish.v1.Chassis.1']\n oem_location = chassis.get('Oem', {}).get('Hpe', {}).get('Location', None)\n if oem_location is not None:\n chassis['Oem']['Hpe']['Location'] = self.config['GeoID']\n\n return attributes\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n @staticmethod\n def create_members(data_json, constants, constants_range):\n if 'Members@odata.count' in data_json and type(data_json['Members@odata.count']) is str:\n count_name = data_json['Members@odata.count'][1:-1]\n saved_count = constants[count_name]\n data_json['Members@odata.count'] = len(constants_range[count_name])\n\n member_string = data_json['Members'][0]['@odata.id']\n\n data_json['Members'] = []\n for i in constants_range[count_name]:\n constants[count_name] = i\n data_json['Members'].append({ '@odata.id' : member_string.format(**constants) })\n\n constants[count_name] = saved_count\n\n return data_json\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n @staticmethod\n def create_Switch_data(attribute_name, data_json, constants, constants_range):\n #\n # Switch special case - update endpoint connection.\n #\n if attribute_name.endswith('Fabrics.GenZ.Endpoints.{ENDPOINTS}'):\n component_id = data_json.get('Oem', {}).get('Hpe', {}).get('Location', {}).get('ComponentID', None)\n if component_id:\n data_json['Oem']['Hpe']['Location']['ComponentID'] = int(component_id)\n\n\n @staticmethod\n def create_Compute_data(attribute_name, data_json, constants, constants_range):\n #\n # Compute special case - endpoint has a list of Ports to link to.\n #\n if attribute_name.endswith('Fabrics.GenZ.Endpoints.{ENDPOINTS}'):\n data_json['Links'] = { 'Ports' : [0 for i in constants_range['FABRIC_ADAPTER_PORTS'] ] }\n for i in constants_range['FABRIC_ADAPTER_PORTS']:\n data_json['Links']['Ports'][i] = { '@odata.id': '/redfish/v1/Systems/1/FabricAdapters/1/Ports/{}'.format(i) }\n\n if attribute_name.endswith('Systems.1.FabricAdapters.{FABRIC_ADAPTERS}'):\n data_json['ControllerCapabilities']['FabricAdapterPortCount'] = len(constants_range['FABRIC_ADAPTER_PORTS'])\n\n data_json['Gen-Z']['RIT'] = [ { 'EIM' : 0xffff } for i in range(16) ]\n data_json['Gen-Z']['PIDT'] = [ { 'MinTimeDelay' : 1 } for i in range(32) ]\n\n\n @staticmethod\n def create_IO_data(attribute_name, data_json, constants, constants_range):\n #\n # IO mimics Compute, so we just call its function.\n #\n Config.create_Compute_data(attribute_name, data_json, constants, constants_range)\n\n\n @staticmethod\n def create_Memory_data(attribute_name, data_json, constants, constants_range):\n #\n # Memory special case - the memory node has 12 switch ports and only 6 endpoints. Also, the last endpoint is NOT\n # connected to a media controller.\n #\n if attribute_name.endswith('Fabrics.GenZ.Switches.Switch1.Ports.{SWITCH_PORTS}'):\n if constants['SWITCH_PORTS'] >= 5:\n del data_json['Links']\n\n if attribute_name.endswith('Chassis.1.MediaControllers.{MEDIA_CONTROLLERS}.Ports.{MEDIA_CONTROLLER_PORTS}'):\n controller_index = constants['MEDIA_CONTROLLERS']\n tokens = data_json['Links']['ConnectedSwitchPorts'][0]['@odata.id'].split('/')\n port_number = controller_index if controller_index >= 3 else controller_index - 1\n tokens[-1] = str(port_number)\n data_json['Links']['ConnectedSwitchPorts'][0]['@odata.id'] = '/'.join(tokens)\n\n if attribute_name.endswith('Fabrics.GenZ.Endpoints.{ENDPOINTS}'):\n if constants['ENDPOINTS'] == 5:\n data_json['Name'] = 'RockStar Local Switch'\n data_json['Description'] = 'RockStar Control Space'\n\n data_json['ConnectedEntities'][0]['EntityType'] = 'Switch'\n data_json['ConnectedEntities'][0]['EntityRole'] = 'Target'\n data_json['ConnectedEntities'][0]['EntityLink'] = { '@odata.id': '/redfish/v1/Fabrics/GenZ/Switches/Switch1' }\n\n del data_json['ConnectedEntities'][1]\n del data_json['Links']\n\n if attribute_name.endswith('Chassis.1.Memory.{MEMORIES}'):\n i = constants['MEMORIES']-1\n data_json['DeviceLocator'] = 'ION {} DIMM {}'.format(1+(i//4), 1+(i%4))\n\n if attribute_name.endswith('Chassis.1.MemoryDomains.{MEMORY_DOMAINS}'):\n if 'InterleavableMemorySets' in data_json:\n data_json['InterleavableMemorySets'][0]['MemorySet'] = [ 0 for i in range(4) ]\n for i in range(1,4+1):\n j = i + 4*(constants['MEMORY_DOMAINS']-1)\n # data_json['InterleavableMemorySets'][i-1] = { '@odata.id': '/redfish/v1/Chassis/1/Memory/{}'.format(i) }\n data_json['InterleavableMemorySets'][0]['MemorySet'][i-1] = { '@odata.id' : '/redfish/v1/Chassis/1/Memory/{}'.format(j) }\n\n if attribute_name.endswith('Chassis.1.MemoryDomains.{MEMORY_DOMAINS}.MemoryChunks.{MEMORY_CHUNKS}'):\n if 'InterleaveSets' in data_json:\n data_json['InterleaveSets'] = [ 0 for i in range(4) ]\n for i in range(1,4+1):\n j = i + 4*(constants['MEMORY_DOMAINS']-1)\n data_json['InterleaveSets'][i-1] = { 'Memory' : { '@odata.id' : '/redfish/v1/Chassis/1/Memory/{}'.format(j) }}\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n @staticmethod\n def create_data(node_type, attribute_name, data_template, constants, constants_range):\n\n data_json = copy.deepcopy(data_template)\n\n #\n # Node specific special cases.\n #\n if node_type == 'IO' : Config.create_IO_data (attribute_name, data_json, constants, constants_range)\n if node_type == 'Memory' : Config.create_Memory_data (attribute_name, data_json, constants, constants_range)\n if node_type == 'Switch' : Config.create_Switch_data (attribute_name, data_json, constants, constants_range)\n if node_type == 'Compute' : Config.create_Compute_data(attribute_name, data_json, constants, constants_range)\n\n #\n # Create member names and resolve constants.\n #\n data_json = Config.create_members(data_json, constants, constants_range)\n\n #\n # Replace all occurrences of '{FIELD}' with the actual value.\n #\n data_string = json.dumps(data_json,indent=4)\n data_string = Config.resolve_constants(data_string, constants)\n\n return data_string\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n @staticmethod\n def resolve_constants(data, constants):\n for c,v in constants.items():\n data = data.replace('{' + c + '}', str(v))\n\n return data\n\n @staticmethod\n def possible_values(constants, all_constants):\n return { x : all_constants[x] for x in constants }\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n @staticmethod\n def process_regular_template(node_type, attribute_name, attribute_data, constants):\n constants_regex = '{[_A-Z0-9]+}'\n attributes = {}\n\n data = copy.deepcopy(attribute_data)\n\n #\n # Find the constants in the attribute name.\n #\n name_constants = set([ x[1:-1] for x in re.findall(constants_regex, attribute_name) ])\n name_constants_range = Config.possible_values(name_constants, constants)\n name_constants_combinations = list(itertools.product(*[value for name,value in name_constants_range.items()]))\n\n #\n # Find the constants in the attribute data but are NOT in the attribute name.\n #\n data_constants = set([ x[1:-1] for x in re.findall(constants_regex, data.replace('\\n', '')) ])\n data_constants = data_constants - name_constants\n data_constants_range = Config.possible_values(data_constants, constants)\n data_constants_combinations = list(itertools.product(*[value for name,value in data_constants_range.items()]))\n\n #\n # Loop over all of the possibilities and resolve the constants.\n #\n for c in name_constants_combinations:\n d = dict(zip(name_constants, c))\n f = attribute_name.format(**d)\n\n instance_data = Config.resolve_constants(data, d)\n data_json = json.loads(instance_data)\n\n name = '/' + f\n if name not in attributes:\n if len(data_constants) == 0:\n attributes[name] = json.loads(instance_data)\n else:\n for x in data_constants_combinations:\n d = dict(zip(data_constants, x))\n\n data_string = Config.create_data(node_type, attribute_name, data_json, d, data_constants_range)\n attributes[name] = json.loads(data_string)\n\n return attributes\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n @staticmethod\n def routing_type_to_entries(node, port_number, routing_type):\n if routing_type in ['LPRT','MPRT']:\n routing_entries = node.routing_data['Ports'][str(port_number)][routing_type]\n else:\n routing_entries = node.routing_data[routing_type]\n\n return routing_entries\n\n\n @staticmethod\n def process_routing_template(node, node_type, attribute_name, attribute_data, constants):\n\n #\n # Routing parameters.\n #\n for routing_type in routing_keywords:\n if routing_type in attribute_name: break\n\n port_type = 'SWITCH_PORTS' if node.node_type() in ['Switch', 'Memory'] else 'FABRIC_ADAPTER_PORTS'\n id_type = 'CIDS' if routing_type in ['LPRT', 'SSDT'] else 'SIDS'\n\n routing_configurations = []\n\n #\n # These files need to have one port number and all the cids/sids that can be reached from that port.\n #\n if re.match(r'.*(LPRT|MPRT|SSDT|MSDT)$', attribute_name):\n if routing_type in ['LPRT','MPRT']:\n for port,port_data in node.routing_data['Ports'].items():\n p = int(port)\n routing_table = port_data[routing_type]\n routing_configurations.append([('SWITCHES', [str(1+p//60)]),\n (port_type, [str(p%60)]),\n (id_type, list(routing_table.keys()))])\n else:\n routing_table = node.routing_data[routing_type]\n routing_configurations.append([(id_type, list(routing_table.keys()))])\n\n #\n # These files need to have one port number and one cid/sid that can be reached from that port.\n #\n if re.match(r'.*(LPRT|MPRT|SSDT|MSDT).({CIDS}|{SIDS})$', attribute_name):\n if routing_type in ['LPRT','MPRT']:\n for port,port_data in node.routing_data['Ports'].items():\n p = int(port)\n routing_table = port_data[routing_type]\n for cid_or_sid in routing_table:\n routing_configurations.append([('SWITCHES', [str(1+p//60)]),\n (port_type, [str(p%60)]),\n (id_type, [ cid_or_sid ])])\n else:\n routing_table = node.routing_data[routing_type]\n for cid_or_sid in routing_table:\n routing_configurations.append([(id_type, [ cid_or_sid ])])\n\n #\n # These files need to have one port number, one cid/sid and all of the routes to reach that cid/sid from the port.\n #\n if re.match(r'.*(LPRT|MPRT|SSDT|MSDT).*.RouteSet$', attribute_name):\n if routing_type in ['LPRT','MPRT']:\n for port,port_data in node.routing_data['Ports'].items():\n p = int(port)\n routing_table = port_data[routing_type]\n for cid_or_sid in routing_table:\n routing_configurations.append([('SWITCHES', [str(1+p//60)]),\n (port_type, [str(p%60)]),\n (id_type, [ cid_or_sid ]),\n ('ROUTES', list(routing_table[cid_or_sid]['Entries'].keys()))])\n else:\n routing_table = node.routing_data[routing_type]\n for cid_or_sid in routing_table:\n routing_configurations.append([(id_type, [ cid_or_sid ]),\n ('ROUTES', list(routing_table[cid_or_sid]['Entries'].keys()))])\n\n #\n # These files need to have one port number, one cid/sid and one routes to reach that cid/sid from the port.\n #\n if re.match(r'.*(LPRT|MPRT|SSDT|MSDT).({CIDS}|{SIDS}).RouteSet.{ROUTES}$', attribute_name):\n if routing_type in ['LPRT','MPRT']:\n for port,port_data in node.routing_data['Ports'].items():\n p = int(port)\n routing_table = port_data[routing_type]\n for cid_or_sid in routing_table:\n for route in routing_table[cid_or_sid]['Entries']:\n routing_configurations.append([('SWITCHES', [str(1+p//60)]),\n (port_type, [str(p%60)]),\n (id_type, [ cid_or_sid ]),\n ('ROUTES', [ route ])])\n else:\n routing_table = node.routing_data[routing_type]\n for cid_or_sid in routing_table:\n for route in routing_table[cid_or_sid]['Entries']:\n routing_configurations.append([(id_type, [ cid_or_sid ]),\n ('ROUTES', [ route ])])\n\n #\n # Process the routing configurations one at a time.\n #\n routing_attributes = {}\n\n for x in routing_configurations:\n for name,value in x:\n constants[name] = value\n\n attribute = Config.process_regular_template(node_type, attribute_name, attribute_data, constants)\n routing_attributes.update(attribute)\n\n return routing_attributes\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n @staticmethod\n def resolve_type(node_type, constants, routing_data, fabric):\n print('preprocessing', node_type)\n\n if node_type == 'IO' : node_attributes = json.loads(io_attributes)\n if node_type == 'Switch' : node_attributes = json.loads(switch_attributes)\n if node_type == 'Memory' : node_attributes = json.loads(memory_attributes)\n if node_type == 'Compute' : node_attributes = json.loads(compute_attributes)\n\n #\n # The routing files depend on the routing variables. We save the global values so we can replace them later.\n #\n constants_copy = copy.deepcopy(constants)\n\n #\n # Loop over all of the attribute templates. We will find all occurrences of variables which need to be\n # resolved. There are 2 sets of variables we are interested in: those that appear in the attribute name\n # and those that appear in the attribute contents. We will need to loop over all possibilities of\n # these variables in order to resolve all possible cases.\n #\n search_term = '({})'.format('|'.join(routing_keywords))\n regex = re.compile(search_term)\n\n regular_templates = list(node_attributes.keys())\n routing_templates = [ attribute_name for attribute_name in regular_templates if routing_data and regex.search(attribute_name) ]\n\n #\n # The regular files don't depend on the routing variables. So we can do them once.\n #\n type_attributes = {}\n for attribute_name in regular_templates:\n attribute_data = json.dumps(node_attributes[attribute_name])\n type_attributes.update(Config.process_regular_template(node_type, attribute_name, attribute_data, constants))\n\n #\n # Process the routing files.\n #\n for name, node in fabric.nodes.items():\n if node.node_type() == node_type:\n print('\\tprocessing', name)\n node.attributes = copy.deepcopy(type_attributes)\n\n #\n # We need specialized routing variables for these types. Therefore we call a method which deduces\n # those variables.\n #\n for attribute_name in routing_templates:\n attribute_data = json.dumps(node_attributes[attribute_name])\n node.attributes.update(Config.process_routing_template(node, node_type, attribute_name, attribute_data, constants))\n\n #\n # Replace the original global constants.\n #\n constants = constants_copy\n","repo_name":"HewlettPackard/ZFM","sub_path":"conf/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":18525,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"34"} +{"seq_id":"71986506657","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\n# pylint: disable=protected-access,too-many-public-methods\n\nfrom hamcrest import is_\nfrom hamcrest import none\nfrom hamcrest import not_none\nfrom hamcrest import has_length\nfrom hamcrest import assert_that\nfrom hamcrest import has_entries\nfrom hamcrest import starts_with\nfrom hamcrest import has_properties\nfrom hamcrest import contains_inanyorder\n\nimport unittest\n\nimport fudge\n\nfrom io import BytesIO\n\nfrom nti.scorm_cloud.client.scorm import ScormCloudService\n\nfrom nti.scorm_cloud.tests import fake_response\nfrom nti.scorm_cloud.tests import SharedConfiguringTestLayer\n\n\nclass TestCourseService(unittest.TestCase):\n\n layer = SharedConfiguringTestLayer\n\n @fudge.patch('nti.scorm_cloud.client.request.ServiceRequest.session')\n def test_get_course_detail(self, mock_ss):\n reply = \"\"\"\n \n \n \n \n \n \n \n 2021-06-22T18:57:00.000+0000\n \n \n \"\"\"\n\n service = ScormCloudService.withargs(\"appid\", \"secret\",\n \"http://cloud.scorm.com/api\")\n course = service.get_course_service()\n\n data = fake_response(content=reply)\n session = fudge.Fake().expects('get').returns(data)\n mock_ss.is_callable().returns(session)\n\n course_data = course.get_course_detail('31796ffa-e7b0-4848-a8dd-45a8e0933482')\n assert_that(course_data, has_properties('title', 'ASPIRE Alpha',\n 'tags', ['6819436859104098208', 'alpha.dev'],\n 'learningStandard', 'cmi5'))\n\n @fudge.patch('nti.scorm_cloud.client.request.ServiceRequest.session')\n def test_import_uploaded_course(self, mock_ss):\n service = ScormCloudService.withargs(\"appid\", \"secret\",\n \"http://cloud.scorm.com/api\")\n course = service.get_course_service()\n\n course_id = 'courseid'\n path = BytesIO(b'data')\n reply = \"\"\"\n \n Photoshop Example -- Competency\n Import Successful\n \n [warning text]\n \n \n \"\"\"\n reply = '%s' % reply\n data = fake_response(content=reply)\n session = fudge.Fake().expects('post').returns(data)\n mock_ss.is_callable().returns(session)\n\n result_list = course.import_uploaded_course(course_id, path)\n assert_that(result_list[0],\n has_properties('title', 'Photoshop Example -- Competency',\n 'message', 'Import Successful',\n 'parserWarnings', ['[warning text]'],\n 'wasSuccessful', True))\n\n @fudge.patch('nti.scorm_cloud.client.request.ServiceRequest.session')\n def test_import_uploaded_course_async(self, mock_ss):\n service = ScormCloudService.withargs(\"appid\", \"secret\",\n \"http://cloud.scorm.com/api\")\n course = service.get_course_service()\n\n course_id = 'courseid'\n path = BytesIO(b'data')\n reply = \"\"\"\n \n e2bfa26e-2e96-48e3-86a6-f435fba6dccb\n \n \"\"\"\n reply = '%s' % reply\n data = fake_response(content=reply)\n session = fudge.Fake().expects('post').returns(data)\n mock_ss.is_callable().returns(session)\n token = course.import_uploaded_course_async(course_id, path)\n assert_that(token, is_('e2bfa26e-2e96-48e3-86a6-f435fba6dccb'))\n\n @fudge.patch('nti.scorm_cloud.client.request.ServiceRequest.session')\n def test_get_async_import_result(self, mock_ss):\n service = ScormCloudService.withargs(\"appid\", \"secret\",\n \"http://cloud.scorm.com/api\")\n course = service.get_course_service()\n\n token = 'e2bfa26e-2e96-48e3-86a6-f435fba6dccb'\n success_reply = \"\"\"\n finished\n \n \n Photoshop Example -- Competency\n Import Successful\n \n \n \"\"\"\n success_reply = '%s' % success_reply\n data = fake_response(content=success_reply)\n session = fudge.Fake().expects('get').returns(data)\n mock_ss.is_callable().returns(session)\n import_result = course.get_async_import_result(token)\n assert_that(import_result, has_properties('title', 'Photoshop Example -- Competency',\n 'status', 'finished',\n 'error_message', none()))\n\n unsuccessful_reply = \"\"\"\n finished\n \n \n Photoshop Example -- Competency\n zip did not contain courses\n \n \n \"\"\"\n unsuccessful_reply = '%s' % unsuccessful_reply\n data = fake_response(content=unsuccessful_reply)\n session = fudge.Fake().expects('get').returns(data)\n mock_ss.is_callable().returns(session)\n import_result = course.get_async_import_result(token)\n assert_that(import_result, has_properties('title', 'Photoshop Example -- Competency',\n 'status', 'error',\n 'error_message', 'zip did not contain courses'))\n\n error_reply = \"\"\"\n error\n Error during import\n \"\"\"\n error_reply = '%s' % error_reply\n data = fake_response(content=error_reply)\n session = fudge.Fake().expects('get').returns(data)\n mock_ss.is_callable().returns(session)\n import_result = course.get_async_import_result(token)\n assert_that(import_result, has_properties('title', none(),\n 'status', 'error',\n 'error_message', 'Error during import'))\n\n running_reply = \"\"\"\n running\n \"\"\"\n running_reply = '%s' % running_reply\n running_reply = '%s' % running_reply\n data = fake_response(content=running_reply)\n session = fudge.Fake().expects('get').returns(data)\n mock_ss.is_callable().returns(session)\n import_result = course.get_async_import_result(token)\n assert_that(import_result, has_properties('title', none(),\n 'status', 'running',\n 'error_message', none()))\n\n\n created_reply = \"\"\"\n created\n \"\"\"\n created_reply = '%s' % created_reply\n created_reply = '%s' % created_reply\n data = fake_response(content=created_reply)\n session = fudge.Fake().expects('get').returns(data)\n mock_ss.is_callable().returns(session)\n import_result = course.get_async_import_result(token)\n assert_that(import_result, has_properties('title', none(),\n 'status', 'created',\n 'error_message', none()))\n\n\n @fudge.patch('nti.scorm_cloud.client.request.ServiceRequest.session')\n def test_delete_course(self, mock_ss):\n service = ScormCloudService.withargs(\"appid\", \"secret\",\n \"http://cloud.scorm.com/api\")\n course = service.get_course_service()\n\n reply = ''\n reply = '%s' % reply\n data = fake_response(content=reply)\n session = fudge.Fake().expects('get').returns(data)\n mock_ss.is_callable().returns(session)\n\n result = course.delete_course('courseid')\n success_nodes = result.getElementsByTagName('success')\n assert_that(success_nodes, is_(not_none()))\n\n @fudge.patch('nti.scorm_cloud.client.request.ServiceRequest.session')\n def test_get_assets(self, mock_ss):\n service = ScormCloudService.withargs(\"appid\", \"secret\",\n \"http://cloud.scorm.com/api\")\n course = service.get_course_service()\n\n reply = u'bytes\\uFFFD'\n data = fake_response(content=reply)\n session = fudge.Fake().expects('get').returns(data)\n mock_ss.is_callable().returns(session)\n\n result = course.get_assets('courseid')\n assert_that(result, is_(reply))\n\n @fudge.patch('nti.scorm_cloud.client.request.ServiceRequest.session')\n def test_get_course_list(self, mock_ss):\n service = ScormCloudService.withargs(\"appid\", \"secret\",\n \"http://cloud.scorm.com/api\")\n course = service.get_course_service()\n\n reply = \"\"\"\n \n \n \n test1\n test2\n \n \n \n \n \n \n \"\"\"\n reply = '%s' % reply\n data = fake_response(content=reply)\n session = fudge.Fake().expects('get').returns(data)\n mock_ss.is_callable().returns(session)\n\n course_list = course.get_course_list()\n assert_that(course_list, has_length(2))\n assert_that(course_list[0],\n has_properties('title', 'Photoshop Example -- Competency',\n 'courseId', 'test321',\n 'numberOfVersions', '-1',\n 'numberOfRegistrations', '2',\n 'tags', contains_inanyorder('test1', 'test2')))\n assert_that(course_list[1],\n has_properties('title', 'Another Test Course',\n 'courseId', 'course321',\n 'numberOfVersions', '-1',\n 'numberOfRegistrations', '5',\n 'tags', []))\n\n def test_get_preview_url(self):\n service = ScormCloudService.withargs(\"appid\", \"secret\",\n \"http://cloud.scorm.com/api\")\n course = service.get_course_service()\n #url = course.get_preview_url('courseid', 'about:none')\n #assert_that(url, starts_with(\"http://cloud.scorm.com/api?\"))\n\n @fudge.patch('nti.scorm_cloud.client.request.ServiceRequest.session')\n def test_get_metadata(self, mock_ss):\n service = ScormCloudService.withargs(\"appid\", \"secret\",\n \"http://cloud.scorm.com/api\")\n course = service.get_course_service()\n\n reply = \"\"\"\n \n \n Package Title\n Package Description\n Package Duration\n 0\n \n Training\n \n \n \n \n \"\"\"\n reply = '%s' % reply\n data = fake_response(content=reply)\n session = fudge.Fake().expects('get').returns(data)\n mock_ss.is_callable().returns(session)\n\n metadata = course.get_metadata('courseid')\n assert_that(metadata,\n has_properties('title', 'Root Title'))\n\n def test_get_property_editor_url(self):\n service = ScormCloudService.withargs(\"appid\", \"secret\",\n \"http://cloud.scorm.com/api\")\n course = service.get_course_service()\n url = course.get_property_editor_url('courseid')\n assert_that(url, starts_with(\"http://cloud.scorm.com/api?\"))\n\n @fudge.patch('nti.scorm_cloud.client.request.ServiceRequest.session')\n def test_get_attributes(self, mock_ss):\n service = ScormCloudService.withargs(\"appid\", \"secret\",\n \"http://cloud.scorm.com/api\")\n course = service.get_course_service()\n\n reply = \"\"\"\n \n \n \n \n \n \n \n \"\"\"\n reply = '%s' % reply\n data = fake_response(content=reply)\n session = fudge.Fake().expects('get').returns(data)\n mock_ss.is_callable().returns(session)\n\n attributes = course.get_attributes('courseid')\n assert_that(attributes,\n has_entries('alwaysFlowToFirstSco', 'false',\n 'commCommitFrequency', '10000',\n 'commMaxFailedSubmissions', '2',\n 'validateInteractionResponses', 'true',\n 'wrapScoWindowWithApi', 'false'))\n\n @fudge.patch('nti.scorm_cloud.client.request.ServiceRequest.session')\n def test_update_assets(self, mock_ss):\n service = ScormCloudService.withargs(\"appid\", \"secret\",\n \"http://cloud.scorm.com/api\")\n course = service.get_course_service()\n\n path = BytesIO(b'data')\n reply = ''\n reply = '%s' % reply\n data = fake_response(content=reply)\n session = fudge.Fake().expects('post').returns(data)\n mock_ss.is_callable().returns(session)\n\n result = course.update_assets('courseid', path)\n success_nodes = result.getElementsByTagName('success')\n assert_that(success_nodes, is_(not_none()))\n\n @fudge.patch('nti.scorm_cloud.client.request.ServiceRequest.session')\n def test_update_attributes(self, mock_ss):\n service = ScormCloudService.withargs(\"appid\", \"secret\",\n \"http://cloud.scorm.com/api\")\n course = service.get_course_service()\n\n reply = \"\"\"\n \n \n \n \n \"\"\"\n reply = '%s' % reply\n data = fake_response(content=reply)\n session = fudge.Fake().expects('get').returns(data)\n mock_ss.is_callable().returns(session)\n\n result = course.update_attributes('courseid', {'showCourseStructure': False,\n 'showNavBar': True})\n assert_that(result,\n has_entries('showCourseStructure', 'false',\n 'showNavBar', 'true'))\n","repo_name":"OpenNTI/nti.scorm_cloud","sub_path":"src/nti/scorm_cloud/tests/test_course.py","file_name":"test_course.py","file_ext":"py","file_size_in_byte":16526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"25839820549","text":"from environments.blackjack_environment import BlackJackEnv, PlayerType, BlackJackEnvCC\nimport sys\nimport numpy as np\n\nbjenv = BlackJackEnvCC()\nself = bjenv\nbjenv.render()\n\nnum_decks = bjenv.num_decks\n\nbjenv.s\n\n\ndef create_projection(low_value_limit = 6, med_value_limit = 9):\n \"\"\"\n This helps define how 'warm' the deck is.\n \"\"\"\n proj = np.zeros((1,10))\n\n for i in range(10):\n if i <= low_value_limit - 2:\n proj[0,i] = -1\n elif i > med_value_limit - 2:\n proj[0,i] = 1\n\n return proj\n\nproj = create_projection()\n\ndef get_cc_component(state, proj):\n res = np.dot(\n state[1],\n proj.transpose()\n )\n return res[0,0]\n\nget_cc_component(bjenv.s, proj)\n\ncc_res = 150\n\nq_tensor = np.zeros([len(bjenv.action_space), bjenv.state_bounds()[1], cc_res])\n\n# if we have a q_table from regular blackjack, try to init the\n# q_tensor with values from here.\n\ntry:\n # initialise the agent with knowledge on how to play regular blackjack.\n q_t = q_table.transpose()\nexcept:\n # no prior knowledge, just play and learn as you go.\n q_t = None\n\nfor i in range(cc_res):\n q_tensor[:,:,i] = q_t\n\n\ndef decompose_state(state, proj, cc_res):\n s = state[0]\n c = int(get_cc_component(state, proj) + cc_res/2)\n return s,c\n\nimport random\nfrom IPython.display import clear_output\n\n# Hyperparameters\nalpha = 0.07\ngamma = 0.7\nepsilon = 0.25\n\n# For plotting metrics\nall_epochs = []\nall_penalties = []\ni = 1\n\nmax_rounds = int(1e6 + 1)\nhard_reset=True\n\nfor i in range(1, max_rounds):\n if i > 1:\n hard_reset = False\n\n state = bjenv.reset(hard_reset)\n s,c = decompose_state(state, proj, cc_res)\n\n epochs, penalties, reward, = 0, 0, 0\n done = False\n\n while not done:\n if random.uniform(0, 1) < epsilon or min(q_tensor[:,s,c]) == max(q_tensor[:, s,c]):\n action_idx, action = bjenv.sample_action() # Explore action space\n else:\n action_idx = np.argmax(q_tensor[:,s,c]) # Exploit learned values\n action = bjenv.action_space[action_idx]\n\n next_state, reward, done, info = bjenv.step(action)\n ns, nc = decompose_state(next_state, proj, cc_res)\n\n #old_value = q_table[state, action_idx]\n old_value = q_tensor[action_idx,s,c]\n next_max = np.max(q_tensor[:,ns,nc])\n\n new_value = (1 - alpha) * old_value + alpha * (reward + gamma * next_max)\n q_tensor[action_idx,s,c] = new_value\n\n if reward < 0:\n penalties += 1\n\n state = next_state\n s,c = ns, nc\n epochs += 1\n\n if i % 100 == 0:\n clear_output(wait=True)\n print(f\"Episode: {i}\")\n\nprint(\"Training finished.\\n\")\n\n\n\ndef play_game():\n state = bjenv.reset()\n epochs, penalties, reward = 0, 0, 0\n\n done = False\n\n #bjenv.render()\n s,c = decompose_state(state, proj, cc_res)\n\n #c - (cc_res*0.5)\n\n while not done:\n #q_tensor[:,s,c]\n action_idx = np.argmax(q_tensor[:,s,c])\n action = bjenv.action_space[action_idx]\n action\n\n state, reward, done, info = bjenv.step(action)\n s,c = decompose_state(state, proj, cc_res)\n #bjenv.render()\n\n\n return reward\n\n\n\n# evaluate performance\nlosses = 0\ndraws = 0\nwins = 0\nblackjacks = 0\ncummulative_reward = 0\n\nnum_games = int(1e4)\n\nbjenv.reset(True)\nfor i in range(num_games):\n reward = play_game()\n cummulative_reward += reward\n\n if reward < 0:\n losses += 1\n\n if reward == 0:\n draws += 1\n\n if reward > 0:\n wins += 1\n\n if reward > 1:\n blackjacks += 1\n\n\ncummulative_reward/num_games\n\nlosses/num_games\ndraws/num_games\nwins/num_games\nblackjacks/num_games\n\n\n\n\n\n# evaluate performance if we choose to play with a biased deck.\n\n\ndef play_game_biased(deck_idx_min = 15, deck_idx_max = 15):\n \"\"\"\n Allow the ability to choose when to play based on the\n heat of the deck\n \"\"\"\n state = bjenv.reset()\n s,c = decompose_state(state, proj, cc_res)\n epochs, penalties, reward = 0, 0, 0\n\n done = False\n\n #bjenv.render()\n c_value = c - (cc_res*0.5)\n if not (deck_idx_min <= c_value <= deck_idx_max):\n played = False\n return 0, played\n\n played = True\n\n #c - (cc_res*0.5)\n\n while not done:\n #q_tensor[:,s,c]\n action_idx = np.argmax(q_tensor[:,s,c])\n action = bjenv.action_space[action_idx]\n action\n\n state, reward, done, info = bjenv.step(action)\n s,c = decompose_state(state, proj, cc_res)\n #bjenv.render()\n\n\n return reward, played\n\n\nlosses = 0\ndraws = 0\nwins = 0\nblackjacks = 0\ncummulative_reward = 0\n\nnum_games = int(1e6)\nnum_games_played = 0\n\nfor i in range(num_games):\n reward, played = play_game_biased(15,100)\n if played:\n cummulative_reward += reward\n num_games_played += 1\n\n if reward < 0:\n losses += 1\n\n if reward == 0:\n draws += 1\n\n if reward > 0:\n wins += 1\n\n if reward > 1:\n blackjacks += 1\n\nnum_games_played\ncummulative_reward/num_games_played\n\nlosses/num_games_played\ndraws/num_games_played\nwins/num_games_played\nblackjacks/num_games_played\n","repo_name":"smstojanovic/RL-Playground","sub_path":"qlearning/blackjack_card_count.py","file_name":"blackjack_card_count.py","file_ext":"py","file_size_in_byte":5165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"16220531284","text":"\"\"\"\nAuthor: Phung Xuan Anh\n\"\"\"\n\nimport redis\nimport random\nimport datetime\n\nPRESENCE_STATUS = 1\nABSENCE_STATUS = 0\nREDIS_CONFIGS = {'host': 'localhost', 'port': 6379, 'db': 1}\n\n\ndef get_redis_client(redis_configs):\n try:\n client = redis.StrictRedis(host=redis_configs[\"host\"], port=redis_configs[\"port\"], db=redis_configs[\"db\"], socket_timeout=5)\n client.ping()\n return client\n except:\n print('Can not connect to redis server')\n return None\n\n\ndef generate_binary_string_randomly(length):\n if length < 0:\n print(\"length of string must be larger than 0\")\n return None\n\n random_number = random.randint(0, 2**length - 1)\n _binary = format(random_number, 'b')\n binary = \"0\" * (length - len(_binary))\n binary = binary + _binary\n return binary\n\n\ndef generate_attendance_randomly(date, number_users):\n if number_users <= 0:\n print('number_users must be unsigned integer')\n return False\n\n try:\n date = datetime.datetime(date[\"year\"], date[\"month\"], date[\"day\"]).strftime(\"%Y-%m-%d\")\n key_name = 'attendance:{}'.format(date)\n except Exception as e:\n print(\"You entered invalid date: {}\".format(e))\n return False\n\n r_client = get_redis_client(REDIS_CONFIGS)\n if not r_client:\n return False\n\n binary_str = generate_binary_string_randomly(number_users)\n print(\"Data of {} is {}\".format(date, binary_str))\n\n for user_id in range(0, number_users):\n r_client.setbit(name=key_name,\n offset=user_id,\n value=int(binary_str[user_id]))\n return True\n\n\ndef get_attendance_a_day(date, number_users):\n if number_users <= 0:\n print(\"number_users must be an unsigned integer\")\n return None\n\n try:\n date = datetime.datetime(date[\"year\"], date[\"month\"], date[\"day\"]).strftime(\"%Y-%m-%d\")\n key_name = 'attendance:{}'.format(date)\n except Exception as e:\n print(\"You entered invalid date: {}\".format(e))\n return None\n\n r_client = get_redis_client(REDIS_CONFIGS)\n if not r_client:\n return None\n\n if not r_client.exists(key_name):\n print(\"Data of day {} does not exist\".format(date))\n return None\n\n ids_presence = []\n ids_absence = []\n\n for user_id in range(0, number_users):\n if r_client.getbit(key_name, user_id) == PRESENCE_STATUS:\n ids_presence.append(user_id)\n else:\n ids_absence.append(user_id)\n return {\n \"ids_presence\": ids_presence,\n \"ids_absence\": ids_absence\n }\n\n\ndef get_attendance_consecutive_days(first_date, number_users):\n if number_users <= 0:\n print(\"number_users must be an unsigned integer\")\n return None\n\n try:\n _first_date = datetime.datetime(first_date[\"year\"], first_date[\"month\"], first_date[\"day\"])\n _second_date = (_first_date + datetime.timedelta(days=1))\n\n key_first_date = 'attendance:{}'.format(_first_date.strftime(\"%Y-%m-%d\"))\n key_second_date = 'attendance:{}'.format(_second_date.strftime(\"%Y-%m-%d\"))\n except Exception as e:\n print(\"You entered invalid date: {}\".format(e))\n return None\n\n r_client = get_redis_client(REDIS_CONFIGS)\n if not r_client:\n return None\n\n if not r_client.exists(key_first_date) or not r_client.exists(key_second_date):\n print('Data of date {} or {} is not exist'.format(_first_date, _second_date))\n return None\n\n # calculate users presence 2 consecutive days\n r_client.bitop('AND',\n 'presence_2_consecutive_days',\n key_first_date,\n key_second_date)\n\n # calculate users absence 2 consecutive days\n r_client.bitop('OR',\n 'absence_2_consecutive_days',\n key_first_date,\n key_second_date)\n\n ids_presence_2_consecutive_days = []\n ids_absence_2_consecutive_days = []\n\n for user_id in range(0, number_users):\n if r_client.getbit('presence_2_consecutive_days', user_id) == PRESENCE_STATUS:\n ids_presence_2_consecutive_days.append(user_id)\n\n if r_client.getbit('absence_2_consecutive_days', user_id) == ABSENCE_STATUS:\n ids_absence_2_consecutive_days.append(user_id)\n\n # print(r_client.bitcount('presence_2_consecutive_days'))\n\n return {\n \"ids_presence\": ids_presence_2_consecutive_days,\n \"ids_absence\": ids_absence_2_consecutive_days\n }\n\n\nif __name__ == '__main__':\n NUMBER_USERS = 100\n dates = [\n {\n \"year\": 2018,\n \"month\": 11,\n \"day\": 3\n },\n {\n \"year\": 2018,\n \"month\": 11,\n \"day\": 4\n }\n ]\n\n print(\"\\n_________________________ generate attendance system data ___________________________\")\n for date in dates:\n generate_attendance_randomly(date=date,\n number_users=NUMBER_USERS)\n\n print(\"\\n_________________________ statistic attendance each day _____________________________\")\n for date in dates:\n result = get_attendance_a_day(date=date,\n number_users=NUMBER_USERS)\n print('-------------- date: {}-{}-{}-----------'.format(date['year'], date['month'], date['day']))\n if result:\n print('counts of presence: ', len(result[\"ids_presence\"]))\n print('ids presence: ', result[\"ids_presence\"])\n print('counts of absence: ', len(result[\"ids_absence\"]))\n print('ids absence: ', result[\"ids_absence\"])\n print(\"\")\n else:\n print('There is no data')\n\n print('\\n__________________________ statistic attendance on 2 consecutive days ______________________')\n result = get_attendance_consecutive_days(first_date=dates[0],\n number_users=NUMBER_USERS)\n if result:\n print('counts of presence on 2 consecutive days: ', len(result['ids_presence']))\n print('user id present on 2 consecutive days: ', result['ids_presence'])\n print('counts of absence on 2 consecutive days: ', len(result['ids_absence']))\n print('user id absent on 2 consecutive days: ', result['ids_absence'])\n else:\n print(\"There is no data\")\n","repo_name":"PhungXuanAnh/python-note","sub_path":"atendance_system/attendance_system.py","file_name":"attendance_system.py","file_ext":"py","file_size_in_byte":6321,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"34"} +{"seq_id":"72746920736","text":"from django.contrib.auth.models import AbstractUser\nfrom django.db import models\n\n\nclass User(AbstractUser):\n\n phone = models.CharField(\n null=True,\n blank=True,\n max_length=11,\n )\n\n address = models.CharField(\n max_length=30,\n null=True,\n blank=True,\n )\n ticket = models.IntegerField(default=0)\n","repo_name":"deadlylaid/amulldanji","sub_path":"amulldanji/users/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"34"} +{"seq_id":"37026492296","text":"import pprint\nimport unittest\n\no = [] # output\na = [\n {\n \"a\": 10,\n \"b\": 20\n }\n]\n\ndef title(v): \n o.append(\"\\n\\n\\n\\n\" + v + \"\\n\")\n\ndef observation(v):\n o.append(\"\\n\\n\" + v)\n\ndef var_dump(v):\n o.append(\"\\n\" + pprint.pformat(v))\n\n# wsgi header\ndef application(environ, start_response):\n status = '200 OK'\n o.append(\"
\")\n   \n    title(\"a\")\n    var_dump(a)\n\n    title(\"a[0]\")\n    var_dump(a[0])\n\n    title(\"a[0][3]\")\n    try:\n      var_dump(a[0][3])\n    except KeyError as e:\n      var_dump(\"Exception KeyError: \" + str(e))\n\n    title(\"a[0][a[0].keys()[0]] to access the first value of a dictionary without knowing the key\")\n    var_dump(a[0][a[0].keys()[0]])\n\n    o.append(\"
\")\n\n# wsgi footer\n response_headers = [('Content-type', 'text/html')]\n start_response(status, response_headers)\n return o\n\nclass UnitTests(unittest.TestCase):\n def testA(self):\n self.assertEqual(a, [{'a': 10, 'b': 20}])\n\n def testB(self):\n self.assertEqual(a[0], {'a': 10, 'b': 20})\n\n def testC(self):\n with self.assertRaises(KeyError):\n a[0][3]\n\n def testD(self):\n self.assertEqual(a[0][a[0].keys()[0]], 10)\n\nif __name__ == '__main__':\n unittest.main() \n","repo_name":"sanoodles/lab","sub_path":"python/map-access.py","file_name":"map-access.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"20752699774","text":"import asyncio\nimport logging\nfrom decimal import Decimal\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, cast\n\nfrom hummingbot.connector.gateway.amm.gateway_evm_amm import GatewayEVMAMM\nfrom hummingbot.connector.gateway.gateway_in_flight_order import GatewayInFlightOrder\nfrom hummingbot.connector.gateway.gateway_price_shim import GatewayPriceShim\nfrom hummingbot.core.data_type.cancellation_result import CancellationResult\nfrom hummingbot.core.data_type.common import TradeType\nfrom hummingbot.core.data_type.in_flight_order import OrderState, OrderUpdate\nfrom hummingbot.core.data_type.trade_fee import TokenAmount\nfrom hummingbot.core.utils import async_ttl_cache\nfrom hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\nfrom hummingbot.logger import HummingbotLogger\n\nif TYPE_CHECKING:\n from hummingbot.client.config.config_helpers import ClientConfigAdapter\n\ns_logger = None\n\n\nclass GatewayNearAMM(GatewayEVMAMM):\n \"\"\"\n Defines basic functions common to connectors that interact with Gateway.\n \"\"\"\n def __init__(self,\n client_config_map: \"ClientConfigAdapter\",\n connector_name: str,\n chain: str,\n network: str,\n address: str,\n trading_pairs: List[str] = [],\n additional_spenders: List[str] = [], # not implemented\n trading_required: bool = True\n ):\n \"\"\"\n :param connector_name: name of connector on gateway\n :param chain: refers to a block chain, e.g. ethereum or avalanche\n :param network: refers to a network of a particular blockchain e.g. mainnet or kovan\n :param address: the address of the eth wallet which has been added on gateway\n :param trading_pairs: a list of trading pairs\n :param trading_required: Whether actual trading is needed. Useful for some functionalities or commands like the balance command\n \"\"\"\n super().__init__(client_config_map=client_config_map,\n connector_name=connector_name,\n chain=chain,\n network=network,\n address=address,\n trading_pairs=trading_pairs,\n additional_spenders=additional_spenders,\n trading_required=trading_required)\n\n @classmethod\n def logger(cls) -> HummingbotLogger:\n global s_logger\n if s_logger is None:\n s_logger = logging.getLogger(cls.__name__)\n return cast(HummingbotLogger, s_logger)\n\n async def update_order_status(self, tracked_orders: List[GatewayInFlightOrder]):\n \"\"\"\n Calls REST API to get status update for each in-flight amm orders.\n \"\"\"\n if len(tracked_orders) < 1:\n return\n\n # split canceled and non-canceled orders\n tx_hash_list: List[str] = await safe_gather(\n *[tracked_order.get_exchange_order_id() for tracked_order in tracked_orders]\n )\n self.logger().debug(\n \"Polling for order status updates of %d orders.\",\n len(tracked_orders)\n )\n update_results: List[Union[Dict[str, Any], Exception]] = await safe_gather(*[\n self._get_gateway_instance().get_transaction_status(\n chain=self.chain,\n network=self.network,\n transaction_hash=tx_hash,\n address=self.address,\n fail_silently=True\n )\n for tx_hash in tx_hash_list\n ], return_exceptions=True)\n for tracked_order, tx_details in zip(tracked_orders, update_results):\n if \"txHash\" not in tx_details:\n continue\n tx_status: int = tx_details.get(\"txStatus\", -1)\n tx_receipt: Optional[Dict[str, Any]] = tx_details.get(\"txReceipt\", None)\n if tx_receipt is not None:\n if tx_status == 1:\n gas_used: int = tx_receipt[\"transaction_outcome\"][\"outcome\"][\"gas_burnt\"]\n gas_price: Decimal = tracked_order.gas_price\n fee: Decimal = Decimal(str(gas_used)) * Decimal(str(gas_price)) / Decimal(str(1e24))\n\n self.processs_trade_fill_update(tracked_order=tracked_order, fee=fee)\n\n order_update: OrderUpdate = OrderUpdate(\n client_order_id=tracked_order.client_order_id,\n trading_pair=tracked_order.trading_pair,\n update_timestamp=self.current_timestamp,\n new_state=OrderState.FILLED,\n )\n\n else: # transaction failed\n order_update: OrderUpdate = OrderUpdate(\n client_order_id=tracked_order.client_order_id,\n trading_pair=tracked_order.trading_pair,\n update_timestamp=self.current_timestamp,\n new_state=OrderState.FAILED,\n )\n\n self._order_tracker.process_order_update(order_update)\n else:\n await self._order_tracker.process_order_not_found(tracked_order.client_order_id)\n\n def get_order_size_quantum(self, trading_pair: str, order_size: Decimal) -> Decimal:\n return Decimal(\"1e-15\")\n\n @property\n def status_dict(self) -> Dict[str, bool]:\n return {\n \"account_balance\": len(self._account_balances) > 0 if self._trading_required else True,\n \"native_currency\": self._native_currency is not None,\n \"network_transaction_fee\": self.network_transaction_fee is not None if self._trading_required else True,\n }\n\n async def start_network(self):\n if self._trading_required:\n self._status_polling_task = safe_ensure_future(self._status_polling_loop())\n self._get_gas_estimate_task = safe_ensure_future(self.get_gas_estimate())\n self._get_chain_info_task = safe_ensure_future(self.get_chain_info())\n\n async def stop_network(self):\n if self._status_polling_task is not None:\n self._status_polling_task.cancel()\n self._status_polling_task = None\n if self._get_chain_info_task is not None:\n self._get_chain_info_task.cancel()\n self._get_chain_info_task = None\n if self._get_gas_estimate_task is not None:\n self._get_gas_estimate_task.cancel()\n self._get_chain_info_task = None\n\n async def cancel_outdated_orders(self, cancel_age: int) -> List[CancellationResult]:\n \"\"\"\n We do not cancel transactions on Near network.\n \"\"\"\n return []\n\n async def update_canceling_transactions(self, canceled_tracked_orders: List[GatewayInFlightOrder]):\n \"\"\"\n Update tracked orders that have a cancel_tx_hash.\n :param canceled_tracked_orders: Canceled tracked_orders (cancel_tx_has is not None).\n \"\"\"\n pass\n\n async def update_token_approval_status(self, tracked_approvals: List[GatewayInFlightOrder]):\n \"\"\"\n Calls REST API to get status update for each in-flight token approval transaction.\n :param tracked_approvals: tracked approval orders.\n \"\"\"\n pass\n\n @async_ttl_cache(ttl=5, maxsize=10)\n async def get_quote_price(\n self,\n trading_pair: str,\n is_buy: bool,\n amount: Decimal,\n ignore_shim: bool = False\n ) -> Optional[Decimal]:\n \"\"\"\n Retrieves a quote price.\n\n :param trading_pair: The market trading pair\n :param is_buy: True for an intention to buy, False for an intention to sell\n :param amount: The amount required (in base token unit)\n :param ignore_shim: Ignore the price shim, and return the real price on the network\n :return: The quote price.\n \"\"\"\n\n base, quote = trading_pair.split(\"-\")\n side: TradeType = TradeType.BUY if is_buy else TradeType.SELL\n\n # Get the price from gateway price shim for integration tests.\n if not ignore_shim:\n test_price: Optional[Decimal] = await GatewayPriceShim.get_instance().get_connector_price(\n self.connector_name,\n self.chain,\n self.network,\n trading_pair,\n is_buy,\n amount\n )\n if test_price is not None:\n # Grab the gas price for test net.\n try:\n resp: Dict[str, Any] = await self._get_gateway_instance().get_price(\n self.chain, self.network, self.connector_name, base, quote, amount, side\n )\n gas_price_token: str = resp[\"gasPriceToken\"]\n gas_cost: Decimal = Decimal(resp[\"gasCost\"])\n self.network_transaction_fee = TokenAmount(gas_price_token, gas_cost)\n except asyncio.CancelledError:\n raise\n except Exception:\n pass\n return test_price\n\n # Pull the price from gateway.\n try:\n resp: Dict[str, Any] = await self._get_gateway_instance().get_price(\n self.chain, self.network, self.connector_name, base, quote, amount, side\n )\n return self.parse_price_response(base, quote, amount, side, price_response=resp, process_exception=False)\n except asyncio.CancelledError:\n raise\n except Exception as e:\n self.logger().network(\n f\"Error getting quote price for {trading_pair} {side} order for {amount} amount.\",\n exc_info=True,\n app_warning_msg=str(e)\n )\n","repo_name":"hummingbot/hummingbot","sub_path":"hummingbot/connector/gateway/amm/gateway_near_amm.py","file_name":"gateway_near_amm.py","file_ext":"py","file_size_in_byte":9794,"program_lang":"python","lang":"en","doc_type":"code","stars":6520,"dataset":"github-code","pt":"34"} +{"seq_id":"22334454780","text":"# -*-coding:Utf-8 -*\n# ----------------------------------------------------------------------\n# Call the modules asked by the user\n# ----------------------------------------------------------------------\n# Packages\n# ----------------------------------------------------------------------\nfrom astropy.coordinates import SkyCoord\nimport configparser as cp\nimport glob\nimport importlib\nfrom muLAn.data import Data\nimport muLAn.iotools as iotools\nfrom muLAn.iotools import LensModel\nimport muLAn.models as mulanmodels\nimport muLAn.models.ephemeris as ephemeris\nfrom muLAn.packages.general_tools import *\nfrom muLAn.instruments import InstrumentsList\nimport muLAn.packages.sortmodels as mulansort\nimport muLAn.plottypes as mulanplots\nimport numpy as np\nimport pandas as pd\nimport os\nimport pickle\nimport scipy\nimport sys\n\n# ====================================================================\n# Fonctions\n# ====================================================================\ndef run_sequence(path_event, options):\n\n # Load configuration files\n cfgsetup = cp.ConfigParser()\n cfgsetup.read([path_event + 'setup.ini', path_event + 'advancedsetup.ini'])\n\n text = \"Load parameter files...\"\n communicate(cfgsetup, 1, text, opts=[printoption.level0], prefix=True, newline=True)\n\n # Deprecated:\n cfgobs = cp.ConfigParser()\n cfgobs.read(path_event + 'observatories.ini')\n # Replaced by:\n fname = \"{:s}/observatories.ini\".format(path_event)\n instruments = InstrumentsList(fname)\n\n # Add the path to the configuration\n cfgsetup.set('FullPaths', 'Event', path_event)\n\n # Check the paths\n if cfgsetup.get('FullPaths', 'Code').replace(\" \", \"\") != \"\":\n if cfgsetup.get('FullPaths', 'Code')[-1] != '/':\n cfgsetup.set('FullPaths', 'Code', cfgsetup.get('FullPaths', 'Code') + '/')\n if cfgsetup.get('FullPaths', 'Event')[-1] != '/':\n cfgsetup.set('FullPaths', 'Event', cfgsetup.get('FullPaths', 'Event') + '/')\n if cfgsetup.get('RelativePaths', 'Data')[-1] != '/':\n cfgsetup.set('RelativePaths', 'Data', cfgsetup.get('RelativePaths', 'Data') + '/')\n if cfgsetup.get('RelativePaths', 'Plots')[-1] != '/':\n cfgsetup.set('RelativePaths', 'Plots', cfgsetup.get('RelativePaths', 'Plots') + '/')\n if cfgsetup.get('RelativePaths', 'Chains')[-1] != '/':\n cfgsetup.set('RelativePaths', 'Chains', cfgsetup.get('RelativePaths', 'Chains') + '/')\n if cfgsetup.get('RelativePaths', 'Outputs')[-1] != '/':\n cfgsetup.set('RelativePaths', 'Outputs', cfgsetup.get('RelativePaths', 'Outputs') + '/')\n if cfgsetup.get('RelativePaths', 'Archives')[-1] != '/':\n cfgsetup.set('RelativePaths', 'Archives', cfgsetup.get('RelativePaths', 'Archives') + '/')\n if cfgsetup.get('RelativePaths', 'ModelsHistory')[-1] != '/':\n cfgsetup.set('RelativePaths', 'ModelsHistory', cfgsetup.get('RelativePaths', 'ModelsHistory') + '/')\n\n if not cfgsetup.has_section('Optimization'):\n cfgsetup.add_section('Optimization')\n if not cfgsetup.has_option('Optimization', 'UseBinaryFiles'):\n cfgsetup.set('Optimization', 'UseBinaryFiles', 'False')\n\n if not cfgsetup.has_section('Modelling'):\n cfgsetup.add_section('Modelling')\n if not cfgsetup.has_option('Modelling', 'IncludeBlending'):\n cfgsetup.set('Modelling', 'IncludeBlending', 'True')\n\n # Take into account manual options\n if options['plot'] != None:\n cfgsetup.set('Controls', 'Modes', 'Plot')\n cfgsetup.set('Plotting', 'Models', options['plot'])\n if options['fit']:\n cfgsetup.set('Controls', 'Modes', 'Fit')\n cond = (options['fit']) and (options['plot'] != None)\n if cond:\n cfgsetup.set('Controls', 'Modes', 'Fit, Plot')\n cfgsetup.set('Plotting', 'Models', options['plot'])\n if options['archive'] != None:\n cfgsetup.set('Controls', 'Archive', options['archive'])\n if options['ncores'] != None:\n if options['ncores'] > 0:\n cfgsetup.set('FitSetupDMCMC', 'Threads', '{:d}'.format(options['ncores']))\n if options['nchains'] != None:\n if options['nchains'] > 0:\n cfgsetup.set('FitSetupDMCMC', 'Chains', '{:d}'.format(options['nchains']))\n if options['resume'] != None:\n if options['resume']: cfgsetup.set('FitSetupDMCMC', 'Resume', 'True')\n if options['verbose'] != None:\n if options['verbose'] > -1:\n cfgsetup.set('Modelling', 'Verbose', '{:d}'.format(options['verbose']))\n if options['optimize'] != None:\n if options['optimize']: cfgsetup.set('Controls', 'Optimize', 'True')\n else: cfgsetup.set('Controls', 'Optimize', 'False')\n\n # Controls\n modes = [a.lower() for a in unpack_options(cfgsetup, 'Controls', 'Modes')]\n cfgsetup.set('Modelling', 'Fit', str(any(x == 'fit' for x in modes)))\n cfgsetup.set('Plotting', 'flag', str(any(x == 'plot' for x in modes)))\n\n # Verbose\n text = \"Parameter files have been read and checked.\"\n communicate(cfgsetup, 4, text, opts=[printoption.good], prefix=False, newline=False)\n\n # Check directories and create missing ones\n paths_to_check = ['Data', 'Plots', 'Outputs', 'Chains', 'Archives']\n for i in range(len(paths_to_check)):\n if not os.path.exists(cfgsetup.get('RelativePaths', paths_to_check[i])):\n os.makedirs(cfgsetup.get('RelativePaths', paths_to_check[i]))\n\n # Test the archive\n if cfgsetup.getboolean('Modelling', 'Fit') & (cfgsetup.getboolean('FitSetupDMCMC', 'Resume')==False)\\\n & (cfgsetup.getint('Modelling', 'Verbose')>0):\n filename = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get('RelativePaths', 'Archives')\n name = prompt(filename, cfgsetup.get('Controls', 'Archive'))\n cfgsetup.set('Controls', 'Archive', name)\n\n # Print the details\n text = \"Event details\"\n communicate(cfgsetup, 3, text, opts=[printoption.level1], prefix=False, newline=True)\n\n text = cfgsetup.get(\"EventDescription\", \"Name\")\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=True, tab=True)\n\n text = \"Original equatorial coordinates: {:s} {:s}\".format(cfgsetup.get(\"EventDescription\", \"RA\"), cfgsetup.get(\"EventDescription\", \"DEC\"))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=True, tab=True)\n\n c_icrs = SkyCoord(ra=cfgsetup.get('EventDescription', 'RA'), dec=cfgsetup.get('EventDescription', 'DEC'), frame='icrs')\n text = \"Equatorial coordinates [deg]: {:.6f} {:.6f}\".format(c_icrs.ra.degree, c_icrs.dec.degree)\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n\n l = c_icrs.transform_to('barycentrictrueecliptic').lon.degree\n b = c_icrs.transform_to('barycentrictrueecliptic').lat.degree\n text = \"Ecliptic coordinates [deg]: {:10.6f} {:10.6f}\".format(l, b)\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n\n l = c_icrs.transform_to('galactic').l.degree\n b = c_icrs.transform_to('galactic').b.degree\n text = \"Galactic coordinates [deg]: {:10.6f} {:10.6f}\".format(l, b)\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n\n text = \"Modelling options\"\n communicate(cfgsetup, 3, text, opts=[printoption.level1], prefix=False, newline=True)\n\n models_temp = np.array(cfgsetup.options(\"Modelling\"))\n cond = np.where(np.array([a.find(\"models_\") for a in cfgsetup.options(\"Modelling\")])==0)\n models_temp = np.atleast_1d(models_temp[cond])\n try:\n a = models_temp[0]\n except:\n raise KeyError(\"No models to load.\")\n models_temp2 = np.atleast_1d([unpack_options(cfgsetup, \"Modelling\", a) for a in models_temp])\n for i in range(len(models_temp)):\n text = \"Models for {:s} observations:\".format(models_temp[i].split(\"_\")[1].upper())\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=True, tab=True)\n for j in range(len(models_temp2[i])):\n a = np.array(models_temp2[i][j].split('/'))\n text = \" {:s} {:.6f} --> {:.6f}\".format(a[1], float(a[0].split(\"-\")[0]), float(a[0].split(\"-\")[1]))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n\n text = \"Minimisation: {:s}\".format(cfgsetup.get(\"Modelling\", \"Method\").upper())\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=True, tab=True)\n\n text = \"List of parameters\"\n communicate(cfgsetup, 3, text, opts=[printoption.level1], prefix=False, newline=True)\n\n counter = 0\n text = \"q {:s}\".format(print_params(unpack_options(cfgsetup, \"Modelling\", \"q\")))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n if text.find(\"within\") > -1: counter = counter + 1\n text = \"s {:s}\".format(print_params(unpack_options(cfgsetup, \"Modelling\", \"s\")))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n if text.find(\"within\") > -1: counter = counter + 1\n text = \"tE {:s}\".format(print_params(unpack_options(cfgsetup, \"Modelling\", \"tE\")))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n if text.find(\"within\") > -1: counter = counter + 1\n text = \"rho {:s}\".format(print_params(unpack_options(cfgsetup, \"Modelling\", \"rho\")))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n if text.find(\"within\") > -1: counter = counter + 1\n text = \"piEN {:s}\".format(print_params(unpack_options(cfgsetup, \"Modelling\", \"piEN\")))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n if text.find(\"within\") > -1: counter = counter + 1\n text = \"piEE {:s}\".format(print_params(unpack_options(cfgsetup, \"Modelling\", \"piEE\")))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n if text.find(\"within\") > -1: counter = counter + 1\n\n text = \"t0 {:s}\".format(print_params(unpack_options(cfgsetup, \"Modelling\", \"t0\")))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n if text.find(\"within\") > -1: counter = counter + 1\n text = \"u0 {:s}\".format(print_params(unpack_options(cfgsetup, \"Modelling\", \"u0\")))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n if text.find(\"within\") > -1: counter = counter + 1\n text = \"alpha {:s}\".format(print_params(unpack_options(cfgsetup, \"Modelling\", \"alpha\")))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n if text.find(\"within\") > -1: counter = counter + 1\n text = \"tp {:s}\".format(cfgsetup.get(\"Modelling\", \"tp\"))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n if text.find(\"within\") > -1: counter = counter + 1\n text = \"tb {:s}\".format(cfgsetup.get(\"Modelling\", \"tb\"))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n\n text = \"Fit parameters\"\n communicate(cfgsetup, 3, text, opts=[printoption.level1], prefix=False, newline=True)\n text = \"Markov Chain Monte Carlo controls:\"\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=True, tab=True)\n\n if (cfgsetup.getint(\"FitSetupDMCMC\", \"Chains\")%2) | (cfgsetup.getint(\"FitSetupDMCMC\", \"Chains\") < 2.0*counter):\n text = \"\\n\\033[1m\\033[91mThe chains number must be even and at least twice the number of fitted\\nparameters. muLAn killed.\\033[0m\"\n sys.exit(text)\n else:\n text = \" {:s} chains in parallel\".format(cfgsetup.get(\"FitSetupDMCMC\", \"Chains\"))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n\n text = \" Length of each chain: {:s}\".format(cfgsetup.get(\"FitSetupDMCMC\", \"ChainLength\"))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n text = \" Maximum number of threads: {:s}\".format(cfgsetup.get(\"FitSetupDMCMC\", \"Threads\"))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n\n text = \"Plot options:\"\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=True, tab=True)\n\n plots_temp = np.atleast_1d(cfgsetup.get(\"Plotting\", \"Type\"))\n options_temp = np.atleast_1d(cfgsetup.get(\"Plotting\", \"Options\"))\n text = \" \"\n [communicate(cfgsetup, 3, text + plots_temp[i] + \": \" + options_temp[i], opts=False, prefix=False, newline=False, tab=True) for i in range(len(plots_temp))]\n\n\n # ----------------------------------------------------------------------\n # Data\n # ----------------------------------------------------------------------\n if cfgsetup.getboolean('Plotting', 'Data') \\\n | cfgsetup.getboolean('Modelling', 'Fit'):\n\n # communicate(cfgsetup, 1, \"\\n\")\n # text = \" Data loading & fit preparation \"\n # communicate(cfgsetup, 1, text, opts=[printoption.reverse])\n\n text = \"Load data\"\n communicate(cfgsetup, 3, text, opts=[printoption.level0], prefix=True, newline=True)\n\n # Data file names\n data2find = np.array(cfgobs.options('ObservatoriesDetails'))\n\n # Cross-match with data to use\n data2use = np.array(cfgsetup.options('Observatories'))\n data2use = np.array([data2find[i] for i in range(len(data2find)) if np.any(data2use == data2find[i])])\n\n # Reference for plotting\n filename = cfgsetup.get('FullPaths', 'Event') + 'setup.ini'\n file = open(filename, 'r')\n for line in file:\n a = line.split(':')[0]\n if a != '':\n a = a.strip().lower()\n if len(np.where(data2use == a)[0]) > 0:\n cfgsetup.set('Observatories', 'Reference', a)\n break\n\n # Cross-match with existing files\n path = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get('RelativePaths', 'Data')\n\n data_filenames = glob.glob(path + '*')\n observatories = [a.split('/')[-1] for a in data_filenames]\n data_filenames = [data_filenames[i] for i in range(len(data_filenames)) if\n np.any(data2use == observatories[i].rpartition('.')[0].lower())]\n observatories = [ob.rpartition('.')[0].lower() for ob in observatories if\n np.any(data2use == ob.rpartition('.')[0].lower())]\n\n obs_properties = dict({'name': [], 'colour': [], 'filter': [], 'gamma': [],\n 'loc': [], 'fluxoumag': [], 'exclude': [], 'key': []})\n # text = 'Data from:\\n'\n for i in range(len(observatories)):\n table = [a.strip() for a in cfgobs.get('ObservatoriesDetails', observatories[i]).split(',')]\n\n obs_properties['name'].append(table[0])\n obs_properties['colour'].append(table[1])\n obs_properties['fluxoumag'].append(table[3])\n obs_properties['loc'].append(table[4])\n obs_properties['key'].append(observatories[i])\n\n try:\n obs_properties['filter'].append(table[2].split(\"=\")[0])\n obs_properties['gamma'].append(float(table[2].split(\"=\")[1]))\n except:\n obs_properties['filter'].append(table[2])\n obs_properties['gamma'].append([0.0])\n\n if (len(table[5:]) > 0):\n if (table[5] != ''):\n obs_properties['exclude'].append(table[5:])\n else:\n obs_properties['exclude'].append(None)\n else:\n obs_properties['exclude'].append(None)\n\n # if i!=len(observatories)-1:\n # text = text + ' ' + table[0] + '\\n'\n # if i==len(observatories)-1:\n # text = text + ' ' + table[0]\n #\n # communicate(cfgsetup, 1, text)\n\n # Parameters of modelling\n model_params = dict()\n interpol_method = dict()\n for i in range(len(obs_properties['loc'])):\n name = 'Models_' + obs_properties['loc'][i]\n table = np.array([a.split('/')[1].strip() for a in unpack_options(cfgsetup, 'Modelling', name)])\n model_params.update({name: table})\n\n table = np.array([a.split('/')[0].strip() for a in unpack_options(cfgsetup, 'Modelling', name)])\n name2 = 'DateRanges_' + obs_properties['loc'][i]\n model_params.update({name2: table})\n\n for j in range(len(unpack_options(cfgsetup, 'Modelling', name))):\n a = unpack_options(cfgsetup, 'Modelling', name)[j]\n a = a.split('/')\n if len(a) == 3:\n name3 = obs_properties['loc'][i] + '#' + a[1] + '#' + a[0]\n t1 = float(a[0].split('-')[0].strip())\n t2 = float(a[0].split('-')[1].strip())\n # print(name3, t1, t2)\n interpol_method.update({name3: [np.linspace(t1, t2, int(a[2])), np.full(int(a[2]), 0, dtype='f8'), np.full(int(a[2]), 0, dtype='f8'), np.full(int(a[2]), 0, dtype='f8')]})\n # print(interpol_method)\n\n # Ephemeris\n path = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get('RelativePaths', 'Data')\n\n if len(obs_properties['loc']) > 1:\n name1 = obs_properties['loc'][np.where(np.array(\n [obs == cfgsetup.get('Observatories', 'Reference').lower()\n for obs in observatories]) == True)[0][0]]\n name1 = glob.glob(path + name1 + '.*')[0]\n else:\n name1 = glob.glob(path + obs_properties['loc'][0] + '.*')[0]\n\n # Load data\n format = {'names': ('id', 'dates', 'magnitude', 'err_magn', 'seeing', 'background'), \\\n 'formats': ('i8', 'f8', 'f8', 'f8', 'f8', 'f8')}\n\n # Event coordinates conversion\n c_icrs = SkyCoord(ra=cfgsetup.get('EventDescription', 'RA'), \\\n dec=cfgsetup.get('EventDescription', 'DEC'),\n frame='icrs')\n l = c_icrs.transform_to('barycentrictrueecliptic').lon.degree\n b = c_icrs.transform_to('barycentrictrueecliptic').lat.degree\n\n # Use Pandas DataFrame to store data\n # ==================================\n filename_bin = \"{:s}/all_data.bin\".format(cfgsetup.get('RelativePaths', 'Data'))\n if (not cfgsetup.getboolean('Optimization', 'UseBinaryFiles'))\\\n | (not os.path.exists(filename_bin)):\n\n data = pd.DataFrame()\n namecol = np.array('id dates magnitude err_magn_orig seeing background'.split())\n namecolf = np.array('id dates flux err_flux_orig seeing background'.split())\n coltype = 'i8 f8 f8 f8 f8 f8'.split()\n coltypet = np.array([np.dtype(a) for a in coltype])\n usecols = range(5)\n coltype = dict(zip(namecol, coltypet))\n coltypef = dict(zip(namecolf, coltypet))\n li = []\n model2load = np.array([])\n text_nb_data = \"\"\n\n # Identify the datasets providing flux\n list_flux = np.array([a for a in observatories \n for i in range(len(obs_properties['key'])) \n if ((a == obs_properties['key'][i]) & \n ((obs_properties['fluxoumag'][i]).lower() == \"flux\"))])\n\n for i in range(len(observatories)):\n # Load data\n flag_flux = any(list_flux == observatories[i])\n if flag_flux:\n df = pd.read_csv(data_filenames[i], sep='\\s+', names=namecolf,\n usecols=usecols, dtype=coltypef, skiprows=1)\n else:\n df = pd.read_csv(data_filenames[i], sep='\\s+', names=namecol,\n usecols=usecols, dtype=coltype, skiprows=1)\n\n # Add dataset name\n df['obs'] = observatories[i]\n nb_data_init = len(df)\n \n # Linear limb darkening coefficient Gamma\n df['gamma'] = obs_properties['gamma'][i]\n \n # Add location for ephemeris\n df['loc'] = obs_properties['loc'][i]\n \n # Rescale the error-bars [see Wyrzykowski et al. (2009)]\n gamma = float(unpack_options(cfgsetup, 'Observatories', observatories[i])[0][1:])\n epsilon = float(unpack_options(cfgsetup, 'Observatories', observatories[i])[1][:-1])\n if flag_flux:\n df['err_flux'] = np.sqrt(np.power(gamma * df['err_flux_orig'],2)\\\n + np.power((np.log(10) * epsilon * df['flux']) / 2.5, 2))\n else:\n df['err_magn'] = np.sqrt(np.power(gamma * df['err_magn_orig'], 2) + epsilon ** 2)\n\n # Select data only in specified time interval\n prop_temp = cfgsetup.get('Observatories', observatories[i]).split(',')\n\n if len(prop_temp) < 3:\n txt = (\"Format error in setup.ini [Observatories]\"\n \"Name : (gamma, epsilon), time1-time2\")\n sys.exit(txt)\n prop_temp = prop_temp[2].replace(' ', '')\n if not prop_temp == '':\n prop_temp = prop_temp.split('-')\n try:\n limits = [float(prop_temp[0]), float(prop_temp[1])]\n except ValueError as err :\n txt = \"{:s}\\n{:s}\\n{:s}\\n{:s} {:s}.\".format(\n \"Format error in setup.ini\",\n \"In [Observatories] you should write:\",\n \"Name : (gamma, epsilon), time1-time2\",\n \"No data will be removed from\",\n data_filenames[i])\n print(err, txt)\n continue\n\n mask = (df['dates'] < limits[0]) | (df['dates'] >= limits[1])\n df.drop(df[mask].index, inplace=True)\n\n # Remove outliers specified in Observatories.ini\n prop_temp = cfgobs.get('ObservatoriesDetails', observatories[i]).split(',')\n if len(prop_temp) > 5:\n idx = np.array([], dtype='i8')\n if prop_temp[5].strip() != '':\n list_temp = [prop_temp[iii].strip() for iii in range(len(prop_temp)) if\n (iii > 4) & (prop_temp[iii].strip() != '')]\n for a in list_temp:\n toremove = np.array(a.split('-'), dtype='i8')\n if len(toremove) == 1: \n idx = np.append(idx, toremove)\n elif len(toremove) == 2: \n n = toremove[1] - toremove[0]\n idx = np.append(idx, np.linspace(toremove[0], toremove[1], n+1, \n endpoint=True, dtype='i8'))\n \n for j in range(idx.shape[0]):\n mask = df['id'] == idx[j]\n df.drop(df[mask].index, inplace=True)\n \n a = float(unpack_options(cfgsetup, \"Observatories\", observatories[i])[2].split(\"-\")[0])\n b = float(unpack_options(cfgsetup, \"Observatories\", observatories[i])[2].split(\"-\")[1])\n text = \"Reading data within {:.6f} --> {:.6f} from {:s}\".format(a, b, data_filenames[i].split(\"/\")[-1])\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n a = len(df)\n b = nb_data_init - a\n if b==0:\n text_nb_data = text_nb_data + \" \\033[1m{:6d}\\033[0m data\\n\".format(a, b)\n else:\n text_nb_data = text_nb_data + \" \\033[1m{:6d}\\033[0m data + \\033[40m\\033[97m\\033[1m{:6d} data excluded\\033[0m\\n\".format(a, b)\n if i==len(observatories)-1:\n text_nb_data = text_nb_data + \" = \\033[1m{:6d}\\033[0m data in total\".format(len(data))\n\n # Calculations from ephemeris for parallax\n name2 = glob.glob(path + obs_properties['loc'][i] + '.*')[0]\n try:\n sTe, sEe, sNe, DsTe, DsEe, DsNe, sTs, sEs, sNs, DsTs, DsEs, DsNs = \\\n ephemeris.Ds(name1, name2, l, b,\n cfgsetup.getfloat('Modelling', 'tp'), cfgsetup)\n if name1 != name2:\n DsN = DsNs\n DsE = DsEs\n else:\n DsN = DsNe\n DsE = DsEe\n df['DsN'] = DsN(df['dates'].values)\n df['DsE'] = DsE(df['dates'].values)\n except:\n DsN = None\n DsE = None\n df['DsN'] = 0\n df['DsE'] = 0\n\n # Models\n name = 'Models_' + obs_properties['loc'][i]\n models_temp = model_params[name]\n name = 'DateRanges_' + obs_properties['loc'][i]\n dates_temp = model_params[name]\n\n df['model'] = 'PSPL'\n\n key = np.array([key for key in interpol_method])\n for j in range(len(models_temp)):\n model2load = np.append(model2load, models_temp[j])\n tmin = float((dates_temp[j]).split('-')[0].strip())\n tmax = float((dates_temp[j]).split('-')[1].strip())\n\n mask = (df['dates'] > tmin) & (df['dates'] <= tmax)\n df.loc[mask, 'model'] = models_temp[j]\n\n if flag_flux:\n try:\n df['magnitude'] = 18.0 - 2.5 * np.log10(df['flux'])\n df['err_magn_orig'] = np.abs(2.5 * df['err_flux_orig']\\\n / (df['flux'] * np.log(10)))\n df['err_magn'] = np.sqrt(np.power(gamma * df['err_magn_orig'], 2) + epsilon ** 2)\n except:\n df['magnitude'] = 0.0\n df['err_magn_orig'] = 0.0\n df['err_magn'] = 0.0\n else:\n # Compute flux from magnitudes\n df['flux'] = np.power( 10, 0.4 * (18.0 - df['magnitude']) )\n df['err_flux_orig'] = np.abs((np.log(10) / 2.5) *\n df['err_magn_orig'] * df['flux'])\n df['err_flux'] = np.abs((np.log(10) / 2.5) * df['err_magn'] * df['flux'])\n\n li.append(df)\n\n # Display data removed and included\n communicate(cfgsetup, 3, text_nb_data, opts=False, prefix=False, newline=True, tab=False)\n\n # Concatenate all the data\n data = pd.concat(li, axis=0, ignore_index=True)\n data.astype({'gamma': np.dtype('f8')})\n\n # Correct dates\n mask = data['dates'] > 2450000\n data.loc[mask, 'dates'] = data.loc[mask, 'dates'] - 2450000\n\n # Create columns for use in fit\n data['amp'] = -1\n data['fs'] = -999\n data['fb'] = -999\n li = ['amp', 'fs', 'fb']\n [data.astype({a: np.dtype('f8')}) for a in li]\n\n # For compatibility, convert DataFrame data into a dictionnary\n time_serie = data.to_dict('list')\n\n # Decide if method interpolation is used or not.\n key_list = np.array([key for key in interpol_method])\n if len(key_list) > 0:\n\n text = \"Ask interpolation\"\n communicate(cfgsetup, 3, text, opts=[printoption.level0], prefix=True, newline=True, tab=False)\n\n for i in range(len(key_list)):\n loc = key_list[i].split('#')[0]\n\n tmin = float(key_list[i].split('#')[2].split('-')[0])\n tmax = float(key_list[i].split('#')[2].split('-')[1])\n\n cond1 = (time_serie['dates'] <= tmax) & (time_serie['dates'] >= tmin) &\\\n (time_serie['loc'] == loc)\n\n # print(loc, len(time_serie['model'][cond1]), len(interpol_method[key_list[i]][0]))\n\n if len(time_serie['model'][cond1]) > len(interpol_method[key_list[i]][0]):\n\n text = \"Relevant for {:s} within {:s} --> {:s}\\n\".format(\n loc,\n key_list[i].split('#')[2].split('-')[0],\n key_list[i].split('#')[2].split('-')[1])\n text = text\\\n + \" {:d} observations / {:d} points asked: \\033[1m\\033[32mOK\\033[0m\".format(\n len(time_serie['model'][cond1]),\n len(interpol_method[key_list[i]][0]))\n # communicate(cfgsetup, 1, text, opts=False)\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=True, tab=True)\n\n time_serie['interpol'][cond1] = key_list[i]\n\n # Ephemeris\n path = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get('RelativePaths', 'Data')\n\n if len(obs_properties['loc']) > 1:\n name1 = obs_properties['loc'][np.where(np.array(\n [obs == cfgsetup.get('Observatories', 'Reference').lower()\n for obs in observatories]) == True)[0][0]]\n name1 = glob.glob(path + name1 + '.*')[0]\n else:\n name1 = glob.glob(path + obs_properties['loc'][0] + '.*')[0]\n\n c_icrs = SkyCoord(ra=cfgsetup.get('EventDescription', 'RA'), \\\n dec=cfgsetup.get('EventDescription', 'DEC'), frame='icrs')\n # print(c_icrs.transform_to('barycentrictrueecliptic'))\n l = c_icrs.transform_to('barycentrictrueecliptic').lon.degree\n b = c_icrs.transform_to('barycentrictrueecliptic').lat.degree\n\n name2 = glob.glob(path + loc + '.*')[0]\n sTe, sEe, sNe, DsTe, DsEe, DsNe, sTs, sEs, sNs, DsTs, DsEs, DsNs = \\\n ephemeris.Ds(name1, name2, l, b, cfgsetup.getfloat('Modelling', 'tp'), \\\n cfgsetup)\n\n if name1 != name2:\n DsN = DsNs\n DsE = DsEs\n else:\n DsN = DsNe\n DsE = DsEe\n\n interpol_method[key_list[i]][1] = DsN(interpol_method[key_list[i]][0])\n interpol_method[key_list[i]][2] = DsE(interpol_method[key_list[i]][0])\n else:\n text = \"Not relevant for {:s} within {:s} --> {:s}\\n\".format(\n loc,\n key_list[i].split('#')[2].split('-')[0],\n key_list[i].split('#')[2].split('-')[1])\n text = text\\\n + \" {:d} observations / {:d} points asked: \\033[1m\\033[31mIGNORED\\033[0m\".format(\n len(time_serie['model'][cond1]),\n len(interpol_method[key_list[i]][0]))\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=True, tab=True)\n\n del interpol_method[key_list[i]]\n\n filename = \"{:s}/all_data.bin\".format(cfgsetup.get('RelativePaths', 'Data'))\n outfile = open(filename,'wb')\n to_dump = [time_serie, model2load]\n pickle.dump(to_dump, outfile)\n outfile.close()\n\n # (Optimization) Load saved data from binary files\n elif cfgsetup.getboolean('Optimization', 'UseBinaryFiles')\\\n & os.path.exists(filename_bin):\n\n text = \"Data from the previous run, loaded from a binary file.\"\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n text = \"If you want to reload all the data, please use option UseBinaryFiles=False in advancedsetup.ini.\"\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=False, tab=True)\n\n filename = \"{:s}/all_data.bin\".format(cfgsetup.get('RelativePaths', 'Data'))\n infile = open(filename,'rb')\n list_input = pickle.load(infile)\n time_serie = list_input[0]\n model2load = list_input[1]\n infile.close()\n\n # Identify which quantities must be fit\n # -------------------------------------\n params = {\n 't0' : np.array([a.strip() for a in cfgsetup.get('Modelling',\n 't0').split(',')]),\\\n 'u0' : np.array([a.strip() for a in cfgsetup.get('Modelling',\n 'u0').split(',')]),\\\n 'tE' : np.array([a.strip() for a in cfgsetup.get('Modelling',\n 'tE').split(',')]),\\\n 'rho' : np.array([a.strip() for a in cfgsetup.get('Modelling',\n 'rho').split(',')]),\\\n 'gamma' : np.array([a.strip() for a in cfgsetup.get('Modelling',\n 'gamma').split(',')]),\\\n 'piEE' : np.array([a.strip() for a in cfgsetup.get('Modelling',\n 'piEE').split(',')]),\\\n 'piEN' : np.array([a.strip() for a in cfgsetup.get('Modelling',\n 'piEN').split(',')]),\\\n 's' : np.array([a.strip() for a in cfgsetup.get('Modelling',\n 's').split(',')]),\\\n 'q' : np.array([a.strip() for a in cfgsetup.get('Modelling',\n 'q').split(',')]),\\\n 'alpha' : np.array([a.strip() for a in cfgsetup.get('Modelling',\n 'alpha').split(',')]),\\\n 'dadt': np.array([a.strip() for a in cfgsetup.get('Modelling', 'dadt').split(',')]),\\\n 'dsdt': np.array([a.strip() for a in cfgsetup.get('Modelling', 'dsdt').split(',')])\\\n }\n \n constp = dict()\n fitp = dict()\n result = np.array([])\n if params['t0'][0]!=\"fit\":\n if params['t0'][0]==\"gri\":\n constp.update({'t0': node['t0']})\n else:\n constp.update({'t0': params['t0'][3].astype(np.float64)})\n else:\n fitp.update({'t0': params['t0'][3].astype(np.float64)})\n result = np.append(result, fitp['t0'])\n if params['u0'][0]!=\"fit\":\n if params['u0'][0]==\"gri\":\n constp.update({'u0': node['u0']})\n else:\n constp.update({'u0': params['u0'][3].astype(np.float64)})\n else:\n fitp.update({'u0': params['u0'][3].astype(np.float64)})\n result = np.append(result, fitp['u0'])\n if params['tE'][0]!=\"fit\":\n if params['tE'][0]==\"gri\":\n constp.update({'tE': node['tE']})\n else:\n constp.update({'tE': params['tE'][3].astype(np.float64)})\n else:\n fitp.update({'tE': params['tE'][3].astype(np.float64)})\n result = np.append(result, fitp['tE'])\n if params['rho'][0]!=\"fit\":\n if params['rho'][0]==\"gri\":\n constp.update({'rho': node['rho']})\n else:\n constp.update({'rho': params['rho'][3].astype(np.float64)})\n else:\n fitp.update({'rho': params['rho'][3].astype(np.float64)})\n result = np.append(result, fitp['rho'])\n if params['gamma'][0]!=\"fit\":\n if params['gamma'][0]==\"gri\":\n constp.update({'gamma': node['gamma']})\n else:\n constp.update({'gamma': params['gamma'][3].astype(np.float64)})\n else:\n fitp.update({'gamma': params['gamma'][3].astype(np.float64)})\n result = np.append(result, fitp['gamma'])\n if params['piEE'][0]!=\"fit\":\n if params['piEE'][0]==\"gri\":\n constp.update({'piEE': node['piEE']})\n else:\n constp.update({'piEE': params['piEE'][3].astype(np.float64)})\n else:\n fitp.update({'piEE': params['piEE'][3].astype(np.float64)})\n result = np.append(result, fitp['piEE'])\n if params['piEN'][0]!=\"fit\":\n if params['piEN'][0]==\"gri\":\n constp.update({'piEN': node['piEN']})\n else:\n constp.update({'piEN': params['piEN'][3].astype(np.float64)})\n else:\n fitp.update({'piEN': params['piEN'][3].astype(np.float64)})\n result = np.append(result, fitp['piEN'])\n if params['s'][0]!=\"fit\":\n if params['s'][0]==\"gri\":\n constp.update({'s': node['s']})\n else:\n constp.update({'s': params['s'][3].astype(np.float64)})\n else:\n fitp.update({'s': params['s'][3].astype(np.float64)})\n result = np.append(result, fitp['s'])\n if params['q'][0]!=\"fit\":\n if params['q'][0]==\"gri\":\n constp.update({'q': node['q']})\n else:\n constp.update({'q': params['q'][3].astype(np.float64)})\n else:\n fitp.update({'q': params['q'][3].astype(np.float64)})\n result = np.append(result, fitp['q'])\n if params['alpha'][0]!=\"fit\":\n if params['alpha'][0]==\"gri\":\n constp.update({'alpha': node['alpha']})\n else:\n constp.update({'alpha': params['alpha'][3].astype(np.float64)})\n else:\n fitp.update({'alpha': params['alpha'][3].astype(np.float64)})\n result = np.append(result, fitp['alpha'])\n if params['dadt'][0]!=\"fit\":\n if params['dadt'][0]==\"gri\":\n constp.update({'dadt': node['dadt']})\n else:\n constp.update({'dadt': params['dadt'][3].astype(np.float64)})\n else:\n fitp.update({'dadt': params['dadt'][3].astype(np.float64)})\n result = np.append(result, fitp['dadt'])\n if params['dsdt'][0]!=\"fit\":\n if params['dsdt'][0]==\"gri\":\n constp.update({'dsdt': node['dsdt']})\n else:\n constp.update({'dsdt': params['dsdt'][3].astype(np.float64)})\n else:\n fitp.update({'dsdt': params['dsdt'][3].astype(np.float64)})\n result = np.append(result, fitp['dsdt'])\n\n # Add flux in fitp\n [fitp.update({f\"fs_{a}\": 1.0}) for a in observatories]\n [fitp.update({f\"fb_{a}\": 1.0}) for a in observatories]\n\n constp.update({'tb': cfgsetup.getfloat('Modelling', 'tb')})\n constp.update({'tb': cfgsetup.getfloat('Modelling', 'tp')})\n\n fitp = pd.Series(fitp)\n constp = pd.Series(constp)\n\n # Load models of magnification\n # ----------------------------\n model_names = np.unique(model2load)\n models_address = dict()\n for i in range(len(model_names)):\n name = 'muLAn.models.{:s}'.format(model_names[i])\n models_address.update({model_names[i]: importlib.import_module(name)})\n\n # Save objects before optimization\n # --------------------------------\n # This is done because some optimization packages works faster with\n # global variables.\n\n if cfgsetup.getboolean('Modelling', 'Fit'):\n\n args = dict()\n args.update({'data': pd.DataFrame().from_dict(time_serie)})\n args.update({'fit_params': fitp})\n args.update({'const_params': constp})\n args.update({'instruments': constp})\n args.update({'const_params': constp})\n #args.update({'model_library': pd.DataFrame().from_dict(models_address)})\n\n # Save file in HDF5 format\n fname = f'args.h5'\n for key, val in args.items():\n val.to_hdf(fname, key=key)\n\n optimization_names = np.array([cfgsetup.get('Modelling', 'Method')])\n optimization_address = list()\n for i in range(len(optimization_names)):\n name = 'muLAn.models.{:s}'.format(optimization_names[i])\n optimization_address.append(importlib.import_module(name))\n\n\n # ------------------------------------------------------------------\n # Explore the parameters space\n # ------------------------------------------------------------------\n if cfgsetup.getboolean('Modelling', 'Fit'):\n\n text = \"Start minimization...\"\n communicate(cfgsetup, 1, text, opts=[printoption.level0], prefix=True, newline=True, tab=False)\n\n text = optimization_address[0].help()\n communicate(cfgsetup, 3, text, opts=False, prefix=False, newline=True, tab=True)\n\n fname = f'args.h5'\n# optimization_address[0].search(cfgsetup=cfgsetup, models=models_address,\n# model_param=model_params, time_serie=time_serie, \\\n# model2load=model2load, interpol_method=interpol_method)\n try:\n optimization_address[0].search(cfgsetup=cfgsetup, models=models_address,\n model_param=model_params, time_serie=time_serie, \\\n model2load=model2load, interpol_method=interpol_method)\n if os.path.exists(fname): os.remove(fname)\n except ValueError as err :\n if os.path.exists(fname): os.remove(fname)\n txt = \"MCMC failed.\"\n print(err, txt)\n\n fname = f'args.h5'\n if os.path.exists(fname): os.remove(fname)\n\n # ----------------------------------------------------------------------\n # Without Data\n # ----------------------------------------------------------------------\n if cfgsetup.getboolean('Plotting', 'Data') == False:\n\n text = \"\\n Preparation of a simulation without data \"\n communicate(cfgsetup, 1, text, opts=[printoption.reverse])\n\n # Data file names\n data2find = np.array(cfgobs.options('ObservatoriesDetails'))\n\n # Cross-match with data to use\n data2use = np.array(cfgsetup.options('Observatories'))\n data2use = np.array([data2find[i] for i in range(len(data2find)) if np.any(data2use == data2find[i])])\n\n observatories = data2use\n\n # Reference for plotting\n filename = cfgsetup.get('FullPaths', 'Event') + 'setup.ini'\n file = open(filename, 'r')\n for line in file:\n a = line.split(':')[0]\n if a != '':\n a = a.strip().lower()\n if len(np.where(data2use == a)[0]) > 0:\n cfgsetup.set('Observatories', 'Reference', a)\n break\n\n obs_properties = dict({'name': [], 'colour': [], 'filter': [], 'loc': [], 'exclude': [], 'key': []})\n text = 'Simulated light curve from:\\n'\n for i in range(len(observatories)):\n table = [a.strip() for a in cfgobs.get('ObservatoriesDetails', observatories[i]).split(',')]\n\n obs_properties['name'].append(table[0])\n obs_properties['colour'].append(table[1])\n obs_properties['filter'].append(table[2])\n obs_properties['loc'].append(table[3])\n obs_properties['key'].append(observatories[i])\n\n if (len(table[4:]) > 0):\n if (table[4] != ''):\n obs_properties['exclude'].append(table[4:])\n else:\n obs_properties['exclude'].append(None)\n else:\n obs_properties['exclude'].append(None)\n\n if i!=len(observatories)-1:\n text = text + ' ' + table[0] + '\\n'\n if i==len(observatories)-1:\n text = text + ' ' + table[0]\n\n communicate(cfgsetup, 1, text)\n\n # Parameters of modelling\n model_params = dict()\n interpol_method = dict()\n for i in range(len(obs_properties['loc'])):\n name = 'Models_' + obs_properties['loc'][i]\n table = np.array([a.split('/')[1].strip() for a in unpack_options(cfgsetup, 'Modelling', name)])\n model_params.update({name: table})\n\n table = np.array([a.split('/')[0].strip() for a in unpack_options(cfgsetup, 'Modelling', name)])\n name2 = 'DateRanges_' + obs_properties['loc'][i]\n model_params.update({name2: table})\n\n for j in range(len(unpack_options(cfgsetup, 'Modelling', name))):\n a = unpack_options(cfgsetup, 'Modelling', name)[j]\n a = a.split('/')\n if len(a) == 3:\n name3 = obs_properties['loc'][i] + '#' + a[1] + '#' + a[0]\n t1 = float(a[0].split('-')[0].strip())\n t2 = float(a[0].split('-')[1].strip())\n # print(name3, t1, t2)\n interpol_method.update({name3: [np.linspace(t1, t2, int(a[2])), np.full(int(a[2]), 0, dtype='f8'), np.full(int(a[2]), 0, dtype='f8'), np.full(int(a[2]), 0, dtype='f8')]})\n # print(interpol_method)\n\n # Ephemeris\n path = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get('RelativePaths', 'Data')\n\n if len(obs_properties['loc']) > 1:\n name1 = obs_properties['loc'][np.where(np.array(\n [obs == cfgsetup.get('Observatories', 'Reference').lower()\n for obs in observatories]) == True)[0][0]]\n name1 = glob.glob(path + name1 + '.*')[0]\n else:\n name1 = glob.glob(path + obs_properties['loc'][0] + '.*')[0]\n\n # Load data\n time_serie = dict({})\n time_serie_temp = dict({})\n model2load = np.array([])\n for i in range(len(observatories)):\n if i == 0:\n time_serie.update({'id': []})\n time_serie.update({'dates': []})\n time_serie.update({'magnitude': []})\n time_serie.update({'err_magn': []})\n time_serie.update({'seeing': []})\n time_serie.update({'background': []})\n time_serie.update({'DsN': []})\n time_serie.update({'DsE': []})\n time_serie.update({'model': []})\n time_serie.update({'interpol': []})\n time_serie.update({'obs': np.array([observatories[i]], dtype='S100')})\n time_serie.update({'loc': np.array([obs_properties['loc'][i]], dtype='S100')})\n else:\n time_serie_temp.update({'id': []})\n time_serie_temp.update({'dates': []})\n time_serie_temp.update({'magnitude': []})\n time_serie_temp.update({'err_magn': []})\n time_serie_temp.update({'seeing': []})\n time_serie_temp.update({'background': []})\n time_serie_temp.update({'DsN': []})\n time_serie_temp.update({'DsE': []})\n time_serie_temp.update({'model': []})\n time_serie_temp.update({'interpol': []})\n time_serie_temp.update({'obs': np.array([observatories[i]], dtype='S100')})\n time_serie_temp.update({'loc': np.array([obs_properties['loc'][i]], dtype='S100')})\n\n time_serie = {key: np.append(np.array(time_serie[key]),\n np.array(time_serie_temp[key])) for key in time_serie}\n\n # Models\n name = 'Models_' + obs_properties['loc'][i]\n models_temp = model_params[name]\n name = 'DateRanges_' + obs_properties['loc'][i]\n dates_temp = model_params[name]\n\n key = np.array([key for key in interpol_method])\n for j in range(len(models_temp)):\n model2load = np.append(model2load, models_temp[j])\n time_serie.update({'model': np.append(time_serie['model'], models_temp[j])})\n\n # Decide if method interpolation is used or not.\n key_list = np.array([key for key in interpol_method])\n if len(key_list) > 0:\n\n # text = \"\\nInterpolation of the amplification asked.\"\n # communicate(cfgsetup, 1, text, opts=[printoption.bright])\n\n for i in range(len(key_list)):\n loc = key_list[i].split('#')[0]\n\n tmin = float(key_list[i].split('#')[2].split('-')[0])\n tmax = float(key_list[i].split('#')[2].split('-')[1])\n\n # Ephemeris\n path = cfgsetup.get('FullPaths', 'Event') + cfgsetup.get('RelativePaths', 'Data')\n\n if len(obs_properties['loc']) > 1:\n name1 = obs_properties['loc'][np.where(np.array(\n [obs == cfgsetup.get('Observatories', 'Reference').lower()\n for obs in observatories]) == True)[0][0]]\n name1 = glob.glob(path + name1 + '.*')[0]\n else:\n name1 = glob.glob(path + obs_properties['loc'][0] + '.*')[0]\n\n c_icrs = SkyCoord(ra=cfgsetup.get('EventDescription', 'RA'), \\\n dec=cfgsetup.get('EventDescription', 'DEC'), frame='icrs')\n # print(c_icrs.transform_to('barycentrictrueecliptic'))\n l = c_icrs.transform_to('barycentrictrueecliptic').lon.degree\n b = c_icrs.transform_to('barycentrictrueecliptic').lat.degree\n\n name2 = glob.glob(path + loc + '.*')[0]\n sTe, sEe, sNe, DsTe, DsEe, DsNe, sTs, sEs, sNs, DsTs, DsEs, DsNs = \\\n ephemeris.Ds(name1, name2, l, b, cfgsetup.getfloat('Modelling', 'tp'), \\\n cfgsetup)\n\n if name1 != name2:\n DsN = DsNs\n DsE = DsEs\n else:\n DsN = DsNe\n DsE = DsEe\n\n interpol_method[key_list[i]][1] = DsN(interpol_method[key_list[i]][0])\n interpol_method[key_list[i]][2] = DsE(interpol_method[key_list[i]][0])\n\n # ----------------------------------------------------------------------\n # Load all the models that will be used\n # ----------------------------------------------------------------------\n def prepar_importation(model2load):\n modules = model2load\n modules_mini = np.array([cfgsetup.get('Modelling', 'Method')])\n path = cfgsetup.get('FullPaths', 'Code') + 'packages/'\n modulesloading_file = open(path + 'modulesloading.py', 'w')\n\n text = \"# -*-coding:Utf-8 -*\\n\"\n text = text + \"import sys\\n\"\n text = text + \"sys.path.insert(0, '\" + cfgsetup.get('FullPaths', 'Code') \\\n + \"models')\\n\"\n\n for i in range(len(modules)):\n text = text + \"import \" + modules[i] + \" as \" + modules[i]\n text = text + \"\\n\"\n\n for i in range(len(modules_mini)):\n text = text + \"import \" + modules_mini[i] + \" as \" + modules_mini[i]\n text = text + \"\\n\"\n\n text = text + \"def main():\\n\"\n text = text + \"\\tmodels_files = [\" + modules[0] + \"]\\n\"\n\n if len(modules) > 1:\n for i in range(len(modules) - 1):\n text = text + \"\\tmodels_files.append(\" + modules[i + 1] + \")\\n\"\n\n text = text + \"\\tminim_files = [\" + modules_mini[0] + \"]\\n\"\n\n if len(modules_mini) > 1:\n for i in range(len(modules_mini) - 1):\n text = text + \"\\tminim_files.append(\" + modules_mini[i + 1] + \")\\n\"\n\n text = text + \"\\treturn models_files, minim_files\\n\"\n\n modulesloading_file.write(text)\n modulesloading_file.close()\n\n\n model2load = np.unique(model2load)\n prepar_importation(model2load)\n sys.path.insert(0, cfgsetup.get('FullPaths', 'Code') + 'packages/')\n import modulesloading as load_modules\n\n models_modules, minim_algo = load_modules.main()\n\n models_modules = {model2load[i]: models_modules[i] for i in range(len(model2load))}\n\n # Sort the MCMC samples and create a summary file for analysis\n # ============================================================\n\n if 'sortno' in options:\n text = \"Post-processing MCMC output...\"\n communicate(cfgsetup, 1, text, opts=[printoption.level0], prefix=True, newline=True, tab=False)\n\n if cfgsetup.getboolean('Optimization', 'UseBinaryFiles'):\n if options['sortno']:\n summary = iotools.FitResults(cfgsetup, format='h5')\n else:\n summary = iotools.FitResults(cfgsetup, format='ascii')\n summary.remove_duplicates(inplace=True)\n summary.save(format='h5')\n else:\n if options['sortno']:\n summary = iotools.FitResults(cfgsetup, format='h5')\n else:\n summary = iotools.FitResults(cfgsetup, format='ascii')\n summary.remove_duplicates(inplace=True)\n summary.save(format='h5')\n n = np.min([len(summary.samples), 1000])\n summary.save(format='ascii', N=n)\n\n # Display a preview in the terminal\n cols = ['fullid', 'dchi2', 'tE', 'q', 's', 'rho', 'tS']\n colnames = [\n 'Model ID',\n '\\u0394\\u03C7\\u00b2', \n 'tE', \n 'q', \n 'sep',\n 'rho',\n 'tS',\n ]\n format={'dchi2': '{:.2f}'.format,\n 'tE': \" {:.1f}\".format,\n 'q': \" {:.2e}\".format,\n 's': \" {:.2e}\".format,\n 'rho': \" {:.2e}\".format,\n 'tS': \" {:.3f}\".format,\n }\n\n txt = \"Best models preview\"\n communicate(cfgsetup, 3, txt, opts=[printoption.level1], prefix=False, newline=True, tab=False)\n txt = summary.samples.head(5).to_string(columns=cols, header=colnames, index=False, formatters=format, max_rows=15, line_width=79)\n txt = ' {:s}'.format(txt.replace('\\n', '\\n '))\n communicate(cfgsetup, 3, txt, opts=False, prefix=False, newline=False, tab=False)\n\n txt = \"Worst models preview\"\n communicate(cfgsetup, 3, txt, opts=[printoption.level1], prefix=False, newline=True, tab=False)\n txt = summary.samples.tail(5).to_string(columns=cols, header=colnames, index=False, formatters=format, max_rows=15, line_width=79)\n txt = ' {:s}'.format(txt.replace('\\n', '\\n '))\n communicate(cfgsetup, 3, txt, opts=False, prefix=False, newline=False, tab=False)\n\n # Compute specified model information\n # ===================================\n # Store data in a new class\n data = Data(time_serie)\n\n # Select two best models\n x = summary.samples[summary.samples['fullid']<4]\n fname = \"{:s}/{:s}.h5\".format(\n cfgsetup.get('RelativePaths', 'Archives'),\n cfgsetup.get('Controls', 'Archive'))\n lenses = LensModel(archive=fname)\n lenses.compute(data=data, models=x, magnification=True, lib=models_modules, parser=cfgsetup)\n\n data_to_plot_models = pd.DataFrame()\n data_to_plot_models['dates'] = np.linspace(5740, 5820, 5000)\n name = 'Models_' + obs_properties['loc'][0]\n models_temp = model_params[name]\n name = 'DateRanges_' + obs_properties['loc'][0]\n dates_temp = model_params[name]\n\n data_to_plot_models['model'] = 'PSPL'\n\n for j in range(len(models_temp)):\n model2load = np.append(model2load, models_temp[j])\n tmin = float((dates_temp[j]).split('-')[0].strip())\n tmax = float((dates_temp[j]).split('-')[1].strip())\n\n mask = (data_to_plot_models['dates'] > tmin) & (data_to_plot_models['dates'] <= tmax)\n data_to_plot_models.loc[mask, 'model'] = models_temp[j]\n\n # Calculations from ephemeris for parallax\n DsN, DsE = ephemeris.dsndse(l, b, cfgsetup, obs_properties, observatories)\n\n if (DsN == None) | (DsE == None):\n data_to_plot_models['DsN'] = DsN \n data_to_plot_models['DsE'] = DsE\n else:\n data_to_plot_models['DsN'] = DsN(data_to_plot_models['dates'].values)\n data_to_plot_models['DsE'] = DsE(data_to_plot_models['dates'].values)\n\n lenses.magnification_model(epochs=data_to_plot_models, models=x, lib=models_modules)\n\n sys.exit()\n # Next step is to select only mmodels required for this computation. And then add caustic, residuals etc.\n\n # ----------------------------------------------------------------------\n # Plots\n # ----------------------------------------------------------------------\n if cfgsetup.get('Plotting', 'flag'):\n\n text = \"Create the plots...\"\n communicate(cfgsetup, 1, text, opts=[printoption.level0], prefix=True, newline=True, tab=False)\n\n # List of plots\n plots2load_brut = unpack_options(cfgsetup, 'Plotting', 'Type')\n\n # Load plot types \n # ---------------\n plots2load = np.unique(plots2load_brut)\n plottypes_list = dict()\n if(len(plots2load)) > 0:\n for i in range(len(plots2load)):\n text = 'muLAn.plottypes.{:s}'.format(plots2load[i])\n importlib.import_module(text)\n plottypes_list.update({plots2load[i]: getattr(mulanplots, plots2load[i])})\n\n # Recursively run the plots routines\n for i in range(len(plots2load_brut)):\n\n text = plots2load_brut[i] + \" - \" + plottypes_list[plots2load_brut[i]].help()\n communicate(cfgsetup, 1, text, opts=False, prefix=False, newline=True, tab=True)\n\n options = unpack_options(cfgsetup, 'Plotting', 'Options')[i]\n plottypes_list[plots2load_brut[i]].plot(\n cfgsetup=cfgsetup, models=models_modules,\n model_param=model_params, time_serie=time_serie,\n obs_properties=obs_properties, options=options,\n interpol_method=interpol_method)\n\nif (__name__ == \"__main__\"):\n pass\n","repo_name":"muLAn-project/muLAn","sub_path":"muLAn/packages/sequential.py","file_name":"sequential.py","file_ext":"py","file_size_in_byte":58508,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"34"} +{"seq_id":"40732346593","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport os\nimport time\nimport unittest\nfrom shutil import rmtree\nfrom tempfile import mkdtemp\n\nimport mozunit\n\nfrom mozbuild import artifact_cache\nfrom mozbuild.artifact_cache import ArtifactCache\n\nCONTENTS = {\n \"http://server/foo\": b\"foo\",\n \"http://server/bar\": b\"bar\" * 400,\n \"http://server/qux\": b\"qux\" * 400,\n \"http://server/fuga\": b\"fuga\" * 300,\n \"http://server/hoge\": b\"hoge\" * 300,\n \"http://server/larger\": b\"larger\" * 3000,\n}\n\n\nclass FakeResponse(object):\n def __init__(self, content):\n self._content = content\n\n @property\n def headers(self):\n return {\"Content-length\": str(len(self._content))}\n\n def iter_content(self, chunk_size):\n content = memoryview(self._content)\n while content:\n yield content[:chunk_size]\n content = content[chunk_size:]\n\n def raise_for_status(self):\n pass\n\n def close(self):\n pass\n\n\nclass FakeSession(object):\n def get(self, url, stream=True):\n assert stream is True\n return FakeResponse(CONTENTS[url])\n\n\nclass TestArtifactCache(unittest.TestCase):\n def setUp(self):\n self.min_cached_artifacts = artifact_cache.MIN_CACHED_ARTIFACTS\n self.max_cached_artifacts_size = artifact_cache.MAX_CACHED_ARTIFACTS_SIZE\n artifact_cache.MIN_CACHED_ARTIFACTS = 2\n artifact_cache.MAX_CACHED_ARTIFACTS_SIZE = 4096\n\n self._real_utime = os.utime\n os.utime = self.utime\n self.timestamp = time.time() - 86400\n\n self.tmpdir = mkdtemp()\n\n def tearDown(self):\n rmtree(self.tmpdir)\n artifact_cache.MIN_CACHED_ARTIFACTS = self.min_cached_artifacts\n artifact_cache.MAX_CACHED_ARTIFACTS_SIZE = self.max_cached_artifacts_size\n os.utime = self._real_utime\n\n def utime(self, path, times):\n if times is None:\n # Ensure all downloaded files have a different timestamp\n times = (self.timestamp, self.timestamp)\n self.timestamp += 2\n self._real_utime(path, times)\n\n def listtmpdir(self):\n return [p for p in os.listdir(self.tmpdir) if p != \".metadata_never_index\"]\n\n def test_artifact_cache_persistence(self):\n cache = ArtifactCache(self.tmpdir)\n cache._download_manager.session = FakeSession()\n\n path = cache.fetch(\"http://server/foo\")\n expected = [os.path.basename(path)]\n self.assertEqual(self.listtmpdir(), expected)\n\n path = cache.fetch(\"http://server/bar\")\n expected.append(os.path.basename(path))\n self.assertEqual(sorted(self.listtmpdir()), sorted(expected))\n\n # We're downloading more than the cache allows us, but since it's all\n # in the same session, no purge happens.\n path = cache.fetch(\"http://server/qux\")\n expected.append(os.path.basename(path))\n self.assertEqual(sorted(self.listtmpdir()), sorted(expected))\n\n path = cache.fetch(\"http://server/fuga\")\n expected.append(os.path.basename(path))\n self.assertEqual(sorted(self.listtmpdir()), sorted(expected))\n\n cache = ArtifactCache(self.tmpdir)\n cache._download_manager.session = FakeSession()\n\n # Downloading a new file in a new session purges the oldest files in\n # the cache.\n path = cache.fetch(\"http://server/hoge\")\n expected.append(os.path.basename(path))\n expected = expected[2:]\n self.assertEqual(sorted(self.listtmpdir()), sorted(expected))\n\n # Downloading a file already in the cache leaves the cache untouched\n cache = ArtifactCache(self.tmpdir)\n cache._download_manager.session = FakeSession()\n\n path = cache.fetch(\"http://server/qux\")\n self.assertEqual(sorted(self.listtmpdir()), sorted(expected))\n\n # bar was purged earlier, re-downloading it should purge the oldest\n # downloaded file, which at this point would be qux, but we also\n # re-downloaded it in the mean time, so the next one (fuga) should be\n # the purged one.\n cache = ArtifactCache(self.tmpdir)\n cache._download_manager.session = FakeSession()\n\n path = cache.fetch(\"http://server/bar\")\n expected.append(os.path.basename(path))\n expected = [p for p in expected if \"fuga\" not in p]\n self.assertEqual(sorted(self.listtmpdir()), sorted(expected))\n\n # Downloading one file larger than the cache size should still leave\n # MIN_CACHED_ARTIFACTS files.\n cache = ArtifactCache(self.tmpdir)\n cache._download_manager.session = FakeSession()\n\n path = cache.fetch(\"http://server/larger\")\n expected.append(os.path.basename(path))\n expected = expected[-2:]\n self.assertEqual(sorted(self.listtmpdir()), sorted(expected))\n\n\nif __name__ == \"__main__\":\n mozunit.main()\n","repo_name":"WaterfoxCo/Waterfox","sub_path":"python/mozbuild/mozbuild/test/test_artifact_cache.py","file_name":"test_artifact_cache.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","stars":3159,"dataset":"github-code","pt":"34"} +{"seq_id":"26505695086","text":"from tensorflow import keras\nfrom recommendedsystem.netflix_prize_dataset import Dataset\nimport os\nimport tensorflow as tf\nimport logging\nimport math\n\n# tf.enable_eager_execution()\n\n\ndef create_netflixprize_model(movie_count=17771, consumer_count=2649430):\n input_movie = keras.layers.Input(name=\"movie\", shape=(1, ))\n input_consumer = keras.layers.Input(name=\"consumer\", shape=(1, ))\n x_movie = keras.layers.Embedding(\n movie_count, 60, input_length=1)(input_movie)\n x_consumer = keras.layers.Embedding(\n consumer_count, 20, input_length=1)(input_consumer)\n x = keras.layers.Concatenate()([x_movie, x_consumer])\n x = keras.layers.Flatten()(x)\n\n def add_layer(x, units=64):\n x = keras.layers.BatchNormalization()(x)\n x = keras.layers.Activation(activation=\"relu\")(x)\n x = keras.layers.Dense(\n units,\n kernel_initializer=keras.initializers.RandomUniform(),\n bias_initializer=keras.initializers.Zeros(),\n kernel_regularizer=keras.regularizers.l2(0.01),\n bias_regularizer=keras.regularizers.l2(0.01))(x)\n return x\n\n x = add_layer(x, 64)\n x = add_layer(x, 64)\n x = add_layer(x, 64)\n x = add_layer(x, 1)\n return keras.Model(inputs=[input_movie, input_consumer], outputs=x)\n\n\ndef load_model(model, checkpoint):\n latest_checkpoint = None\n if os.path.exists(checkpoint):\n latest_checkpoint = checkpoint\n else:\n latest_checkpoint = tf.train.latest_checkpoint(\n os.path.dirname(checkpoint))\n if latest_checkpoint:\n logging.info(\"load model from {}\".format(latest_checkpoint))\n model.load_weights(latest_checkpoint)\n\n\ndef train_model(model, dataset, validation, epochs, checkpoint, logdir):\n checkpoint_callback = keras.callbacks.ModelCheckpoint(\n checkpoint,\n save_weights_only=True,\n verbose=1,\n )\n tensorboard_callback = keras.callbacks.TensorBoard(logdir)\n model.fit(\n dataset,\n epochs=epochs,\n validation_data=validation,\n steps_per_epoch=100,\n validation_steps=20,\n callbacks=[checkpoint_callback, tensorboard_callback],\n )\n # model.save_weights(MODEL_PATH)\n\n\ndef evaluate_model(model, dataset):\n return model.evaluate(dataset, steps=10000)\n\n\ndef main():\n DATASET_DIR = os.path.expanduser(\"~/datasets/netflix-prize/tfrecord\")\n # CHECKPOINT_PATH = \"./checkpoint/model-{epoch:08d}.ckpt\"\n CHECKPOINT_PATH = os.path.expanduser(\"./checkpoint/model.h5\")\n LOG_DIR = os.path.expanduser(\"./logs\")\n EPOCHS = 40\n BATCH_SIZE = 20000\n BUFFER_SIZE = 40000\n if not os.path.isdir(os.path.dirname(CHECKPOINT_PATH)):\n os.makedirs(os.path.dirname(CHECKPOINT_PATH))\n\n model = create_netflixprize_model()\n\n def loss_fn(y_true, y_pred):\n # return keras.backend.sqrt(\n # keras.metrics.mean_squared_error(y_true, y_pred * 5))\n return keras.metrics.mean_squared_error(y_true, y_pred * 5)\n\n model.compile(\n loss=loss_fn,\n # loss=\"mean_squared_error\",\n optimizer='adadelta',\n # optimizer=tf.train.AdamOptimizer(),\n )\n # model.summary()\n load_model(model, CHECKPOINT_PATH)\n\n dataset = Dataset(directory=DATASET_DIR)\n dataset_train = dataset.tfdataset(\"trainingset\")\n dataset_evaluate = dataset.tfdataset(\"qualifyingset\")\n dataset_validate = dataset.tfdataset(\"probeset\")\n dataset_train = dataset_train.shuffle(buffer_size=BUFFER_SIZE)\n dataset_evaluate = dataset_evaluate.shuffle(buffer_size=BUFFER_SIZE)\n dataset_validate = dataset_validate.shuffle(buffer_size=BUFFER_SIZE)\n dataset_train = dataset_train.repeat(3)\n\n def convert(x):\n return {\n \"movie\": x[\"movieindex\"],\n \"consumer\": x[\"consumerindex\"]\n }, x[\"rate\"]\n\n dataset_train = dataset_train.map(convert)\n dataset_evaluate = dataset_evaluate.map(convert)\n dataset_validate = dataset_validate.map(convert)\n dataset_train = dataset_train.batch(BATCH_SIZE)\n dataset_evaluate = dataset_evaluate.batch(20)\n dataset_validate = dataset_validate.batch(60)\n train_model(model, dataset_train, dataset_validate, EPOCHS,\n CHECKPOINT_PATH, LOG_DIR)\n loss = evaluate_model(model, dataset_evaluate)\n print(\"rmse: {:5.2f}\".format(math.sqrt(loss)))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"miacro/recommended-system","sub_path":"recommendedsystem/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"70000670179","text":"import pygame\n\nfrom pygame.locals import *\nfrom source.state.state_game import StateGame\nfrom source.manager import Manager\nfrom source.MyScreen import MyScreen # MyScreen class\nfrom source.state.state_char_selection_screen import StateCharSelectionScreen\n\nclass StateSplashScreen(StateGame, Manager):\n def __init__(self, game):\n StateGame.__init__(self, game)\n self.waiting = None\n\n def init(self):\n\n # splash screen\n self.game.gamestate = \"splash screen\"\n self.game.active_screen = MyScreen('splash_screen_done.png')\n self.game.screen.blit(self.game.active_screen.image, self.game.active_screen.rect)\n pygame.display.update()\n\n def listen_events(self):\n # get input\n for event in pygame.event.get():\n if event.type == QUIT or \\\n (event.type == KEYDOWN and event.key == K_ESCAPE):\n return False\n\n def process_logic(self):\n keystate = pygame.key.get_pressed()\n if keystate[K_SPACE]:\n self.waiting = False\n self.game.step = self.game.step + 1\n if self.game.step > 4:\n self.game.step = 0\n self.game.animstep = self.game.animstep + 1\n if self.game.animstep > 5:\n self.game.animstep = 0\n\n def render_update(self):\n # update all the sprites\n self.game.all.update()\n\n # draw the scene\n dirty = self.game.all.draw(self.game.screen)\n pygame.display.update(dirty)\n\n # cap the framerate\n self.game.clock.tick(40)\n\n def show_char_selection_screen(self):\n self.init()\n self.waiting = True\n\n while self.waiting:\n if self.listen_events() is False: return\n self.process_logic()\n self.render_update()\n\n for myScreen in self.game.my_screens:\n myScreen.kill()\n\n self.game.state = StateCharSelectionScreen(self.game)","repo_name":"is2-team-b/MedievalBrawler","sub_path":"source/state/state_splash_screen.py","file_name":"state_splash_screen.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"34"} +{"seq_id":"16089530973","text":"from odoo import api, fields, models\n\n\nclass SaleOrderLine(models.Model):\n _inherit = \"sale.order.line\"\n\n tag_ids = fields.Many2many(comodel_name=\"sale.order.line.tag\")\n\n line_number = fields.Integer(compute=\"_compute_line_number\", store=True)\n\n @api.depends(\"order_id.order_line\", \"sequence\")\n def _compute_line_number(self):\n order_ids = self.mapped(\"order_id\")\n for order in order_ids:\n n = 1\n for line in order.order_line.sorted(lambda l: l.sequence):\n line.line_number = n\n n += 1\n","repo_name":"Volodiay616/bootcamp","sub_path":"sale_order_line_number/models/sale_order_line.py","file_name":"sale_order_line.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"43693598121","text":"from discord.ext import commands\nfrom time import time\nfrom functions import red\n\nwhitelist = []\n\nclass Join(commands.Cog):\n def __init__(self, client):\n self.client = client\n\n @commands.command()\n async def liberar(self, arg):\n whitelist.append(arg)\n\n @commands.Cog.listener()\n async def on_member_join(self, member):\n # Long Beach\n if member.guild.id == 696664282615513188:\n conta = self.client.get_user(member.id)\n criacao = conta.created_at\n if str(member) in whitelist:\n role = member.guild.get_role(699108448008405002)\n await member.add_roles(role)\n channel = member.guild.get_channel(880867172262498365)\n await channel.send(f'> {member.mention} entrou.')\n return\n elif time() - criacao.timestamp() < 518400:\n await member.kick()\n try:\n await member.send(\n f'❌ **{member.display_name}**, nosso sistema de segurança detectou que sua conta tem menos de `UMA SEMANA` de vida. Para realizar sua verificação que não é um robô, entre em contato com **Chali#3955** pelo Discord.'\n )\n except Exception as e:\n print(red(f'{e} {member}'))\n else:\n role = member.guild.get_role(699108448008405002)\n await member.add_roles(role)\n channel = member.guild.get_channel(880867172262498365)\n await channel.send(f'> {member.mention} entrou.')\n # LBPD\n if member.guild.id == 865643871933038602:\n role = member.guild.get_role(872270783446147102)\n await member.add_roles(role)\n channel = member.guild.get_channel(865643872151797774)\n await channel.send(f'> {member.mention} entrou.')\n # FTO\n if member.guild.id == 866729056203702284:\n role = member.guild.get_role(871412869420429323)\n await member.add_roles(role)\n channel = member.guild.get_channel(871405947753492521)\n await channel.send(f'> {member.mention} entrou.')\n # SID\n if member.guild.id == 871441311788580905:\n role = member.guild.get_role(871441311788580907)\n await member.add_roles(role)\n channel = member.guild.get_channel(871441314980442192)\n await channel.send(f'> {member.mention} entrou.')\n # STD\n if member.guild.id == 871447558248083456:\n role = member.guild.get_role(871447558248083458)\n await member.add_roles(role)\n channel = member.guild.get_channel(871447558248083464)\n await channel.send(f'> {member.mention} entrou.')\n # ASD\n if member.guild.id == 872100014883733505:\n role = member.guild.get_role(872100014883733507)\n await member.add_roles(role)\n channel = member.guild.get_channel(872100015567429632)\n await channel.send(f'> {member.mention} entrou.')\n\n\ndef setup(client):\n client.add_cog(Join(client))\n","repo_name":"glmchalita/polacobot","sub_path":"events/on_member_join.py","file_name":"on_member_join.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"23791216085","text":"from pygame.locals import *\n\nconf = None\n\n\nclass Keys:\n def __init__(self):\n self.up = self.down = self.left = self.right = None\n self.button = (None, None)\n\n\nclass PlayerConfig:\n\n instances = []\n\n def __init__(self, player_id):\n self.keys = Keys()\n if player_id == -1:\n # dummy config\n return\n PlayerConfig.instances.append(self)\n if player_id == 0:\n self.keys.up = K_UP\n self.keys.down = K_DOWN\n self.keys.left = K_LEFT\n self.keys.right = K_RIGHT\n self.keys.button = [K_RETURN, K_RSHIFT]\n elif player_id == 1:\n self.keys.up = K_e\n self.keys.down = K_d\n self.keys.left = K_s\n self.keys.right = K_f\n self.keys.button = [K_a, K_q]\n elif player_id == 2:\n self.keys.up = K_KP8\n self.keys.down = K_KP5\n self.keys.left = K_KP4\n self.keys.right = K_KP6\n self.keys.button = [K_KP1, K_KP2]\n elif player_id == 3:\n self.keys.up = K_i\n self.keys.down = K_k\n self.keys.left = K_j\n self.keys.right = K_l\n self.keys.button = [K_h, K_y]\n\n def assign():\n i = 0\n from game import game\n\n for player in game.players:\n if player.local:\n print(\"assign config\", i, \"to player\", player.player_id)\n config = PlayerConfig.instances[i]\n i += 1\n else:\n config = PlayerConfig(-1)\n player.set_config(config)\n\n assign = staticmethod(assign)\n\n\nclass Config:\n server = \"localhost\"\n total_players = 2\n local_players = 2\n ai_players = 1\n fullscreen = False\n sound = False\n\n\ndef open_config_file(mode):\n import os\n\n if os.name == \"posix\":\n file = open(os.path.join(os.getenv(\"HOME\"), \".castle-combat.config\"), mode)\n else:\n file = open(\"castle-combat.config\", mode)\n return file\n\n\ndef save():\n conf.player_configs = PlayerConfig.instances\n conf.version = 1\n file = open_config_file(\"wb\")\n import pickle\n\n pickle.dump(conf, file)\n\n\ndef load():\n global conf\n try:\n file = open_config_file(\"rb\")\n import pickle\n\n conf = pickle.load(file)\n try:\n if conf.version != 1:\n raise \"Unknown config file version.\"\n except AttributeError:\n print(\"Updating config file from alpha version\")\n PlayerConfig.instances = conf.player_configs\n except IOError:\n print(\"Could not load user's config file, loading defaults.\")\n for i in range(4):\n PlayerConfig(i)\n conf = Config()\n","repo_name":"karlb/castle-combat","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"34"} +{"seq_id":"43005899661","text":"import pandas as pd\r\nimport seaborn as sns\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.colors as mcolors\r\nimport matplotlib.cm as cm\r\nimport numpy as np\r\nimport os\r\nimport sys\r\nimport time\r\nimport datetime\r\nimport re\r\nimport statistics\r\nimport random\r\nimport math\r\nfrom statistics import mean\r\nfrom matplotlib.colors import LinearSegmentedColormap\r\n\r\ntest_x_1_list=list()\r\ntest_y_1_list=list()\r\n\r\ntest_x_2_list=list()\r\ntest_y_2_list=list()\r\n\r\ntest_x_3_list=list()\r\ntest_y_3_list=list()\r\ntest_z_3_list=list()\r\n\r\nn=10000\r\nfor i in range(n):\r\n test_x_1=random.random()\r\n test_y_1=random.random()\r\n test_x_1_list.append(test_x_1)\r\n test_y_1_list.append(test_y_1)\r\n\r\n test_x_2=random.random()\r\n test_y_2=test_x_2*(-5)+0.6\r\n test_x_2_list.append(test_x_2)\r\n test_y_2_list.append(test_y_2)\r\n\r\n test_x_3=random.random()\r\n test_z_3=random.random()\r\n test_y_3=test_x_3*test_z_3\r\n test_x_3_list.append(test_x_3)\r\n test_z_3_list.append(test_z_3)\r\n test_y_3_list.append(test_y_3)\r\n\r\nmatplotlib.rc('xtick', labelsize=25)\r\nmatplotlib.rc('ytick', labelsize=25)\r\n\r\nxy_1=list()\r\nx_sqr_1=list()\r\ny_1=list()\r\n\r\nxy_2=list()\r\nx_sqr_2=list()\r\ny_2=list()\r\n\r\nxy_3=list()\r\nx_sqr_3=list()\r\ny_3=list()\r\n\r\n#chto_x=[3,4,2]\r\n#chto_y=[15,5,1]\r\n\r\nn_1=len(test_x_1_list)\r\n\r\nn_2=len(test_x_2_list)\r\n\r\nn_3=len(test_x_3_list)\r\n\r\nfor i in range(len(test_x_1_list)):\r\n xy_1.append(test_x_1_list[i]*test_y_1_list[i])\r\n x_sqr_1.append(test_x_1_list[i]*test_x_1_list[i])\r\na_1=((n_1*sum(xy_1)-sum(test_x_1_list)*sum(test_y_1_list))/(n_1*sum(x_sqr_1)-(sum(test_x_1_list)*sum(test_x_1_list))))\r\nb_1=(sum(test_y_1_list)-a_1*sum(test_x_1_list))/n_1\r\nfor i in range(len(test_x_1_list)):\r\n y_1.append(a_1*test_x_1_list[i]+b_1)\r\n\r\nfor i in range(len(test_x_2_list)):\r\n xy_2.append(test_x_2_list[i]*test_y_2_list[i])\r\n x_sqr_2.append(test_x_2_list[i]*test_x_2_list[i])\r\na_2=((n_2*sum(xy_2)-sum(test_x_2_list)*sum(test_y_2_list))/(n_2*sum(x_sqr_2)-(sum(test_x_2_list)*sum(test_x_2_list))))\r\nb_2=(sum(test_y_2_list)-a_2*sum(test_x_2_list))/n_2\r\nfor i in range(len(test_x_2_list)):\r\n y_2.append(a_2*test_x_2_list[i]+b_2)\r\n\r\nfor i in range(len(test_x_3_list)):\r\n xy_3.append(test_x_3_list[i]*test_y_3_list[i])\r\n x_sqr_3.append(test_x_3_list[i]*test_x_3_list[i])\r\na_3=((n_3*sum(xy_3)-sum(test_x_3_list)*sum(test_y_3_list))/(n_3*sum(x_sqr_3)-(sum(test_x_3_list)*sum(test_x_3_list))))\r\nb_3=(sum(test_y_3_list)-a_3*sum(test_x_3_list))/n_3\r\nfor i in range(len(test_x_3_list)):\r\n y_3.append(a_3*test_x_3_list[i]+b_3)\r\n\r\nprint (a_1, b_1)\r\nprint (a_2, b_2)\r\nprint (a_3, b_3)\r\n#print(test_x_1_list[0])\r\n#print(test_y_1_list[0])\r\n#print(test_x_1_list[0]*test_y_1_list[0])\r\n#print(xy)\r\n#print(x_sqr)\r\n#print(a_1)\r\n#print(b_1)\r\n\r\n#print(a_2)\r\n#print(b_2)\r\n\r\n#print(a_3)\r\n#print(b_3)\r\n#print(y_1)\r\n\r\n#D_x_1=0\r\n#D_x_2=0\r\n#D_x_3=0\r\n#D_y_1=0\r\n#D_y_2=0\r\n#D_y_3=0\r\n\r\n#binsvalues_x_1=list()\r\n#binsvalues_y_1=list()\r\n#binsvalues_xy_1=list()\r\n#binsvalues_xx_1=list()\r\n#binsvalues_yy_1=list()\r\nmult=list()\r\n\r\n#for j in range (0,100,1):\r\n #binsvalues_y_1.append((j+1)/100)\r\n #py.append(test_y_1_list[j]/5000)\r\n\r\ndef mean(x):\r\n return sum(x)/len(x)\r\n\r\ndef cov(x,y):\r\n mult.clear()\r\n for i in range(len(x)):\r\n mult.append(x[i]*y[i])\r\n return mean(mult)-mean(x)*mean(y)\r\n\r\n#for i in range(len(test_x_1_list)):\r\n #binsvalues_xy_1.append(test_x_1_list[i]*test_y_1_list[i])\r\n #binsvalues_xx_1.append(test_x_1_list[i]*test_x_1_list[i])\r\n #binsvalues_yy_1.append(test_y_1_list[i]*test_y_1_list[i])\r\n #binsvalues_x_1.append((i+1)/100)\r\n #px.append(test_x_1_list[i]/5000)\r\n #for j in range (0,100,1):\r\n #binsvalues_xy_1.append(binsvalues_x_1[i]*binsvalues_y_1[j])\r\n\r\n#E_x_1=sum(test_x_1_list)/len(test_x_1_list)\r\n#E_x_1=(1/100)*sum(binsvalues_x_1)\r\n#E_y_1=sum(test_y_1_list)/len(test_y_1_list)\r\n#E_y_1=(1/100)*sum(binsvalues_y_1)\r\n#E_xy_1=sum(binsvalues_xy_1)/len(binsvalues_xy_1)\r\n#E_xx_1=sum(binsvalues_xx_1)/len(binsvalues_xx_1)\r\n#E_yy_1=sum(binsvalues_yy_1)/len(binsvalues_yy_1)\r\n#E_xy_1=(1/100)*(1/100)*sum(binsvalues_xy_1)\r\ncov_1=cov(test_x_1_list,test_y_1_list)\r\ncov_1_xx=cov(test_x_1_list,test_x_1_list)\r\ncov_1_yy=cov(test_y_1_list,test_y_1_list)\r\n#for i in range (0,100,1):\r\n #D_x_1+=(1/100)*(binsvalues_x_1[i]-E_x_1)*(binsvalues_x_1[i]-E_x_1)\r\n #D_y_1+=(1/100)*(binsvalues_y_1[i]-E_y_1)*(binsvalues_y_1[i]-E_y_1)\r\n\r\ncor_1=cov_1/(math.sqrt(cov_1_xx)*math.sqrt(cov_1_yy))\r\n\r\n#print(sum(binsvalues_x_1))\r\n#print(sum(binsvalues_y_1))\r\n#print(E_x_1)\r\n#print(E_y_1)\r\n#print(binsvalues_x_1)\r\n#print(binsvalues_y_1)\r\n#print(binsvalues_xy)\r\nprint(\"Ковариация 1 = \", cov_1)\r\n#print(cov_1_xx, cov_1_yy)\r\nprint(\"Корреляционный фактор 1 = \", cor_1, \"\\n\")\r\n\r\n#binsvalues_x_2=list()\r\n#binsvalues_y_2=list()\r\n#binsvalues_xy_2=list()\r\n\r\n#for j in range (0,100,1):\r\n #binsvalues_y_2.append(((j+1)/100)*(-5)+0.6)\r\n #py.append(test_y_1_list[j]/5000)\r\n\r\n#for i in range (0,100,1):\r\n #binsvalues_x_2.append((i+1)/100)\r\n #px.append(test_x_1_list[i]/5000)\r\n #for j in range (0,100,1):\r\n #if i==j:\r\n #binsvalues_xy_2.append(binsvalues_x_2[i]*binsvalues_y_2[j])\r\n\r\n\r\ncov_2=cov(test_x_2_list,test_y_2_list)\r\ncov_2_xx=cov(test_x_2_list,test_x_2_list)\r\ncov_2_yy=cov(test_y_2_list,test_y_2_list)\r\n\r\n#E_x_2=(1/100)*sum(binsvalues_x_2)\r\n#E_y_2=(1/100)*sum(binsvalues_y_2)\r\n#E_xy_2=(1/(100*math.sqrt(2)))*sum(binsvalues_xy_2)\r\n#cov_2=E_xy_2-E_x_2*E_y_2\r\n\r\n#for i in range (0,100,1):\r\n #D_x_2+=(1/100)*(binsvalues_x_2[i]-E_x_2)*(binsvalues_x_2[i]-E_x_2)\r\n #D_y_2+=(1/100)*(binsvalues_y_2[i]-E_y_2)*(binsvalues_y_2[i]-E_y_2)\r\n\r\n#cor_2=cov_2/(math.sqrt(D_x_2)*math.sqrt(D_y_2))\r\ncor_2=cov_2/(math.sqrt(cov_2_xx)*math.sqrt(cov_2_yy))\r\n\r\nif cor_2<(-1):\r\n cor_2=-0.999999999999999\r\n\r\n#print(binsvalues_x_2)\r\n#print(binsvalues_y_2)\r\n#print(binsvalues_xy)\r\nprint(\"Ковариация 2 = \", cov_2)\r\n#print(cov_2_xx, cov_2_yy)\r\nprint(\"Корреляционный фактор 2 = \", cor_2, \"\\n\")\r\n\r\n#m_1=100\r\n#m_2=100\r\n#binsvalues_x_3=list()\r\n#binsvalues_y_3=list()\r\n#binsvalues_z_3=list()\r\n#binsvalues_xy_3=list()\r\n#binsvalues_y_3_filled=list()\r\n#binsvalues_xy_3_filled=[[0]*m_1 for i in range(m_2)]\r\n\r\n#for j in range (0,100,1):\r\n #binsvalues_z_3.append((j+1)/100)\r\n #binsvalues_y_3.append((j+1)/100)\r\n #binsvalues_y_3_filled.append(0)\r\n #py.append(test_y_1_list[j]/5000)\r\n\r\n#for i in range (0,100,1):\r\n #binsvalues_x_3.append((i+1)/100)\r\n #px.append(test_x_1_list[i]/5000)\r\n\r\n#for j in range (0,100,1):\r\n #if j!=0 and j!=99:\r\n #for element in test_y_3_list:\r\n #if element < ((j+1)/100) and element >= (j/100):\r\n #num=test_y_3_list.index(element)\r\n #binsvalues_y_3_filled[j]+=1\r\n #for i in range (0,100,1):\r\n #if i!=0 and i!=99:\r\n #if test_x_3_list[num] < ((i+1)/100) and test_x_3_list[num] >= (i/100):\r\n #binsvalues_xy_3_filled[j][i]+=1\r\n #elif i==0:\r\n #if test_x_3_list[num] < ((j+1)/100):\r\n #binsvalues_xy_3_filled[j][i]+=1\r\n #else:\r\n #if test_x_3_list[num] >= (j/100):\r\n #binsvalues_xy_3_filled[j][i]+=1\r\n #elif j==0:\r\n #for element in test_y_3_list:\r\n #if element < ((j+1)/100):\r\n #num=test_y_3_list.index(element)\r\n #binsvalues_y_3_filled[j]+=1\r\n #for i in range (0,100,1):\r\n #if i!=0 and i!=99:\r\n #if test_x_3_list[num] < ((i+1)/100) and test_x_3_list[num] >= (i/100):\r\n #binsvalues_xy_3_filled[j][i]+=1\r\n #elif i==0:\r\n #if test_x_3_list[num] < ((j+1)/100):\r\n #binsvalues_xy_3_filled[j][i]+=1\r\n #else:\r\n #if test_x_3_list[num] >= (j/100):\r\n #binsvalues_xy_3_filled[j][i]+=1\r\n #else:\r\n #for element in test_y_3_list:\r\n #if element >= (j/100):\r\n #num=test_y_3_list.index(element)\r\n #binsvalues_y_3_filled[j]+=1\r\n #for i in range (0,100,1):\r\n #if i!=0 and i!=99:\r\n #if test_x_3_list[num] < ((i+1)/100) and test_x_3_list[num] >= (i/100):\r\n #binsvalues_xy_3_filled[j][i]+=1\r\n #elif i==0:\r\n #if test_x_3_list[num] < ((j+1)/100):\r\n #binsvalues_xy_3_filled[j][i]+=1\r\n #else:\r\n #if test_x_3_list[num] >= (j/100):\r\n #binsvalues_xy_3_filled[j][i]+=1\r\n\r\n#binsvalues_only_x_3=list()\r\n\r\n#for i in range (0,100,1):\r\n #binsvalues_only_x_3.append(0)\r\n\r\n#for i in range (0,100,1):\r\n #for j in range (0,100,1):\r\n #binsvalues_only_x_3[i]+=binsvalues_xy_3_filled[j][i]\r\n\r\n#E_x_3=(1/100)*sum(binsvalues_x_3)\r\n#E_y_3=0\r\n#E_xy_3=0\r\n\r\n#summary=0\r\n\r\n#for row in binsvalues_xy_3_filled:\r\n #for elem in row:\r\n #summary+=elem\r\n\r\n#summary=5000\r\n\r\n#for i in range (0,100,1):\r\n #E_y_3+=(binsvalues_y_3_filled[i]/sum(binsvalues_y_3_filled))*((i+1)/100)\r\n #for j in range (0,100,1):\r\n #E_xy_3+=(binsvalues_xy_3_filled[j][i]/summary)*((i+1)/100)*((j+1)/100)\r\n\r\ncov_3=cov(test_x_3_list,test_y_3_list)\r\ncov_3_xx=cov(test_x_3_list,test_x_3_list)\r\ncov_3_yy=cov(test_y_3_list,test_y_3_list)\r\n#cov_3=E_xy_3-E_x_3*E_y_3\r\n\r\n#for i in range (0,100,1):\r\n #D_x_3+=(1/100)*(binsvalues_x_3[i]-E_x_3)*(binsvalues_x_3[i]-E_x_3)\r\n #D_y_3+=(binsvalues_y_3_filled[i]/sum(binsvalues_y_3_filled))*(binsvalues_y_3[i]-E_y_3)*(binsvalues_y_3[i]-E_y_3)\r\n\r\n#cor_3=cov_3/(math.sqrt(D_x_3)*math.sqrt(D_y_3))\r\ncor_3=cov_3/(math.sqrt(cov_3_xx)*math.sqrt(cov_3_yy))\r\n\r\n#print(binsvalues_x_2)\r\n#print(binsvalues_y_2)\r\n#print(binsvalues_xy)\r\n#print(binsvalues_xy_3_filled)\r\nprint(\"Ковариация 3 = \", cov_3)\r\n#print(cov_3_xx, cov_3_yy)\r\nprint(\"Корреляционный фактор 3 = \", cor_3, \"\\n\")\r\n\r\nt_1=(abs(cor_1)*math.sqrt(n-2))/(math.sqrt(1-cor_1*cor_1))\r\nt_2=(abs(cor_2)*math.sqrt(n-2))/(math.sqrt(1-cor_2*cor_2))\r\nt_3=(abs(cor_3)*math.sqrt(n-2))/(math.sqrt(1-cor_3*cor_3))\r\n\r\nprint(\"t_stat_1 = \", t_1)\r\nprint(\"t_stat_2 = \", t_2)\r\nprint(\"t_stat_3 = \", t_3)\r\n\r\nax1 = sns.jointplot(x=test_x_1_list, y=test_y_1_list, marginal_kws=dict(bins=100, fill=True))\r\nax1.ax_joint.cla()\r\nax1.ax_joint.set_xlabel(\"x\", fontsize=25)\r\nax1.ax_joint.set_ylabel(\"y\", fontsize=25)\r\nax1.ax_joint.set_title(\"x, y - псевдослучайные \\n\\n\\n\\n\\n\", fontsize=25)\r\nplt.sca(ax1.ax_joint)\r\nplt.plot(test_x_1_list, y_1, color=\"k\", linewidth=6)\r\nplt.hist2d(test_x_1_list, test_y_1_list, bins=(100, 100), range=[[-0.3, 1.3],[-0.3, 1.3]], cmap=cm.brg);\r\n#plt.colorbar()\r\n\r\nax1 = sns.jointplot(x=test_x_2_list, y=test_y_2_list, marginal_kws=dict(bins=100, fill=True))\r\nax1.ax_joint.cla()\r\nax1.ax_joint.set_xlabel(\"x\", fontsize=25)\r\nax1.ax_joint.set_ylabel(\"y\", fontsize=25)\r\nax1.ax_joint.set_title(\"x - псведослучайная, y=-5x+0.6 \\n\\n\\n\\n\\n\", fontsize=25)\r\nplt.sca(ax1.ax_joint)\r\nplt.plot(test_x_2_list, y_2, color=\"k\", linewidth=2)\r\nplt.hist2d(test_x_2_list, test_y_2_list, bins=(100, 100), range=[[-0.3, 1.3],[-4.7, 0.9]], cmap=cm.brg);\r\n#plt.colorbar()\r\n\r\nax1 = sns.jointplot(x=test_x_3_list, y=test_y_3_list, marginal_kws=dict(bins=100, fill=True))\r\nax1.ax_joint.cla()\r\nax1.ax_joint.set_xlabel(\"x\", fontsize=25)\r\nax1.ax_joint.set_ylabel(\"y\", fontsize=25)\r\nax1.ax_joint.set_title(\"x, z - псевдослучайные, y=zx \\n\\n\\n\\n\\n\", fontsize=25)\r\nplt.sca(ax1.ax_joint)\r\nplt.plot(test_x_3_list, y_3, color=\"k\", linewidth=6)\r\nplt.hist2d(test_x_3_list, test_y_3_list, bins=(100, 100), range=[[-0.3, 1.3],[-0.3, 1.3]], cmap=cm.brg);\r\n#plt.colorbar()\r\n\r\nplt.show()\r\n","repo_name":"Russianrakkan/statistical_analysis","sub_path":"mag_lab_1.py","file_name":"mag_lab_1.py","file_ext":"py","file_size_in_byte":11911,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"13877089403","text":"from gtts import gTTS\nimport pdfplumber\n\ndef pdf_to_mp3(file_path='test.pdf', language='en'):\n if Path(file_path).is_file() and Path(file_path) == '.pdf':\n return 'File exists!'\n else:\n return 'File not exist, check the file path'\n\ndef Pdf_to_mp3():\n print(pdf_to_mp3(file_path='\\Dekunov\\Documents\\HYPER\\HIPER_CORP_v5_3_сент.pdf'))\n\nif __name__ == '__Pdf_to_mp3__':\n main()","repo_name":"alexdekunov/PDF_to_-mp3","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"36420238845","text":"\"\"\"\nExample script that creates the model manually using sympy.\n\"\"\"\n\n# Author: Fabricio Olivetti de Franca \n# Gabriel Kronberger \n#\n# License: MIT\n\nimport numpy as np\nimport sympy as sym\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfont = {'family' : 'normal',\n 'weight' : 'bold',\n 'size' : 22}\n\nmatplotlib.rc('font', **font)\n\nfrom profile_t.symbolic_expression import SymExpr\nfrom profile_t import ProfileT\nfrom profile_t.plots import plot_all_theta_theta, plot_all_tau_theta, plot_errorbar\n\ndef DemoBOD():\n # data points\n x = np.array([1,2,3,4,5,7])\n y = np.array([8.3, 10.3, 19.0, 16.0, 15.6, 19.8])\n\n # sympy symbols\n x_symb = sym.symbols('x')\n t_symb = sym.symbols('theta0 theta1')\n\n # initial values of theta\n theta = [20, 0.24]\n\n # regression model\n expr = t_symb[0] * (1 - sym.exp(-x_symb * t_symb[1]))\n\n # create profile object and calculate the ci with linear approx. and without\n profile = ProfileT(SymExpr(expr, t_symb, x_symb, x, y), theta)\n profile.report_parameters_ci(0.01, True)\n profile.report_parameters_ci(0.01)\n print(\"\\nPrediction intervals (linear):\")\n profile.report_prediction_interval(np.arange(0,6,1), 0.01, True)\n print(\"\\nPrediction intervals (profile):\")\n profile.report_prediction_interval(np.arange(0,6,1), 0.01)\n\n # create the plots\n plot_all_theta_theta(profile, \"BOD\", 0.01, font)\n plot_all_tau_theta(profile, \"BOD\", font)\n\n fig, ax = plt.subplots(2,1,figsize=(15,15), constrained_layout=True)\n ax_linear = plt.subplot(2,1,1)\n ax_prof = plt.subplot(2,1,2)\n plot_errorbar(profile, 0.01, np.arange(0,6,1), ax_linear, ax_prof)\n plt.savefig('BOD_predictions.pdf')\n\nif __name__ == '__main__':\n DemoBOD()","repo_name":"folivetti/profile_t","sub_path":"examples/DemoBOD.py","file_name":"DemoBOD.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"31138574568","text":"#!/usr/bin/python3\n\"\"\"\nPython script to export data in the CSV format.\n\"\"\"\nfrom sys import argv\nimport csv\nimport requests\n\n\nif __name__ == '__main__':\n url = 'https://jsonplaceholder.typicode.com/'\n\n user_endpoint = '{}users/{}'.format(url, argv[1])\n user_response = requests.get(user_endpoint)\n user_data = user_response.json()\n employee_name = user_data.get('username')\n\n todos_endpoint = '{}todos?userId={}'.format(url, argv[1])\n todos_response = requests.get(todos_endpoint)\n todos_data = todos_response.json()\n\n with open('{}.csv'.format(argv[1]), mode='w') as csvfile:\n csv_writer = csv.writer(csvfile, quoting=csv.QUOTE_ALL)\n for todo in todos_data:\n csv_writer.writerow([argv[1], employee_name,\n todo.get('completed'), todo.get('title')])\n","repo_name":"kelechi-aims/alx-system_engineering-devops","sub_path":"0x15-api/1-export_to_CSV.py","file_name":"1-export_to_CSV.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"71985035937","text":"\"\"\"Classes to manage presentations.\"\"\"\n\nimport json\nimport logging\nfrom uuid import uuid4\n\nfrom ...config.injection_context import InjectionContext\nfrom ...error import BaseError\nfrom ...holder.base import BaseHolder\nfrom ...ledger.base import BaseLedger\nfrom ...verifier.base import BaseVerifier\n\nfrom .models.presentation_exchange import PresentationExchange\nfrom .messages.presentation_request import PresentationRequest\nfrom .messages.credential_presentation import CredentialPresentation\n\n\nclass PresentationManagerError(BaseError):\n \"\"\"Presentation error.\"\"\"\n\n\nclass PresentationManager:\n \"\"\"Class for managing presentations.\"\"\"\n\n def __init__(self, context: InjectionContext):\n \"\"\"\n Initialize a PresentationManager.\n\n Args:\n context: The context for this credential\n \"\"\"\n self._context = context\n self._logger = logging.getLogger(__name__)\n\n @property\n def context(self) -> InjectionContext:\n \"\"\"\n Accessor for the current request context.\n\n Returns:\n The injection context for this presentation manager\n\n \"\"\"\n return self._context\n\n async def create_request(\n self,\n name: str,\n version: str,\n requested_attributes: list,\n requested_predicates: list,\n connection_id: str,\n ):\n \"\"\"Create a proof request.\"\"\"\n\n presentation_request = {\n \"name\": name,\n \"version\": version,\n \"nonce\": str(uuid4().int),\n \"requested_attributes\": {},\n \"requested_predicates\": {},\n }\n\n for requested_attribute in requested_attributes:\n presentation_request[\"requested_attributes\"][\n str(uuid4())\n ] = requested_attribute\n\n for requested_predicates in requested_predicates:\n presentation_request[\"requested_predicates\"][\n str(uuid4())\n ] = requested_predicates\n\n presentation_request_message = PresentationRequest(\n request=json.dumps(presentation_request)\n )\n\n presentation_exchange = PresentationExchange(\n connection_id=connection_id,\n initiator=PresentationExchange.INITIATOR_SELF,\n state=PresentationExchange.STATE_REQUEST_SENT,\n presentation_request=presentation_request,\n thread_id=presentation_request_message._thread_id,\n )\n\n await presentation_exchange.save(\n self.context, reason=\"Create presentation request\"\n )\n\n return presentation_exchange, presentation_request_message\n\n async def receive_request(\n self, presentation_request_message: PresentationRequest, connection_id: str\n ):\n \"\"\"\n Receive a presentation request.\n\n Args:\n presentation_request_message: Presentation message to receive\n \"\"\"\n\n presentation_exchange = PresentationExchange(\n connection_id=connection_id,\n thread_id=presentation_request_message._thread_id,\n initiator=PresentationExchange.INITIATOR_EXTERNAL,\n state=PresentationExchange.STATE_REQUEST_RECEIVED,\n presentation_request=json.loads(presentation_request_message.request),\n )\n\n await presentation_exchange.save(\n self.context, reason=\"Receive presentation request\"\n )\n\n return presentation_exchange\n\n async def create_presentation(\n self,\n presentation_exchange_record: PresentationExchange,\n requested_credentials: dict,\n ):\n \"\"\"\n Receive a presentation request.\n\n Args:\n presentation_exchange_record: Record to update\n requested_credentials: Indy formatted requested_credentials\n\n i.e.,\n\n ::\n\n {\n \"self_attested_attributes\": {\n \"j233ffbc-bd35-49b1-934f-51e083106f6d\": \"value\"\n },\n \"requested_attributes\": {\n \"6253ffbb-bd35-49b3-934f-46e083106f6c\": {\n \"cred_id\": \"5bfa40b7-062b-4ae0-a251-a86c87922c0e\",\n \"revealed\": true\n }\n },\n \"requested_predicates\": {\n \"bfc8a97d-60d3-4f21-b998-85eeabe5c8c0\": {\n \"cred_id\": \"5bfa40b7-062b-4ae0-a251-a86c87922c0e\"\n }\n }\n }\n\n \"\"\"\n\n # Get all credential ids for this presentation\n credential_ids = []\n\n requested_attributes = requested_credentials[\"requested_attributes\"]\n for presentation_referent in requested_attributes:\n credential_id = requested_attributes[presentation_referent][\"cred_id\"]\n credential_ids.append(credential_id)\n\n requested_predicates = requested_credentials[\"requested_predicates\"]\n for presentation_referent in requested_predicates:\n credential_id = requested_predicates[presentation_referent][\"cred_id\"]\n credential_ids.append(credential_id)\n\n # Get all schema and credential definition ids in use\n # TODO: Cache this!!!\n schema_ids = []\n credential_definition_ids = []\n holder: BaseHolder = await self.context.inject(BaseHolder)\n for credential_id in credential_ids:\n credential = await holder.get_credential(credential_id)\n schema_id = credential[\"schema_id\"]\n credential_definition_id = credential[\"cred_def_id\"]\n schema_ids.append(schema_id)\n credential_definition_ids.append(credential_definition_id)\n\n schemas = {}\n credential_definitions = {}\n\n ledger: BaseLedger = await self.context.inject(BaseLedger)\n async with ledger:\n\n # Build schemas for anoncreds\n for schema_id in schema_ids:\n schema = await ledger.get_schema(schema_id)\n schemas[schema_id] = schema\n\n # Build credential_definitions for anoncreds\n for credential_definition_id in credential_definition_ids:\n (credential_definition) = await ledger.get_credential_definition(\n credential_definition_id\n )\n credential_definitions[credential_definition_id] = credential_definition\n\n holder: BaseHolder = await self.context.inject(BaseHolder)\n presentation = await holder.create_presentation(\n presentation_exchange_record.presentation_request,\n requested_credentials,\n schemas,\n credential_definitions,\n )\n\n presentation_message = CredentialPresentation(\n presentation=json.dumps(presentation)\n )\n\n # TODO: Find a more elegant way to do this\n presentation_message._thread = {\"thid\": presentation_exchange_record.thread_id}\n\n # save presentation exchange state\n presentation_exchange_record.state = (\n PresentationExchange.STATE_PRESENTATION_SENT\n )\n presentation_exchange_record.presentation = presentation\n await presentation_exchange_record.save(\n self.context,\n reason=\"Create presentation\",\n log_params={\"requested_credentials\": requested_credentials},\n )\n\n return presentation_exchange_record, presentation_message\n\n async def receive_presentation(self, presentation: dict, thread_id: str):\n \"\"\"Receive a presentation request.\"\"\"\n (\n presentation_exchange_record\n ) = await PresentationExchange.retrieve_by_tag_filter(\n self.context, tag_filter={\"thread_id\": thread_id, \"initiator\": \"self\"}\n )\n\n presentation_exchange_record.presentation = presentation\n presentation_exchange_record.state = (\n PresentationExchange.STATE_PRESENTATION_RECEIVED\n )\n await presentation_exchange_record.save(\n self.context, reason=\"Receive presentation\"\n )\n\n return presentation_exchange_record\n\n async def verify_presentation(\n self, presentation_exchange_record: PresentationExchange\n ):\n \"\"\"Verify a presentation request.\"\"\"\n\n presentation_request = presentation_exchange_record.presentation_request\n presentation = presentation_exchange_record.presentation\n\n schema_ids = []\n credential_definition_ids = []\n\n identifiers = presentation[\"identifiers\"]\n for identifier in identifiers:\n schema_ids.append(identifier[\"schema_id\"])\n credential_definition_ids.append(identifier[\"cred_def_id\"])\n\n schemas = {}\n credential_definitions = {}\n\n ledger: BaseLedger = await self.context.inject(BaseLedger)\n async with ledger:\n\n # Build schemas for anoncreds\n for schema_id in schema_ids:\n schema = await ledger.get_schema(schema_id)\n schemas[schema_id] = schema\n\n # Build credential_definitions for anoncreds\n for credential_definition_id in credential_definition_ids:\n (credential_definition) = await ledger.get_credential_definition(\n credential_definition_id\n )\n credential_definitions[credential_definition_id] = credential_definition\n\n verifier: BaseVerifier = await self.context.inject(BaseVerifier)\n verified = await verifier.verify_presentation(\n presentation_request, presentation, schemas, credential_definitions\n )\n\n presentation_exchange_record.verified = \"true\" if verified else \"false\"\n presentation_exchange_record.state = PresentationExchange.STATE_VERIFIED\n\n await presentation_exchange_record.save(\n self.context, reason=\"Verify presentation\"\n )\n\n return presentation_exchange_record\n","repo_name":"OpenMined/PyAriesFL","sub_path":"aries_cloudagent/messaging/presentations/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":9887,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"34"} +{"seq_id":"42872682795","text":"\"\"\"\nSet of handlers of the Flickr backup data.\n\"\"\"\nimport collections.abc\nimport json\nimport logging\nimport re\nimport shutil\nimport os\nfrom os import path\nfrom typing import List, Optional\n\nfrom flickr.utils import find_duplicates, normalize\n\n\nlogger = logging.getLogger(\"flickr_backup\")\n\n\nclass FlickrAlbums(collections.abc.Mapping):\n \"\"\"\n Flickr's albums (read-only) collection.\n \"\"\"\n\n def __init__(self, raw_albums: dict):\n \"\"\"\n Class initialization.\n \"\"\"\n self.albums: dict = dict()\n for album in raw_albums[\"albums\"]:\n self.albums[album[\"title\"]] = {\n \"normalized_title\": normalize(album[\"title\"], allow_unicode=False),\n \"photos\": album[\"photos\"],\n }\n\n def __iter__(self):\n return iter(self.albums)\n\n def keys(self):\n return self.albums.keys()\n\n def items(self):\n return self.albums.items()\n\n def values(self):\n return self.albums.values()\n\n def __getitem__(self, key) -> dict:\n return self.albums[key]\n\n def __contains__(self, item) -> bool:\n return item in self.albums\n\n def __len__(self) -> int:\n return len(self.albums)\n\n\nclass FlickrAlbumsHandler:\n \"\"\"\n Handlers of the Flickr albums\n \"\"\"\n\n #: Flickr's albums JSON filename.\n JSON_FILENAME: str = \"albums.json\"\n #: Duplicates registry filename.\n DUPLICATES_FILENAME: str = \"duplicates.txt\"\n #: Directory name for photos without album.\n ALBUMLESS_PICS_DIR: str = \"__no_album__\"\n\n def __init__(self, json_dir: str, photos_dir: str, output_dir: Optional[str] = None):\n \"\"\"\n Class initialization.\n\n :param json_dir: Absolute or relative path to the `albums.json` file.\n :param photos_dir: Absolute or relative path to the photos directory.\n :param output_dir: Absolute to relative path to the output dir, defaults\n to `photos_dir`.\n \"\"\"\n with open(path.join(path.abspath(json_dir), self.JSON_FILENAME), \"r\") as albums_file:\n raw_albums = json.load(albums_file)\n\n self.albums = FlickrAlbums(raw_albums)\n self.photos_dir = path.abspath(photos_dir)\n\n if output_dir:\n self.output_dir = path.abspath(output_dir)\n\n if not path.exists(self.output_dir):\n os.mkdir(self.output_dir)\n else:\n self.output_dir = self.photos_dir\n\n def _get_pics_filenames(self, pic_ids: List[str]) -> List[str]:\n \"\"\"\n Find the photo filenames identified by its corresponding Flick photo Id.\n\n :param pic_id: List of Flickr photo Ids.\n :return: List of photo filenames that are found.\n \"\"\"\n dir_content = os.listdir(self.photos_dir)\n pattern = re.compile(rf\".*_({'|'.join(pic_ids)})_.*\")\n\n return list(filter(pattern.match, dir_content))\n\n def _create_album(self, name: str, pic_filenames: List[str]):\n \"\"\"\n Creates an album (directory) and copy its pictures.\n\n :param name: Album's name.\n :param pic_filenames: List of photo filenames.\n \"\"\"\n album_dir = path.join(self.output_dir, name)\n if not path.exists(album_dir):\n os.mkdir(album_dir)\n else:\n logger.info(f\"Album '{name}' already exists, no photos copied/moved.\")\n return\n\n pics_num = 0\n for filename in pic_filenames:\n full_filename = path.join(self.photos_dir, filename)\n shutil.copy2(full_filename, album_dir)\n logger.debug(f\"Photo '{filename}' copied to album '{name}'.\")\n\n pics_num += 1\n\n logger.info(f\"Album '{name}' created with {pics_num} photos.\")\n\n def _duplicates(self, pics_sets: List[set]) -> int:\n \"\"\"\n Detects photos shared among several albums a write a duplicates registry\n in a text file.\n\n :param pics_sets: Set of photos per album.\n :return: Number of duplicates.\n \"\"\"\n duplicates = sorted(find_duplicates(pics_sets))\n\n with open(path.join(self.output_dir, self.DUPLICATES_FILENAME), \"w\") as dup_file:\n for filename in duplicates:\n dup_file.write(\"{}\\n\".format(filename))\n\n return len(duplicates)\n\n def _albumless_pics(self, album_pics: set) -> int:\n \"\"\"\n Identifies photos that are not included in any album to group them into\n a separate directory.\n\n :param album_pics: Set of pics that were included in albums.\n :return: Number of photos without album.\n \"\"\"\n all_pics = set()\n for filename in os.listdir(self.photos_dir):\n if path.isfile(path.join(self.photos_dir, filename)) and not filename.endswith(\".json\"):\n all_pics.add(filename)\n\n no_album_pics = all_pics - album_pics\n\n if no_album_pics:\n self._create_album(self.ALBUMLESS_PICS_DIR, list(no_album_pics))\n\n return len(no_album_pics)\n\n def make(self):\n \"\"\"\n Creates directories with album names and copy/move photos to them.\n \"\"\"\n pics_sets = []\n for album_metadata in self.albums.values():\n album_pics = self._get_pics_filenames(album_metadata[\"photos\"])\n self._create_album(album_metadata[\"normalized_title\"], album_pics)\n\n # To find duplicates\n pics_sets.append(set(album_pics))\n\n # Handling duplicates\n num_duplicates = self._duplicates(pics_sets)\n\n # Handling photos that has no album.\n album_pics = set.union(*pics_sets)\n num_albumless_pics = self._albumless_pics(album_pics)\n\n logger.info(\n f\"Processed {len(self.albums)} albums and {len(album_pics)} photos of which \"\n f\"{num_duplicates} are shared among two or more albums.\"\n )\n logger.info(f\"List of shared photos written to {self.DUPLICATES_FILENAME}\")\n if num_albumless_pics:\n logger.info(\n f\"An additional of {num_albumless_pics} photos weren't part of any album. Such \"\n f\"photos were copied to the directory '{self.ALBUMLESS_PICS_DIR}'.\"\n )\n","repo_name":"layoaster/flickr-backup","sub_path":"flickr/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":6155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"34"} +{"seq_id":"31991347521","text":"from scipy import zeros\nfrom scipy.misc import factorial\n\nimport operator\n\ndef nChooseK(n, k):\n \"\"\"n choose k\n \n Returns number of combinations of k elements in n elements\n @param n total number of elements in set\n @param k number of elements in subset to choose\n @return C(n, k)\n \"\"\"\n numerator = 1\n for i in xrange(max(n - k, k) + 1, n + 1):\n numerator *= i\n \n return numerator / factorial(min(n - k, k), exact = 1)\n\nclass xcombinations(object):\n \"\"\"Returns all combinations of subsetSize number from [0, setSize)\n \n Supports len()\n @param setSize number of elements in set to select from\n @param subsetSize number of elements chosen from set\n @return generator of combinations. Combination is stored in a 1D array of subsetSize length.\n None if subsetSize is 0.\n \"\"\"\n \n def __init__(self, setSize, subsetSize):\n if setSize < subsetSize:\n raise ValueError(\"setSize (%d) must be >= subsetSize (%d)\" % \n (setSize, subsetSize))\n \n self.setSize = setSize\n self.subsetSize = subsetSize\n \n def len(self):\n return nChooseK(self.setSize, self.subsetSize)\n \n def __iter__(self):\n a = zeros(self.subsetSize)\n # using a closure faster than passing setSize\n def recursiveXCombinations(setStart, recursiveSubsetSize):\n if recursiveSubsetSize == 0:\n yield None\n else:\n index = self.subsetSize - recursiveSubsetSize\n for i in xrange(setStart, self.setSize - recursiveSubsetSize + 1):\n a[index] = i\n for j in recursiveXCombinations(i + 1, recursiveSubsetSize - 1):\n yield a\n \n return recursiveXCombinations(0, self.subsetSize)\n\ndef permutations(setSize, subsetSize):\n \"\"\"Return 'setSize permute subsetSize' or nPk\n \n @param setSize number of elements in set to select from\n @param subsetSize number for elements chosen from set\n @return number of permutations of subsetSize of setSize\n \"\"\"\n count = 1\n for i in xrange(setSize - subsetSize + 1, setSize + 1):\n count *= i\n \n return count\n\nclass xpermutations(object):\n \"\"\"Returns all permutations of subsetSize number from [0, setSize)\n \n Supports len()\n @param setSize number of elements in set to select from\n @param subsetSize number for elements chosen from set\n @return generator of permutations. Permutations stored in a 1D array of\n subsetSize length. None if subsetsize is 0\n \"\"\"\n \n def __init__(self, setSize, subsetSize):\n if setSize < subsetSize:\n raise ValueError(\"setSize (%d) must be >= subsetSize (%d)\" % \n (setSize, subsetSize))\n \n self.setSize = setSize\n self.subsetSize = subsetSize\n \n def len(self):\n return permutations(self.setSize, self.subsetSize)\n \n def __iter__(self):\n a = zeros(self.subsetSize)\n items = range(self.setSize)\n # using a closure faster than passing setSize\n def recursiveXPermutations(recursiveItems, recursiveSubsetSize):\n if recursiveSubsetSize == 0:\n yield None\n else:\n index = self.subsetSize -recursiveSubsetSize\n for i in xrange(len(recursiveItems)):\n a[index] = recursiveItems[i]\n for cc in recursiveXPermutations(recursiveItems[:i] + recursiveItems[i + 1:], recursiveSubsetSize - 1):\n yield a\n \n return recursiveXPermutations(items, self.subsetSize)\n\ndef selections(setSizes):\n length = 1\n for setSize in setSizes:\n length *= setSize\n \n return length\n\nclass xselections(object):\n \"\"\"Returns all selections of one item from each set of setSizes\n \n Supports len()\n @param collection of set sizes\n @return generator of selections. Selection is stored in a 1D array with\n each entry corresponding to the selected index from the respective\n set.\n None if no sets\n \"\"\"\n \n def __init__(self, setSizes):\n self.setSizes = setSizes\n \n def __len__(self):\n return selections(self.setSizes)\n \n def len(self):\n return selections(self.setSizes)\n \n def __iter__(self):\n a = zeros(len(self.setSizes))\n setCount = len(self.setSizes)\n \n def recursiveXSelections(setIndex):\n if setIndex == setCount:\n yield None\n else:\n for i in xrange(0, self.setSizes[setIndex]):\n a[setIndex] = i\n for j in recursiveXSelections(setIndex + 1):\n yield a\n \n return recursiveXSelections(0)\n","repo_name":"KronicDeth/biclustering","sub_path":"src/python/Biclustering/Combinatorics.py","file_name":"Combinatorics.py","file_ext":"py","file_size_in_byte":4866,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"34"} +{"seq_id":"11218495149","text":"# scoding:utf-8\nimport pylab as pl\nimport data_field_cluster as dfc\nimport numpy as np\nimport show_track\nimport Utility\n\n\n# def compare_num_limit(min_num, max_num, dist_2_array, velocity_list, optimal_sigma, velocity_sigma):\ndef compare_num_limit(min_num, max_num, dist_2_array, velocity_list, optimal_sigma, velocity_sigma, compressed_data):\n colors = ['r', 'b', 'g', 'y', 'k']\n colors_len = len(colors)\n num_interval = (max_num - min_num)/(colors_len-1)\n first_num = min_num\n color_index = 0\n plot_arr = []\n num_arr = []\n # pl.figure(figsize=(8, 6), dpi=200)\n # pl.subplot(1, 1, 1)\n while first_num <= max_num:\n num_arr.append(first_num)\n dist_2_array_copy = []\n for arr in dist_2_array: # 备份起来,最后的优化处理会用到\n arr_list = []\n for ele in arr:\n arr_list.append(ele)\n dist_2_array_copy.append(arr_list)\n # 在进行密度计算时,距离矩阵也需要先归一化\n partial_dist_list = Utility.calculate_partial_dist(dist_2_array, first_num)\n Utility.normalize_dist_array(dist_2_array_copy, partial_dist_list)\n stability_list = Utility.calculate_stability(compressed_data, first_num) # 采用距离方差的方法\n potential_list = Utility.calculate_potential_value(dist_2_array_copy, stability_list,\n optimal_sigma, velocity_sigma, first_num)\n potential_list.sort(reverse=True)\n sequence_xlable = []\n max_potential = max(potential_list)\n total_len = len(potential_list)\n\n for i in range(total_len):\n potential_list[i] = float(potential_list[i] / max_potential)\n sequence_xlable.append(float(i*1.0/total_len))\n l, = pl.plot(sequence_xlable, potential_list, colors[color_index % colors_len])\n plot_arr.append(l)\n pl.setp(l, markersize=3)\n pl.xlabel('normalized sequence')\n pl.ylabel('normalized density')\n first_num += num_interval\n color_index += 1\n pl.legend((plot_arr[0], plot_arr[1], plot_arr[2], plot_arr[3], plot_arr[4]),\n (r'Nap=' + str(num_arr[0]), r'Nap=' + str(num_arr[1]),\n r'Nap=' + str(num_arr[2]), r'Nap=' + str(num_arr[3]),\n r'Nap=' + str(num_arr[4])\n ), loc='best', numpoints=1)\n # pl.show()\n pl.savefig(u\"C:\\\\Users\\Administrator\\Desktop\\\\1.png\", dpi=1000)\n\n\ndef compare_distance_sigma(min_sigma, max_sigma, dist_2_array, velocity_list, velocity_sigma, num_limit):\n colors = ['r', 'b', 'g', 'y', 'k', 'c']\n colors_len = len(colors)\n sigma_interval = (max_sigma - min_sigma) / (len(colors)-1)\n first_sigma = min_sigma\n color_index = 0\n plot_arr = []\n sigma_arr = []\n while first_sigma <= max_sigma:\n dist_2_array_copy = []\n for arr in dist_2_array: # 备份起来,最后的优化处理会用到\n arr_list = []\n for ele in arr:\n arr_list.append(ele)\n dist_2_array_copy.append(arr_list)\n # 在进行密度计算时,距离矩阵也需要先归一化\n partial_dist_list = Utility.calculate_partial_dist(dist_2_array, num_limit)\n Utility.normalize_dist_array(dist_2_array_copy, partial_dist_list)\n potential_list = Utility.calculate_potential_value(dist_2_array_copy, velocity_list,\n first_sigma, velocity_sigma, num_limit)\n potential_list.sort(reverse=True)\n sequence_xlable = []\n max_potential = max(potential_list)\n total_len = len(potential_list)\n for i in range(total_len):\n potential_list[i] = float(potential_list[i] / max_potential)\n sequence_xlable.append(float(i * 1.0 / total_len))\n l, = pl.plot(sequence_xlable, potential_list, colors[color_index % colors_len])\n plot_arr.append(l)\n sigma_arr.append(first_sigma)\n pl.setp(l, markersize=3)\n first_sigma += sigma_interval\n color_index += 1\n pl.legend((plot_arr[0], plot_arr[1], plot_arr[2], plot_arr[3], plot_arr[4], plot_arr[5]),\n (r'$\\sigma_1=$' + str(sigma_arr[0]), r'$\\sigma_1=$' + str(sigma_arr[1]),\n r'$\\sigma_1=$' + str(sigma_arr[2]), r'$\\sigma_1=$' + str(sigma_arr[3]),\n r'$\\sigma_1=$' + str(sigma_arr[4]), r'$\\sigma_1=$' + str(sigma_arr[5])\n ), loc='best', numpoints=1)\n pl.xlabel('normalized sequence')\n pl.ylabel('normalized density')\n # pl.title('the density influence of sigma')\n # pl.show()\n pl.savefig(u\"C:\\\\Users\\Administrator\\Desktop\\\\2.png\", dpi=1000)\n\n\ndef test_num_limit(file_name, min_num, max_num, optimal_sigma, velocity_sigma):\n show_track.show_track(file_name)\n # data = Utility.read_data_file(file_name) # 注意修改数据文件时要修改读文件程序\n data = Utility.read_geolife_data_file(file_name)\n compressed_data = Utility.data_preprocessing(data)\n dist_2_array = Utility.calculate_dist_2_array(compressed_data)\n dfc.normalize_point_velocity(compressed_data) # 速度归一化\n velocity_list = [point.velocity for point in compressed_data]\n compare_num_limit(min_num, max_num, dist_2_array, velocity_list, optimal_sigma, velocity_sigma, compressed_data)\n\n\ndef test_distance_sigma(file_name, min_sigma, max_sigma, velocity_sigma, num_limit):\n show_track.show_track(file_name)\n # data = Utility.read_data_file(file_name) # 注意修改数据文件时要修改读文件程序\n data = Utility.read_geolife_data_file(file_name)\n compressed_data = Utility.data_preprocessing(data)\n dist_2_array = Utility.calculate_dist_2_array(compressed_data)\n dfc.normalize_point_velocity(compressed_data) # 速度归一化\n # velocity_list = [point.velocity for point in compressed_data]\n # compare_distance_sigma(min_sigma, max_sigma, dist_2_array, velocity_list, velocity_sigma, num_limit)\n stability_list = Utility.calculate_stability(compressed_data, num_limit) #采用距离方差的方法\n compare_distance_sigma(min_sigma, max_sigma, dist_2_array, stability_list, velocity_sigma, num_limit)\n\n# f_name = u\"D:\\Python\\PaperPy\\DataOperation\\data\\geolife_data\\geolife_022\\geolife_022_2009-07-16.txt\"\nf_name = \"D:\\Python\\PaperPy\\data_filed_cluster\\experience_result\\\\new experiment\\\\NewDBSCAN\\compare_experiment\" \\\n \"\\CB-SMotT\\geolife_experiment\\geolife_subtrajectory2\\\\90.txt\"\n# f_name = 'data\\IMIS_3_DAY_152.txt'\n# vel_sigma = 0.5\n# adj_num = 51\n\ntest_num_limit(f_name, 20, 100, 0.3, 0.5)\n# test_distance_sigma(f_name, 0.1, 0.8, vel_sigma, adj_num)\n\n","repo_name":"ltingtech/PaperPy","sub_path":"data_field_cluster/parameter_compare.py","file_name":"parameter_compare.py","file_ext":"py","file_size_in_byte":6688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"34"} +{"seq_id":"71794889403","text":"#!/usr/bin/python3\n\"\"\"\nScript that sends a request to the URL and\ndisplays the value of the X-Request-Id.\n\"\"\"\n\nimport urllib.request\nfrom sys import argv\n\nif __name__ == \"__main__\":\n url = argv[1]\n with urllib.request.urlopen(url) as response:\n html = response.headers\n print(html[\"X-Request-Id\"])\n","repo_name":"LuisaPinillos/holbertonschool-higher_level_programming","sub_path":"0x11-python-network_1/1-hbtn_header.py","file_name":"1-hbtn_header.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"981579356","text":"import doctest\nimport sys\n\ndef factorial(n):\n '''Returns the factorial of N\n \n F(N) = N!= N * (N-1) * (N-2)...*1\n F(0) = 1\n \n >>> factorial(0)\n 1\n >>> factorial(1)\n 1\n >>> factorial(10)\n 3628800\n '''\n total = 1\n for i in range(1,n+1):\n total *= i\n return total\n \ndef fibonacci(n):\n '''Returns the Nth value in the Fibonacci\n sequence\n \n F(N) = F(N-1) + F(N-2)\n F(0) = 0, F(1) = 1\n \n >>> fibonacci(0)\n 0\n >>> fibonacci(1)\n 1\n >>> fibonacci(2)\n 1\n >>> fibonacci(5)\n 5\n '''\n assert n >= 0\n assert isinstance(n, int)\n a, b = 0, 1\n while n > 0:\n a, b = b, a+b\n n -= 1\n return a\n\nif __name__ == \"__main__\": \n doctest.testmod()\n","repo_name":"KerensaMcElroy/SWC1","sub_path":"fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"24911827249","text":"import re\nimport os\n\ndef count_functions(file_path):\n # Regular expression patterns\n pattern_external_body = re.compile(r'#\\[verifier\\(external_body\\)]\\s*pub\\s+fn')\n pattern_external_pub_fn = re.compile(r'#\\[verifier\\(external\\)]\\s*pub\\s+fn')\n pattern_external_fn = re.compile(r'#\\[verifier\\(external\\)]\\s*fn')\n view_struct_pattern = re.compile(r'struct\\s+View\\b')\n\n # Reading the file\n with open(file_path, 'r') as file:\n file_contents = file.read()\n\n # Finding the position of the first 'View' struct\n view_struct_match = view_struct_pattern.search(file_contents)\n if view_struct_match:\n content_up_to_view_struct = file_contents[:view_struct_match.start()]\n else:\n content_up_to_view_struct = file_contents\n\n # Counting the occurrences\n count_external_body = len(pattern_external_body.findall(content_up_to_view_struct))\n count_external_pub_fn = len(pattern_external_pub_fn.findall(content_up_to_view_struct))\n count_external_fn = len(pattern_external_fn.findall(content_up_to_view_struct))\n\n # Returning the counts\n return count_external_body, count_external_pub_fn, count_external_fn\n\ndef count_test_functions(test_filename, test_directory_path='src/unit_tests/kubernetes_api_objects'):\n \"\"\"Count test functions in the given file.\"\"\"\n test_file_path = os.path.join(test_directory_path, test_filename)\n count = 0\n test_function_pattern = re.compile(r\"pub fn test_\")\n special_functions = {\"test_marshal\", \"test_kube\"}\n if os.path.isfile(test_file_path):\n with open(test_file_path, 'r') as file:\n content = file.read()\n matches = test_function_pattern.findall(content)\n count = len(matches)\n for special_function in special_functions:\n if special_function in content:\n count += 1\n return count\n\ndef find_structs(file_path):\n \"\"\"Find all struct names in the given file.\"\"\"\n with open(file_path, 'r') as file:\n file_contents = file.read()\n\n struct_pattern = re.compile(r'pub struct\\s+(\\w+)\\b')\n enum_pattern = re.compile(r'pub enum\\s+(\\w+)\\b')\n all_structs = struct_pattern.findall(file_contents) + enum_pattern.findall(file_contents)\n\n # Exclude structs containing 'View' in their name\n return [s for s in all_structs if 'View' not in s]\n\ndef camel_to_snake(name):\n \"\"\"Convert CamelCase to snake_case.\"\"\"\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()\n\ndef main():\n api_directory_path = 'src/kubernetes_api_objects' # Update this path if needed\n test_directory_path = 'src/unit_tests/kubernetes_api_objects'\n for filename in sorted(os.listdir(api_directory_path)): # loop through all files in api_directory_path\n if filename.endswith('.rs'):\n file_path = os.path.join(api_directory_path, filename)\n structs = find_structs(file_path)\n if filename == 'api_method.rs':\n structs = ['ApiMethod']\n if filename == 'error.rs':\n structs = ['Error']\n test_count = 0\n struct_count = {}\n for struct_name in structs: # count every struct's test functions\n test_filename = f\"{camel_to_snake(struct_name)}.rs\"\n test_file_path = os.path.join(test_directory_path, test_filename)\n temp = count_test_functions(test_filename)\n test_count += temp\n struct_count[struct_name] = temp\n count_external_body, count_external_pub_fn, count_external_fn = count_functions(file_path)\n total_count = count_external_body + count_external_pub_fn + count_external_fn\n \n if total_count != test_count:\n print(f\"{filename}: Total Count = {total_count}\")\n print(\"Test Count = \", test_count)\n print(\"ERROR: Test Count != Total Count\")\n print(struct_count)\n print(\"-------------------------------------------\")\n elif total_count == 0:\n print(f\"{filename}: Total Count = {total_count}\")\n print(\"-------------------------------------------\")\n else:\n print(f\"{filename}: Total Count = {total_count}\")\n print(\"Test Count = \", test_count)\n print(\"Test coverage:\", round(test_count / total_count * 100, 2), \"%\")\n print(\"-------------------------------------------\")\nif __name__ == \"__main__\":\n main()\n","repo_name":"marshtompsxd/verifiable-controllers","sub_path":"tools/count-tests.py","file_name":"count-tests.py","file_ext":"py","file_size_in_byte":4562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"41"} +{"seq_id":"7330963899","text":"import re\nstring1 = '{{\"设备\"}, {\"Bluetooth Mouse M557\", \"已连接\"}, {\"Jason\\'s QC35\", \"未连接\"}, {\"“Jason”的 Powerbeats³\", \"未连接\"}}'\n\n\n# 去除大括号\ndef remove_braces(inputstr):\n string_list = inputstr.split('{')\n slist = []\n for s in string_list:\n if '}' in s:\n s = re.sub('}', '', s, 1000)\n\n slist.append(s)\n while '' in slist:\n slist.remove('')\n# print(slist)\n return slist\n\n\n# 去除多余的词汇如'设备'\ndef remove_words(inputlist):\n slist = []\n for s in inputlist:\n if '设备' in s:\n pass\n else:\n slist.append(s)\n# print(slist)\n return slist\n\n\n# 将字典中同一项里的逗号连接换乘冒号连接\ndef remove_comma(inputlist):\n slist = []\n for s in inputlist:\n if ',' in s:\n s = re.sub(', ', '', s, 1000)\n slist.append(s)\n slist2 = []\n for s in slist:\n s = re.sub('\\\"\\\"', '\\\":\\\"', s, 1000)\n slist2.append(s)\n# print(slist2)\n return slist2\n\n\n# 去除多余的双引号\ndef remove_quota(inputlist):\n slist = []\n for s in inputlist:\n if '\"' in s:\n s = re.sub('\\\"', '', s, 1000)\n slist.append(s)\n# print(slist)\n return slist\n\n\n# 得到经典干净的字典\ndef turn_into_dic(inputlist):\n sdic = {}\n for s in inputlist:\n s1 = []\n s1 = s.split(':')\n sdic[s1[0]] = s1[1]\n# print(sdic)\n return sdic\n\n\ndef dp(inputlist):\n a = remove_braces(inputlist)\n b = remove_words(a)\n c = remove_comma(b)\n d = remove_quota(c)\n e = turn_into_dic(d)\n return e\n\n\na = remove_braces(string1)\nb = remove_words(a)\nc = remove_comma(b)\nd = remove_quota(c)\ne = turn_into_dic(d)\n\n#print(e['Bluetooth Mouse M557'])\n\nprint(dp(string1))","repo_name":"gzj1000xp/py_study","sub_path":"dp1.py","file_name":"dp1.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"19189871856","text":"import argparse\n\nimport gym\nfrom gym_minigrid.wrappers import FullyObsWrapper\nimport numpy as np\nimport stable_baselines3 as sb3\nfrom tqdm import tqdm\nimport h5py\n\nimport sys\nsys.path.append('../../')\n\nfrom src.common.wrappers import MyFullWrapper, StepWrapper\n\ndef main(\n num_trajectories\n):\n \n f = h5py.File('toy_data.hdf5', 'w') # change this to 'a' to prevent overwrite?\n f.create_group('done')\n f.create_group('obs')\n f.create_group('action')\n f.create_group('reward')\n \n model_name = \"PPO_toy\"\n model = sb3.PPO.load(model_name)\n\n # set up environment\n env = gym.make(\"MiniGrid-SimpleCrossingS9N1-v0\")\n env = StepWrapper(env)\n env = FullyObsWrapper(env)\n env = MyFullWrapper(env)\n \n # running stats helpers\n ctr = 0\n first_moment = 0\n second_moment = 0\n\n # Collect trajectories\n obs_list = []\n action_list = []\n done_list = []\n reward_list = []\n for traj in tqdm(range(num_trajectories)):\n obs = env.reset()\n done = False\n done_candidates = [int(done)] \n obs_candidates = []\n action_candidates = []\n reward_candidates = []\n while not done:\n action, _states = model.predict(obs)\n obs_candidates.append(obs)\n obs, reward, done, info = env.step(action)\n action_candidates.append(action)\n reward_candidates.append(reward)\n done_candidates.append(int(done))\n\n action, _states = model.predict(obs)\n obs_candidates.append(obs)\n action_candidates.append(action) \n\n\n done_list.extend(done_candidates)\n obs_list.extend(obs_candidates)\n action_list.extend(action_candidates)\n reward_list.extend(reward_candidates)\n \n # update running stats\n ctr += len(obs_candidates) * 7 * 7\n first_moment += np.sum(np.array(obs_candidates))\n second_moment += np.sum(np.array(obs_candidates) ** 2)\n \n f['done'].create_dataset(f'traj_{traj}', data=np.array(done_candidates))\n f['reward'].create_dataset(f'traj_{traj}', data=np.array(reward_candidates))\n f['obs'].create_dataset(f'traj_{traj}', data=np.array(obs_candidates))\n f['action'].create_dataset(f'traj_{traj}', data=np.array(action_candidates))\n \n\n f['obs'].attrs.create('mean', first_moment / ctr)\n f['obs'].attrs.create('std', np.sqrt(second_moment / ctr - first_moment ** 2 / ctr ** 2))\n f.close()\n\n\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--num_trajectories', type=int, default=10000)\n args = parser.parse_args()\n main(**vars(args))","repo_name":"TomFrederik/master_thesis","sub_path":"experiments/dreamer/collect_toy_trajectories.py","file_name":"collect_toy_trajectories.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"24928892785","text":"import rospy\nfrom pub_sub.msg import Inputmsg, Outputmsg \nimport numpy as np\nimport math\n\npub = rospy.Publisher('manipulated_vector', Outputmsg, queue_size=10)\n\ndef callback(data):\n # rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", data.data)\n rospy.loginfo(\"received x: %s, y: %s, z: %s, alpha: %s, beta: %s, gamma: %s, d: %s \" % (data.x, data.y, data.z, data.alpha, data.beta, data.gamma, data.d))\n \n given_vector = np.array([data.x, data.y, data.z, 1])\n\n rotation_along_x_matrix = np.array([ \n [1, 0, 0, 0 ],\n [0, math.cos(data.alpha), -math.sin(data.alpha), 0],\n [0, math.sin(data.alpha), math.cos(data.alpha), 0],\n [0, 0, 0, 1] \n ])\n\n rotation_along_y_matrix = np.array([ \n [math.cos(data.beta), 0, math.sin(data.beta), 0],\n [0, 1, 0, 0 ],\n [-math.sin(data.beta), 0, math.cos(data.beta), 0],\n [0, 0, 0, 1] \n ])\n\n rotation_along_z_matrix = np.array([ \n [math.cos(data.gamma), -math.sin(data.gamma), 0, 0],\n [math.sin(data.gamma), math.cos(data.gamma), 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1 ]\n ])\n\n translation_matrix = np.array([\n [1, 0, 0, data.d],\n [0, 1, 0, data.d],\n [0, 0, 1, data.d],\n [0, 0, 0, 1]\n ])\n\n # retVector = np.dot(translation_matrix, np.dot(rotation_along_z_matrix, np.dot(rotation_along_y_matrix, np.dot(rotation_along_x_matrix, given_vector))))\n retVector = (((given_vector.dot(rotation_along_x_matrix)).dot(rotation_along_y_matrix)).dot(rotation_along_z_matrix)).dot(translation_matrix)\n \n msg = Outputmsg()\n msg.x = retVector[0]\n msg.y = retVector[1]\n msg.z = retVector[2]\n\n pub.publish(msg)\n\ndef subscriber():\n rospy.init_node('main_sub', anonymous=True)\n\n rospy.Subscriber(\"chatter\", Inputmsg, callback)\n\n rospy.spin()\n\nif __name__ == '__main__':\n subscriber()","repo_name":"mickyCyb/Robotics","sub_path":"src/pub_sub/src/scripts/sub.py","file_name":"sub.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"12243067803","text":"import argparse\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\n\ndef chunks(seq, n):\n \"\"\"Yield successive n-sized chunks from seq.\"\"\"\n for i in range(0, len(seq), n):\n yield seq[i:i + n]\n\n\ndef line_breaking(s: str, line_len: int, max_len: int = None, max_line_breaks: int = None):\n if line_len <= 0:\n raise ValueError(f\"'line_len' must be > 0 (was {line_len})\")\n if max_len is not None and max_len <= 0:\n raise ValueError(f\"'max_len' must be > 0 (was {max_len})\")\n if max_line_breaks is not None and max_line_breaks <= 0:\n raise ValueError(f\"'max_line_breaks' must be > 0 (was {max_line_breaks})\")\n \n words = s.split(\" \")\n split_words = []\n \n for word in words:\n if len(word) > line_len:\n splits = [c for c in chunks(word, line_len - 1)] # -1 because of the additional splitting dash character\n for i, split in enumerate(splits):\n if i == len(splits) - 1:\n split_words.append(split)\n else:\n split_words.append(split + \"-\")\n else:\n split_words.append(word)\n \n line = \"\"\n lines = []\n skipped_lines = False\n \n for word in split_words:\n if len(line) == 0:\n line += word\n elif len(line) + 1 + len(word) > line_len: # +1 because of the separating space character\n if max_line_breaks is None or len(lines) < max_line_breaks:\n lines.append(line)\n line = word\n else:\n skipped_lines = True\n break\n else:\n line += \" \" + word\n lines.append(line)\n \n skip_indicator = \"...\"\n if skipped_lines:\n # this means we left the loop early and skipped the remaining words\n last_line = lines[-1]\n diff = len(last_line) + len(skip_indicator) - line_len\n if diff > 0:\n last_line = last_line[:-diff] + skip_indicator\n else:\n last_line += skip_indicator\n lines[-1] = last_line\n \n new_s = \"\\n\".join(lines)\n if max_len is not None and len(new_s) > max_len:\n # TODO: should leave loop early when max_len is reached instead of processing everything and then slicing\n return new_s[:max_len - len(skip_indicator)] + skip_indicator\n return new_s\n\n\ndef plot_grade_hist(grading_files: list[str], skz: str = None):\n # merge all files and keep last entry in case of duplicates = most recent entry if list is ordered\n dfs = [pd.read_csv(gf, sep=\";\", names=[\"id\", \"skz\", \"grade\", \"reason\"]) for gf in grading_files]\n df = pd.concat(dfs, ignore_index=True).drop_duplicates(subset=[\"id\", \"skz\"], keep=\"last\")\n if skz is not None:\n df = df[df[\"skz\"] == skz]\n if len(df) == 0:\n raise ValueError(f\"no entries found for specified SKZ = {skz}\")\n df[\"reason\"] = \": \" + df[\"reason\"] # only adds \": \" for non-NaN values\n df[\"reason\"].fillna(\"\", inplace=True)\n df[\"grade_detail\"] = (df[\"grade\"].astype(str) + df[\"reason\"]).apply(line_breaking, line_len=20, max_line_breaks=2)\n df.sort_values(\"grade_detail\", inplace=True)\n \n def _plot_grade_hist(ax: plt.Axes, x: str, rotate: float = None):\n grade_is_str = df[x].dtype == object\n ax_twin = ax.twinx()\n sns.histplot(data=df, x=x, discrete=True, ax=ax, color=\"bisque\")\n if not grade_is_str:\n ax.set_xticks(range(1, 6))\n counts = [len(group_df) for _, group_df in df.groupby(x)]\n # shift count labels by 1% of max (so there is some space between the bars and the labels)\n y_offset = 0.01 * max(counts)\n for i, (grade, group_df) in enumerate(df.groupby(x)):\n x_pos = i if grade_is_str else grade\n y_pos = len(group_df) + y_offset\n ax.text(x_pos, y_pos, f\"{len(group_df)} ({len(group_df) / len(df):.1%})\", ha=\"center\")\n max_percent = max([100 * c / len(df) for c in counts])\n # plot an invisible vertical line to automatically get the correct y-ticks\n x_pos = np.mean(ax.get_xticks())\n ax_twin.plot([x_pos, x_pos], [0, max_percent], alpha=0)\n ax_twin.set_ylim(0, ax_twin.get_ylim()[1])\n ax_twin.set_ylabel(\"Percent\")\n if rotate is not None:\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n ax.set_xlabel(\"\")\n \n # type hints to enable PyCharm suggestions and code completion\n fig: plt.Figure\n fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14, 6))\n _plot_grade_hist(ax1, \"grade\")\n _plot_grade_hist(ax2, \"grade_detail\", rotate=45)\n title = \"\\n\".join([os.path.split(os.path.dirname(gf))[1] + \"/\" + os.path.basename(gf) for gf in grading_files])\n title += f\"\\nGrades (count = {len(df)}; median = {df['grade'].median():.1f}; mean = {df['grade'].mean():.2f})\"\n if skz is not None:\n title += f\" for SKZ = {skz}\"\n fig.suptitle(title)\n fig.tight_layout()\n \n plt.show()\n plt.close(fig)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"grading_files\", nargs=\"+\", type=str,\n help=\"The output CSV files where the grades are stored. In case of duplicate entries, \"\n \"the file specified last takes precedence, i.e., the order of this list matters.\")\n parser.add_argument(\"--skz\", type=int,\n help=\"Restrict the output to only include students with this study identification (SKZ).\")\n args = parser.parse_args()\n plot_grade_hist(args.grading_files, args.skz)\n","repo_name":"Andi144/moodle-kusss-grading","sub_path":"grading/eval/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":5645,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"73740023482","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('job', '0001_initial'),\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Application',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('application_date', models.DateTimeField(auto_now_add=True)),\n ('applicant', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ('job_name', models.ForeignKey(to='job.Job')),\n ],\n ),\n ]\n","repo_name":"Kiiwi/Syssel","sub_path":"syssel/application/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"40761821031","text":"import json\nimport requests\nfrom doorsProject.payloadCollection import PayloadCollection\n\n\nclass DoorsData:\n def __init__(self):\n self.headers = PayloadCollection.headers\n self.url = PayloadCollection.canneraldRpcServerUrl\n self.doorsData = self.getDoorsPropertyData()\n\n def getAccessPointsWithTwoFactorAuthenticationId(self):\n accessPointIdList = []\n response = requests.get(\n url=self.url,\n headers=self.headers,\n verify=True,\n data=PayloadCollection.accessPointPropertyData,\n )\n results = json.loads(response.text)[\"result\"]\n for result in results:\n for key, value in result.items():\n if {key: value} == {\"propertyId\": PayloadCollection.towFactorAuthenticationId}:\n for key, value in result.items():\n if {key: value} == {\"value\": True} or {key: value} == {\"value\": '1'}:\n baseId = result['baseId']\n accessPointIdList.append(baseId)\n return accessPointIdList\n\n def getDoorsPropertyData(self):\n accessPointIdList = self.getAccessPointsWithTwoFactorAuthenticationId()\n response = requests.get(\n url=self.url,\n headers=self.headers,\n verify=True,\n data=PayloadCollection.devices,\n )\n\n results = json.loads(response.text)[\"result\"]\n accessPointDevices = {}\n for result in results:\n for accessPointId in accessPointIdList:\n if result['accessPointId'] == accessPointId:\n list_of_dicts = [result]\n for item in list_of_dicts:\n access_point_id = item['accessPointId']\n device_type = item['deviceType']\n device_id = item['deviceid']\n if device_type == 103:\n accessPointDevices.setdefault(access_point_id, {}).setdefault('IO_Module', []).append(\n device_id)\n if device_type == 80:\n accessPointDevices.setdefault(access_point_id, {}).setdefault('IO_Extender', []).append(\n device_id)\n elif device_type == 101 or device_type == 102:\n accessPointDevices.setdefault(access_point_id, {}).setdefault('E_Reader', []).append(\n device_id)\n\n return accessPointDevices\n\n\n","repo_name":"Ramzi-dr/canneraldBackupServer","sub_path":"doorsProject/doorsData.py","file_name":"doorsData.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"69872255483","text":"class Solution:\n def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:\n n = len(edges)\n dj = [i for i in range(n+1)]\n \n def find(u):\n if u != dj[u]:\n dj[u] = find(dj[u])\n return dj[u]\n \n def union(u,v):\n tem1 = find(u)\n tem2 = find(v)\n if tem1 == tem2: # u, v in set already\n return 0\n else:\n dj[tem1] = tem2\n return 1\n \n for item in edges:\n if(union(item[0],item[1]) == 0):\n return item\n ","repo_name":"IrwinLai/LeetCode","sub_path":"684. Redundant Connection.py","file_name":"684. Redundant Connection.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"38045332608","text":"import networkx as nx\nimport os, os.path, sys\nimport matplotlib.pyplot as plt\nfrom networkx.utils import open_file\nfrom collections import defaultdict\nimport random\nfrom numpy.random import choice\nimport numpy as np\n\nfrom definitions import colors, files\n\n@open_file(0, mode='rb')\ndef read_pajek_clu(path, encoding='UTF-8'):\n lines = (line.decode(encoding) for line in path)\n return parse_pajek_clu(lines)\n\n\ndef parse_pajek_clu(lines):\n communities = None\n if isinstance(lines, str):\n lines = iter(lines.split('\\n'))\n lines = iter([line.rstrip('\\n') for line in lines])\n\n while lines:\n try:\n l = next(lines)\n except: # EOF\n break\n if l.lower().startswith(\"*vertices\"):\n l, nnodes = l.split()\n communities = defaultdict(list)\n for vertice in range(1, int(nnodes) + 1):\n l = next(lines)\n community = int(l)\n communities.setdefault(community, []).append(vertice)\n else:\n break\n\n return [v for k, v in dict(communities).items()]\n\n\nif __name__ == \"__main__\":\n\n for f in files:\n g = nx.read_pajek(os.getcwd() + '\\\\' + f.get('folder') + '\\\\' + f.get('net'))\n aux = dict(g.nodes(data='id'))\n for k, v in aux.iteritems():\n aux[k] = int(v)\n g = nx.relabel_nodes(g, aux)\n if f.get('coords'):\n list_x = nx.get_node_attributes(g, 'x')\n list_y = nx.get_node_attributes(g, 'y')\n pos = {}\n for k, v in dict.iteritems(list_x):\n pos[k] = np.array([v, list_y[k]])\n else:\n pos = nx.spring_layout(g)\n print(pos)\n for c in f.get('clu'):\n clu = read_pajek_clu(os.getcwd() + '\\\\' + f.get('folder') + '\\\\' + c)\n fig, axe = plt.subplots(figsize=(12, 7))\n axe.set_title(f.get('net') + ' - ' + c, loc='right')\n nx.draw(g, pos, edge_color='k', with_labels=True, font_weight='light',\n node_size=280, width=0.7, font_size=8)\n for community in clu:\n nx.draw_networkx_nodes(g, pos, nodelist=community, node_color=colors[clu.index(community)])\n plt.show()\n for c in range(1, 4):\n clu_filename = f.get('net')[:-4] + '.clu'\n clu = read_pajek_clu(os.getcwd() + '\\\\type' + str(c) + '\\\\' + clu_filename)\n fig, axe = plt.subplots(figsize=(12, 7))\n axe.set_title(f.get('net') + ' - ' + clu_filename[:-4] + '-type' + str(c) + '.clu', loc='right')\n nx.draw(g, pos, edge_color='k', with_labels=True, font_weight='light',\n node_size=280, width=0.7, font_size=8)\n for community in clu:\n nx.draw_networkx_nodes(g, pos, nodelist=community, node_color=colors[clu.index(community)])\n plt.show()\n","repo_name":"kikemolina3/ComplexNetworksScripts","sub_path":"exercise3/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"30500565866","text":"# https://leetcode.com/problems/number-of-islands/\nclass Solution:\n def numIslands(self, grid: [[str]]) -> int:\n def remove(i, j):\n if 0 <= i < len(grid) and 0 <= j < len(grid[i]) and grid[i][j] == '1':\n grid[i][j] = '0'\n\n remove(i + 1, j)\n remove(i, j + 1)\n remove(i - 1, j)\n remove(i, j - 1)\n\n counter = 0\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] == '1':\n remove(i, j)\n counter += 1\n return counter\n","repo_name":"alexeykostyukov/LeetCode","sub_path":"Number of Islands/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"32132142327","text":"from PIL import Image,ImageFilter\nimport numpy as np\nimport os,time,cv2\nimport functions as f\nimport math\n\ndef inlist(a,gap,lista):\n\taux = np.isclose(a,lista,atol=gap)\n\tfor i in aux:\n\t\tif i.all()==True:\n\t\t\treturn True\n\t\telse:\n\t\t\tcontinue\n\treturn False\n\ndef targets(path,img_name,result_path,scene):\n\tlayout = []\n\tcolor_file = open('layout_colors_{}.txt'.format(scene),'r')\n\tc_list = color_file.read().split('\\n')\n\tfor i in range(len(c_list)-1):\n\t\tr,g,b = c_list[i].split(' ')\n\t\tcol = [int(b),int(g),int(r)]\n\t\tlayout.append(tuple(col))\n\tlayout = np.array(layout,np.uint8)\n\timg = cv2.imread('{}{}.png'.format(path,img_name))\n\th,w,c = img.shape\n\tc_img = img.reshape(1,w*h,3)\n\t#EDGES\n\tfor i in range(w*h):\n\t\tcol = c_img[0,i]\n\t\tif not inlist(col,3,layout):\n\t\t\tc_img[0,i] = c_img[0,i-1023]\n\tmask = c_img.reshape(h,w,c)\n\tedges = cv2.Canny(mask,100,200)\n\t#CORNERS\t\t\t\t\n\tcorners = np.full_like(edges,0)\n\tfor i in range(h-3):\n\t\tfor j in range(w-3):\n\t\t\twindow = mask[i:i+3,j:j+3]\n\t\t\tif window.size<25:\n\t\t\t\tprint(window,i,j)\n\t\t\tcol = np.unique(window.reshape(1,9,3),axis=1)\n\t\t\tcount = col.shape[1]\n\t\t\tif count == 3:\n\t\t\t\tcorners[i:i+2,j:j+2] = 255\n\tcolor_file.close()\n\tedge_name = '{}EM_gt/{}_EM.jpg'.format(result_path,img_name)\n\tcorner_name = '{}CM_gt/{}_CM.jpg'.format(result_path,img_name)\n\tcv2.imwrite(edge_name,edges)\n\tcv2.imwrite(corner_name,corners)\n\tgaussian_blur(result_path,edge_name,corner_name)\n\t\ndef gaussian_blur(result_path,edge,corner):\n\tedges = Image.open(edge)\n\tpx_edges = edges.load()\n\tcorners = Image.open(corner)\n\tpx_corners = corners.load()\n\tim_w,im_h = edges.size\n\tsigma = max(im_w,im_h)\n\tblur_edge = edges.filter(ImageFilter.GaussianBlur(radius = sigma*0.0065))\n\tblur_corner = corners.filter(ImageFilter.GaussianBlur(radius = sigma*0.009))\n\tmin_e,max_e = blur_edge.getextrema()\n\tmin_c,max_c = blur_corner.getextrema()\n\tif max_e == 0:\n\t\tmax_e = 1\n\t\tprint('Max_e fail')\n\tif max_c == 0:\n\t\tmax_c = 1\n\t\tprint('Max_c fail')\n\tfor i in range(im_w-1):\n\t\tfor j in range(im_h-1):\n\t\t\tc_edge = blur_edge.getpixel((i,j))\n\t\t\tc_corner = blur_corner.getpixel((i,j))\n\t\t\tpx_edges[i,j] = int((c_edge*255)/float(max_e))\n\t\t\tpx_corners[i,j] = int((c_corner*255)/float(max_c))\n\tedges.save(edge)\n\tcorners.save(corner)\n\ndef png2jpg(directory,result):\n\tlista = os.listdir(directory)\n\tif not os.path.exists(result):\n\t\t\tos.makedirs(result)\n\tfor image in lista:\n\t\timg = Image.open(directory+image)\n\t\timg.convert(\"RGB\").save(result+image[0:-4]+'.jpg')\n\t\t\t\ndef setCFLfolder(path):\n\tif not os.path.exists(\"{}EM_gt/\".format(path)):\n\t\tos.makedirs(\"{}EM_gt/\".format(path))\n\tif not os.path.exists(\"{}CM_gt/\".format(path)):\n\t\tos.makedirs(\"{}CM_gt/\".format(path))\n\tif not os.path.exists(\"{}VP_gt/\".format(path)):\n\t\tos.makedirs(\"{}VP_gt/\".format(path))\n\tif not os.path.exists(\"{}HL_gt/\".format(path)):\n\t\tos.makedirs(\"{}HL_gt/\".format(path))\n\tif not os.path.exists(\"{}RGB/\".format(path)):\n\t\tos.makedirs(\"{}RGB/\".format(path))\n\n\ndef get_images(scene):\n\t#-----------------------------------------------------------------------------------------------\n\tfinal_w = 1024\t\t\t\t#Image resolution: width\n\tfinal_h = 512\t\t\t\t#Image resolution: height\n\tinit_loc = 1\t\n\tnum_locs = input('Number of locations in the scene: ')\t#Number of locations to evaluate\n\tloc_list = [i + init_loc for i in range(num_locs)] \t#List of locations\n\trot = raw_input('Rotation from file?(yes/no): ').capitalize()\n\tif rot == 'Yes':\n\t\trot1 = ('cam_rot.txt')\n\t\trot2 = ('R')\n\telse:\n\t\trot1 = (raw_input('Set camera view direction axis (x/y/z): ').lower())\n\t\trot2 = (raw_input('Set direction sign (pos/neg): ').lower())\n\t#-----------------------------------------------------------------------------------------------\n\tif not cv2.useOptimized():\n\t\tprint('Turn on the Optimizer')\n\t\tcv2.setUseOptimized(True)\n\t#Geometric parameters\n\tNor,Rot = f.load_geom()\n\t#Camera images - cubemap\n\tfor loc in loc_list:\n\t\tprint('Composing ground truth for CFL in location {} of {}'.format(loc,loc_list[-1]))\n\t\tresult_path = \"CFL/test/\"\n\t\tsetCFLfolder(result_path)\n\t\tfinal = np.zeros((final_h,final_w,3), np.uint8)\n\t\tr,g,b = np.empty(final_h*final_w),np.empty(final_h*final_w),np.empty(final_h*final_w)\n\t\timage_path = \"CFL/layout/\"\n\t\timage_name = \"{}-equirec-{}-{}\".format(scene,rot1[0]+rot2,loc)\n\t\timagenx_pos = cv2.imread(\"CFL/layout/loc{}/img{}1.png\".format(loc,loc))\n\t\timagenx_neg = cv2.imread(\"CFL/layout/loc{}/img{}2.png\".format(loc,loc))\n\t\timageny_pos = cv2.imread(\"CFL/layout/loc{}/img{}3.png\".format(loc,loc))\n\t\timageny_neg = cv2.imread(\"CFL/layout/loc{}/img{}4.png\".format(loc,loc))\n\t\timagenz_pos = cv2.imread(\"CFL/layout/loc{}/img{}5.png\".format(loc,loc))\n\t\timagenz_neg = cv2.imread(\"CFL/layout/loc{}/img{}6.png\".format(loc,loc))\n\t\timagenes=[imagenx_pos,imagenx_neg,imageny_pos,imageny_neg,imagenz_pos,imagenz_neg]\n\t\tim_h,im_w,ch = imagenx_pos.shape\n\t\tim_w -=1\n\t\tim_h -=1\n\t\tv_north = np.array([0,0,1]).reshape(1,3)\n\t\tv_south = np.array([0,0,-1]).reshape(1,3)\n\t\t#Camera parameters\n\t\tR_cam = np.matrix('0 0 -1; 0 -1 0;1 0 0')\n\t\tR_view = f.camera_rotation(rot1,rot2,loc) #Rotation matrix of the viewer\n\t\tR_world = R_view*R_cam\t\t\n\t\tFOV = math.pi/2.0\n\t\tfx = (im_w/2.0)/math.tan(FOV/2.0)\n\t\tfy = (im_h/2.0)/math.tan(FOV/2.0)\n\t\tK = np.matrix('{} 0 {}; 0 {} {}; 0 0 1'.format(fx,im_w/2,fy,im_h/2))\n\t\tini = 0\n\t\t#Pixel mapping\n\t\ttheta = np.array([(2*i/float(final_w)-1.0)*math.pi for i in range(final_w)])\n\t\tI_theta = np.full_like(theta,1)\n\t\tphi = np.array([(1/2.0 - j/float(final_h))*math.pi for j in range(final_h)])\n\t\tI_phi = np.full_like(phi,1)\n\t\tct,st,cp,sp = np.cos(theta),np.sin(theta),np.cos(phi),np.sin(phi)\n\t\tvec = np.array([np.outer(cp,ct),np.outer(cp,st),np.outer(sp,I_theta)]).reshape(3,final_w*final_h)\n\t\tv_abs = np.dot(R_world,vec)\n\t\td_north = np.arccos(v_north*v_abs)\n\t\td_south = np.arccos(v_south*v_abs)\n\t\td_horizon = np.arcsin(v_north*v_abs)\n\t\tsigma_pole, sigma_horizon = 3*math.pi/180,3*math.pi/180\n\t\texp_north = np.exp(-np.square(d_north)/np.square(2*sigma_pole))/(sigma_pole*np.sqrt(2*math.pi))\n\t\texp_south = np.exp(-np.square(d_south)/np.square(2*sigma_pole))/(sigma_pole*np.sqrt(2*math.pi))\n\t\texp_horizon = np.exp(-np.square(d_horizon)/np.square(2*sigma_horizon))/(sigma_horizon*np.sqrt(2*math.pi))\n\t\tpoles = exp_north + exp_south\n\t\tmax_pole = np.max(poles)\n\t\tmax_horizon = np.max(exp_horizon)\n\t\timg_index = f.get_index(v_abs)\n\t\tfor i in range(img_index.size):\n\t\t\tn,imagen,R = Nor[img_index[0,i]],imagenes[img_index[0,i]],Rot[img_index[0,i]]\n\t\t\tp_x, p_y = f.get_pixel(v_abs[:,i], R, K)\n\t\t\tcolor = imagen[p_y, p_x]\n\t\t\tr[i],g[i],b[i] = color[0:3]\n\t\tfinal = cv2.merge((r,g,b)).reshape(final_h,final_w,3)\n\t\tcv2.imwrite('{}.png'.format(image_path+image_name),final)\n\t\tvpoint = poles*255/max_pole\n\t\thorizon = exp_horizon*255/max_horizon\n\t\tvp_gt = vpoint.reshape(final_h,final_w)\n\t\thl_gt = horizon.reshape(final_h,final_w)\n\t\tcv2.imwrite('{}_VP.jpg'.format('CFL/test/VP_gt/'+image_name),vp_gt)\n\t\tcv2.imwrite('{}_HL.jpg'.format('CFL/test/HL_gt/'+image_name),hl_gt)\n\t\ttargets(image_path,image_name,result_path,scene)\n\t\t\t\n","repo_name":"Sbrunoberenguel/OmniSCV","sub_path":"OmniSCV-27/Pack/programs/CFL_data.py","file_name":"CFL_data.py","file_ext":"py","file_size_in_byte":6943,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"41"} +{"seq_id":"16611829733","text":"\"\"\"Scoreboard configs.\"\"\"\nfrom turtle import Turtle\nLEVEL_FONT = (\"Courier\", 12, \"normal\")\nGAME_OVER_FONT = (\"Courier\", 40, \"bold\")\n\n\nclass Scoreboard(Turtle):\n \"\"\"Scoreboard to keep track of the levels and game messages.\"\"\"\n def __init__(self):\n super().__init__()\n self.hideturtle()\n self.penup()\n self.level = 1\n\n def inform_level(self,) -> None:\n \"\"\"Displays the current level on the top-right of the screen.\"\"\"\n self.clear()\n self.goto(-290, 280)\n msg = f\"Level {self.level}\"\n self.write(arg=msg, move=False, align=\"left\", font=LEVEL_FONT)\n\n def game_over_msg(self) -> None:\n \"\"\"Displays a GAME OVER message on the center of the screen.\"\"\"\n self.home()\n self.color(\"red\")\n self.write(\"GAME OVER\", align=\"center\", font=GAME_OVER_FONT)\n","repo_name":"tompy017/100_days_of_code","sub_path":"challenges/TurtleCrossingGame/scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"72971605243","text":"# _*_ coding:utf-8 _*_\n__author__ = 'T'\n\n\nimport numpy as np\nimport pandas as pd\nfrom twi.cluster.apriori import Apriori\n\n\ndef load_data():\n data_path = 'data/yiyu.csv'\n d_pat = {}\n with open(data_path, encoding='utf8', mode= 'r', errors='ignore') as f:\n for line in f.readlines():\n fields = line.replace('\\\\,',' ').replace('\\n','').split(',')\n if d_pat.get(fields[3]) is None:\n d_pat[fields[3]] = set({})\n d_pat[fields[3]].add(fields[4])\n\n l_pat_med = []\n for key, val in d_pat.items():\n l_pat_med.append(val)\n return l_pat_med\n\n\ndef analysis():\n data = load_data()\n ap = Apriori(support_min=0.05)\n ap.analyze(data)\n ap.showrules()\n\n\ndef load_data2(hsp):\n data_path = 'data/yiyu.csv'\n d_pat = {}\n df_med = pd.read_csv(data_path)\n df_med.columns = ['hspcode', 'icd10', 'icdname', 'id', 'med']\n tmp = df_med[df_med.hspcode==hsp][['id','med']]\n for idx in tmp.index:\n id = tmp.loc[idx][0]\n med = tmp.loc[idx][1]\n if d_pat.get(id) is None:\n d_pat[id] = set({})\n d_pat[id].add(med)\n l_pat_med = []\n for key, val in d_pat.items():\n l_pat_med.append(val)\n return l_pat_med\n\n\ndef analysis2():\n ap = Apriori(support_min=0.05)\n print('**' * 20, '回龙观', '**' * 20)\n data_54X = load_data2('40068654XA')\n ap.analyze(data_54X)\n ap.showrules()\n print('**' * 20, '安定', '**' * 20)\n data_465 = load_data2('400688465A')\n ap = Apriori(support_min=0.05)\n ap.analyze(data_465)\n ap.showrules()\n\nif __name__ == \"__main__\":\n analysis2()\n","repo_name":"WangXiaoguang0712/PythonWB","sub_path":"work/yiyu.py","file_name":"yiyu.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"25694047065","text":"import inspect\nimport sympy\nimport json\nfrom sympy import Symbol\nfrom sympy.parsing.latex import parse_latex\nfrom sympy.core.basic import preorder_traversal\nfrom sympy import Integral\nfrom sympy.core.function import Derivative, UndefinedFunction\nfrom sympy.parsing.sympy_parser import parse_expr\nfrom sympy.simplify import simplify\n\nfrom mathlearning.utils.list.list_size_transformer import ListSizeTransformer\nfrom mathlearning.utils.list.commutative_group_transformer import CommutativeGroupTransformer\nfrom mathlearning.utils.list.non_commutative_group_transformer import NonCommutativeGroupTransformer\nfrom mathlearning.utils.latex_utils import clean_latex\nfrom typing import Union, List\nfrom sympy import integrate\n\nfrom mathlearning.utils.sympy_utils import SympyUtils\n\nsympy_classes = tuple(x[1] for x in inspect.getmembers(sympy, inspect.isclass))\n\ndef is_sympy_exp(formula):\n return isinstance(formula, sympy_classes)\n\ndef make_sympy_expr(formula, is_latex):\n if isinstance(formula, str) and is_latex:\n clean_formula = clean_latex(formula)\n sympy_expr = parse_latex(clean_formula)\n sympy_expr = sympy_expr.subs(simplify(parse_expr(\"e\")), parse_expr(\"exp(1)\"))\n sympy_expr = sympy_expr.xreplace({parse_latex(\"\\\\ln(x)\"): parse_expr('log(x,E)')})\n elif is_sympy_exp(formula):\n sympy_expr = formula\n elif isinstance(formula, str):\n sympy_expr = parse_expr(formula)\n else:\n raise (Exception(\"error while trying to create an Expression, unsuported formula type\" + str(formula)))\n return sympy_expr\n\ndef make_complete_sympy_expr(sympy_expr, variables):\n complete_sympy_expr = sympy_expr\n\n # for variable in variables:\n # complete_sympy_expr = complete_sympy_expr.subs(parse_expr(variable.tag), variable.expression.sympy_expr)\n\n return complete_sympy_expr\n\n\nclass Expression:\n\n def __init__(self, formula: Union['Expression', str], variables: List['ExpressionVariable'] = [], is_latex=True):\n self.variables = variables\n self.commutative_group_transformer = CommutativeGroupTransformer()\n self.non_commutative_group_transformer = NonCommutativeGroupTransformer()\n self.commutative_list_size_transformer = ListSizeTransformer(CommutativeGroupTransformer())\n self.non_commutative_list_size_transformer = ListSizeTransformer(NonCommutativeGroupTransformer())\n self.sympy_expr = make_sympy_expr(formula, is_latex)\n self.sympy_expr = make_complete_sympy_expr(self.sympy_expr, variables)\n\n def replace_variables(self) -> 'Expression':\n complete_sympy_expr = self.get_copy().sympy_expr\n for variable in self.variables:\n complete_sympy_expr = complete_sympy_expr.subs(parse_expr(variable.tag), variable.expression.sympy_expr)\n return Expression(complete_sympy_expr)\n\n def is_leaf(self) -> bool:\n return len(self.sympy_expr.args) == 0\n\n def is_commutative(self) -> bool:\n return self.sympy_expr.is_commutative\n\n def is_constant(self) -> bool:\n free_symbols = self.sympy_expr.expr_free_symbols\n for symbol in free_symbols:\n if isinstance(symbol, Symbol):\n return False\n return True\n\n def get_copy(self) -> 'Expression':\n return Expression(parse_expr(str(self.sympy_expr)),self.variables)\n\n # Search and derivate expressions\n def solve_derivatives(self) -> 'Expression':\n derivatives_solved = self.get_copy()\n for exp in preorder_traversal(self.sympy_expr):\n # TODO\n exp = Expression(exp)\n if exp.is_derivative():\n derivative_applied = exp.apply_derivative()\n derivatives_solved.replace(exp, derivative_applied)\n return derivatives_solved\n\n def replace_derivatives_for_json(self):\n replacements = []\n for exp in preorder_traversal(self.sympy_expr):\n # TODO\n expression = Expression(exp)\n if expression.is_derivative():\n content = Expression(exp.args[0]).to_latex()\n variable = Expression(exp.args[1][0]).to_latex()\n\n replacement = '\\\\frac{d(%s)}{d%s}' % (content, variable)\n replacements.append({\"derivative\": expression.to_latex(), \"replacement\": replacement})\n return replacements\n\n\n # possibilities of solving just 1 derivative\n def derivatives_solving_possibilities(self) -> List['Expression']:\n\n derivatives = []\n for exp in preorder_traversal(self.sympy_expr):\n exp = Expression(exp)\n if exp.is_derivative():\n derivatives.append(exp)\n\n possibilities = []\n for derivative in derivatives:\n derivative_solved = self.get_copy()\n derivative_solved.replace(derivative, derivative.apply_derivative())\n possibilities.append(derivative_solved)\n\n return possibilities\n\n # possibilities of solving just 1 integral\n def integrals_solving_possibilities(self) -> List['Expression']:\n\n integrals = []\n for exp in preorder_traversal(self.sympy_expr):\n exp = Expression(exp)\n if exp.is_integral():\n integrals.append(exp)\n\n possibilities = []\n for integral in integrals:\n applied_integral = integral.apply_integral()\n\n # without integral constant\n integral_solved = self.get_copy()\n integral_solved.replace(integral, applied_integral)\n possibilities.append(integral_solved)\n\n # with integral constant\n integral_solved = self.get_copy()\n integral_solved.replace(integral, applied_integral)\n c = sympy.symbols('c')\n expression_with_constant = Expression(sympy.Add(integral_solved.sympy_expr, c))\n possibilities.append(expression_with_constant)\n\n return possibilities\n\n def is_integral(self):\n return isinstance(self.sympy_expr, sympy.Integral)\n\n def is_derivative(self) -> bool:\n return isinstance(self.sympy_expr, Derivative)\n\n def is_integral(self) -> bool:\n return isinstance(self.sympy_expr, Integral)\n\n def apply_derivative(self) -> 'Expression':\n deriv = Derivative(self.sympy_expr.args[0], self.sympy_expr.args[1])\n return Expression(deriv.doit())\n\n def apply_integral(self) -> 'Expression':\n integrand = Expression(self.sympy_expr.args[0])\n if self.contains_derivative() or integrand.contains_integral():\n return self\n return Expression(integrate(self.sympy_expr.args[0], self.sympy_expr.args[1]))\n\n def simplify(self) -> 'Expression':\n copy = self.get_copy()\n return Expression(simplify(copy.sympy_expr))\n\n def is_user_defined_func(self) -> bool:\n return isinstance(self.sympy_expr.func, UndefinedFunction) and not self.is_derivative()\n\n def to_string(self) -> str:\n return json.dumps({\n 'expression': str(self.sympy_expr),\n 'variables': list(map(lambda variable: variable.to_json(), self.variables))\n })\n\n def to_json(self):\n return {\n 'expression': str(self.sympy_expr),\n 'variables': list(map(lambda variable: variable.to_json(), self.variables))\n }\n\n def to_expression_string(self):\n return str(self.sympy_expr)\n\n def to_latex(self) -> str:\n return sympy.latex(self.sympy_expr)\n\n\n def to_latex_with_derivatives(self) -> str:\n replacements = self.replace_derivatives_for_json()\n latex_exp = sympy.latex(self.sympy_expr)\n for replacement in replacements:\n latex_exp = latex_exp.replace(replacement['derivative'], replacement['replacement'])\n return latex_exp\n\n def is_equivalent_to(self, expression: 'Expression') -> bool:\n if str(simplify(self.sympy_expr)) == str(simplify(expression.sympy_expr)) or \\\n self == expression:\n return True\n self_simplifications = self.get_simplifications()\n expression_simplifications = expression.get_simplifications()\n\n # simplify both expressions and compare them\n # TODO use a set to reduce time complexity\n for self_simplification in self_simplifications:\n for expression_simplification in expression_simplifications:\n simplifications_match = str(self_simplification.sympy_expr) == str(expression_simplification.sympy_expr)\n if simplifications_match:\n return True\n\n return False\n\n def contains_user_defined_funct(self) -> bool:\n if self.is_user_defined_func():\n return True\n if len(self.get_children()) == 0:\n return False\n result = False\n for child in self.get_children():\n result = result or child.contains_user_defined_funct()\n return result\n\n def compare_func(self, expression: 'Expression') -> bool:\n return self.sympy_expr.func == expression.sympy_expr.func\n\n def has_all_free_symbols(self, free_symbols) -> bool:\n for free_symbol in free_symbols:\n if free_symbol.func == Symbol and not self.sympy_expr.has(free_symbol) and str(free_symbol) != \"e\":\n return False\n return True\n\n def free_symbols_match(self, expression: 'Expression') -> bool:\n result = self.has_all_free_symbols(expression.sympy_expr.expr_free_symbols)\n result &= expression.has_all_free_symbols(self.sympy_expr.expr_free_symbols)\n return result\n\n def children_amount(self) -> int:\n # TODO: handle this cases derivatives\n if self.is_derivative():\n return 1\n return len(self.get_children())\n\n def get_children(self) -> List['Expression']:\n children = []\n if self.is_derivative():\n children.append(Expression(self.sympy_expr.args[0]))\n return children\n for child in self.sympy_expr.args:\n expression_child = Expression(child)\n if self.is_commutative() and self.compare_func(expression_child):\n children.extend(expression_child.get_children())\n else:\n children.append(expression_child)\n return children\n\n # todo remove side effect\n def replace(self, to_replace: 'Expression', replacement: 'Expression'):\n to_replace_sympy = to_replace.sympy_expr\n replacement_sympy = simplify(replacement.sympy_expr)\n new_sympy_expr = self.sympy_expr.subs({to_replace_sympy: replacement_sympy})\n\n if (new_sympy_expr == self.sympy_expr and self.contains_derivative()):\n # TODO: workaround because sympy issue https://github.com/sympy/sympy/issues/5670\n new_sympy_expr = new_sympy_expr.xreplace({to_replace_sympy: replacement_sympy})\n\n if new_sympy_expr == self.sympy_expr:\n to_replace_sympy = simplify(to_replace.sympy_expr)\n self.sympy_expr = self.sympy_expr.subs({to_replace_sympy: replacement_sympy})\n else:\n self.sympy_expr = new_sympy_expr\n\n # Refactor\n def get_child_with_size_possibilities(self, size) -> List['Expression']:\n if self.is_commutative():\n transformer = self.commutative_group_transformer\n else:\n transformer = self.non_commutative_list_size_transformer\n possibilities = []\n combinations = transformer.combinations_of_n_elements(self.get_children(), size)\n\n for combination in combinations:\n sympy_elements = []\n for element in combination.elements:\n sympy_elements.append(element.sympy_expr)\n children_sympy = self.sympy_expr.func(*sympy_elements)\n possibilities.append(Expression(children_sympy))\n return possibilities\n\n def get_children_with_size(self, size) -> List[List['Expression']]:\n # TODO refactor\n if self.is_commutative():\n transformer = self.commutative_list_size_transformer\n else:\n transformer = self.non_commutative_list_size_transformer\n transformations = transformer.transform(list(self.sympy_expr.args), size)\n results = []\n for transformation in transformations:\n children_transformation = []\n for item in transformation:\n if len(item) == 1:\n children_transformation.append(Expression(item[0]))\n elif len(item) > 1:\n children_sympy = self.sympy_expr.func(*item)\n children_transformation.append(Expression(children_sympy))\n results.append(children_transformation)\n return results\n\n def get_simplifications(self) -> List['Expression']:\n simplifications = []\n posible_simplifications = [\n Expression(sympy.expand(self.sympy_expr)),\n Expression(sympy.cancel(self.sympy_expr)),\n Expression(sympy.simplify(self.sympy_expr)),\n Expression(sympy.factor(self.sympy_expr))\n ]\n\n original_integral_amount = self.amount_of_integrals()\n\n # TODO check how to do this (Integral(x,x) + Integral(cos(x), x) is simplified to Integral(x+cos(x))\n # This workaround solves that problem\n for posible_simplification in posible_simplifications:\n if posible_simplification.amount_of_integrals() == original_integral_amount:\n simplifications.append(posible_simplification)\n\n return simplifications\n\n def __eq__(self, other):\n \"\"\"Overrides the default implementation\"\"\"\n if isinstance(other, Expression):\n are_formulas_equals = self.to_string() == other.to_string()\n\n if len(self.variables) != len(other.variables):\n return False\n\n if len(self.variables) == 0 and len(other.variables) == 0: # TODO Lucas: add tests for it\n return are_formulas_equals\n\n self_variables_set = set((x.tag, x.expression) for x in self.variables)\n different_values = [x for x in other.variables if (x.tag, x.expression) not in self_variables_set]\n are_variables_equal = len(different_values) == 0\n\n return are_formulas_equals and are_variables_equal\n\n return False\n\n def __hash__(self):\n return hash(self.sympy_expr)\n\n def __str__(self):\n return str(self.sympy_expr)\n\n # TODO: refactor\n def get_operators_by_level(self):\n operators = {}\n to_check = [{\n 'expression': self,\n 'level': 0\n }]\n while len(to_check) > 0:\n current = to_check.pop()\n current_level = current['level']\n current_expression = current['expression']\n operator = current['expression'].sympy_expr.func\n\n if not isinstance(operator, UndefinedFunction) and not current_expression.is_constant() \\\n and not operator.is_symbol:\n\n if current_level not in operators:\n operators[current_level] = []\n\n if SympyUtils.is_division(current_expression.sympy_expr):\n operators[current_level].append('Division')\n\n operators[current_level].append(operator)\n to_check += list(\n map(\n lambda expression: {'expression': expression, 'level': current_level + 1},\n current['expression'].get_children()\n )\n )\n\n return operators\n\n # TODO: refactor\n # Compares if all the operators or a sub_expression are contained and in the right level order\n def operators_and_levels_match(self, sub_expression: 'Expression'):\n self_operators = self.get_operators_by_level()\n sub_expression_operators = sub_expression.get_operators_by_level()\n\n if len(sub_expression_operators) == 0:\n return True\n\n # expression x + x**(2+x) -- 0: [Add] ; 1: [Pow] ; 2: [Add]\n # sub_expression x**(2+x) -- 0: [Pow] ; 1: [Add]\n # self_level is used to find the starting point where the first Pow of sub_expression is.\n # in this example the only possible values are 0 and 1 since if we select 2 as the starting level\n # we have to match the 1: [Add] sub_expression level with an non existent level.\n for self_level in range(0, len(self_operators) - len(sub_expression_operators) + 1):\n first_sub_expression_operator = sub_expression_operators[0][0]\n if first_sub_expression_operator in self_operators[self_level]:\n all_match = True\n # check if the rest of the levels match\n for self_level_to_check in range(self_level, self_level + len(sub_expression_operators)):\n sub_level_to_check = self_level_to_check - self_level\n sub_level_operators = sub_expression_operators[sub_level_to_check]\n for sub_level_operator in sub_level_operators:\n if sub_level_operator not in self_operators[self_level_to_check]:\n all_match = False\n if all_match:\n return True\n return False\n\n # TODO: refactor\n def get_subtrees_with_root_func_by_level(self, expression: 'Expression'):\n subtrees = []\n func = expression.sympy_expr.func\n to_check = [{\n 'expression': self,\n 'level': 0\n }]\n while len(to_check) > 0:\n current = to_check.pop()\n current_level = current['level']\n if current['expression'].sympy_expr.func == func:\n subtrees.append(current)\n to_check += list(\n map(\n lambda expression: {'expression': expression, 'level': current_level + 1},\n current['expression'].get_children()\n )\n )\n return subtrees\n\n # TODO: refactor\n def get_depth(self):\n if self is None:\n return 0\n\n to_check = [{\n 'expression': self,\n 'depth': 1\n }]\n\n max = 0\n while len(to_check) > 0:\n current = to_check.pop()\n if current['depth'] > max:\n max = current['depth']\n if not current['expression'].is_user_defined_func():\n to_check += list(\n map(\n lambda expression: {'expression': expression, 'depth': current['depth'] + 1},\n current['expression'].get_children()\n )\n )\n return max\n\n def can_group_children(self):\n if self.sympy_expr.func in [sympy.Add, sympy.Mul]:\n return True\n return False\n\n def contains_derivative(self):\n for exp in preorder_traversal(self.sympy_expr):\n expression = Expression(exp)\n if expression.is_derivative():\n return True\n return False\n\n def contains_integral(self):\n for exp in preorder_traversal(self.sympy_expr):\n expression = Expression(exp)\n if expression.is_integral():\n return True\n return False\n\n def amount_of_integrals(self):\n count = 0\n for exp in preorder_traversal(self.sympy_expr):\n expression = Expression(exp)\n if expression.is_integral():\n count += 1\n return count\n\n def compare_variables(self, variables):\n for self_variable in self.variables:\n contained = False\n for variable in variables:\n if self_variable == variable:\n contained = True\n if not contained:\n return False\n\n return True\n","repo_name":"math-learning/math-solver","sub_path":"mathlearning/model/expression.py","file_name":"expression.py","file_ext":"py","file_size_in_byte":19799,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"41751604022","text":"\"\"\"Module containing the Lattice class.\"\"\"\n\nimport os\nimport math\n\n__all__ = ['Lattice']\n\nclass Lattice:\n \"\"\"\n Lattice class that defines the lattice structure on which species can bind, diffuse and react.\n As in Zacros' original input files, there are four different ways of specifying a lattice structure.\n Below we describe these four ways with the corresponding parameters as well with examples of use.\n\n **Default Lattices:**\n\n * ``lattice_type`` -- Define the lattice to use. Possible options are:\n\n - ``Lattice.TRIANGULAR``: Specifies a lattice with coordination number 3. The unit cell is not the primitive cell. The obtained unit cell is a rectangular cell containing 4 sites.\n - ``Lattice.RECTANGULAR``: Specifies a lattice with coordination number 4. The unit cell contains 1 site. The unit cell is the primitive cell.\n - ``Lattice.HEXAGONAL``: Specifies a lattice with coordination number 6. The unit cell is not the primitive cell. The obtained unit cell is a rectangular cell containing 2 sites.\n\n * ``lattice_constant`` -- Defines the lattice constant (in angstrom).\n * ``repeat_cell`` -- The number of repetitions of the unit cell in the horizontal and vertical.\n\n Example:\n\n .. code:: python\n\n lattice = Lattice( lattice_type=Lattice.HEXAGONAL, lattice_constant=1.0, repeat_cell=[4,5] )\n\n .. image:: ../../images/lattice_default.png\n :align: center\n\n **Unit-Cell-Defined Periodic Lattices:**\n\n * ``cell_vectors`` -- Define the unit vectors. *e.g.* ``[[0.123, 0.000],[1.234,1.234]]``\n * ``repeat_cell`` -- The number of repetitions of the unit cell in the directions of unit vectors. *e.g.* ``(10,10)``\n * ``site_types`` -- The names of the different site types. *e.g.* ``[ \"cn2\", \"br42\", \"cn2\" ]``\n * ``site_coordinates`` -- Pairs of real numbers specifying the “fractional coordinates” of each site\n in the unit cell. *e.g.* ``[ (0.123,0.894), (0.456,0.123) ]``\n * ``neighboring_structure`` -- Defines a neighboring structure block. *e.g.*\n ``[ ((0,0),Lattice.NORTH), ((0,1),Lattice.NORTHEAST) ]``\n\n Example:\n\n .. code:: python\n\n lattice = Lattice( cell_vectors=[[2.77185866, 0.00000000],[1.38592933, 2.40050002]],\n repeat_cell=[2, 2],\n site_types=[\"b\", \"h\", \"b\", \"b\", \"f\", \"t\"],\n site_coordinates=[[0.00001, 0.49999],\n [0.33333, 0.33333],\n [0.49999, 0.00001],\n [0.49999, 0.49999],\n [0.66667, 0.66667],\n [0.99999, 0.00001]],\n neighboring_structure=[ [(0,1), Lattice.SELF],\n [(1,2), Lattice.SELF],\n [(1,3), Lattice.SELF],\n [(3,4), Lattice.SELF],\n [(4,2), Lattice.NORTH],\n [(4,0), Lattice.EAST],\n [(5,5), Lattice.NORTH],\n [(5,5), Lattice.EAST],\n [(5,4), Lattice.SELF],\n [(5,1), Lattice.SELF],\n [(5,1), Lattice.EAST],\n [(5,4), Lattice.SOUTHEAST],\n [(5,1), Lattice.SOUTHEAST],\n [(4,5), Lattice.NORTH],\n [(5,5), Lattice.SOUTHEAST] ] )\n\n .. image:: ../../images/lattice_unit_cell.png\n :align: center\n\n **Explicitly Defined Custom Lattices:**\n\n * ``site_types`` -- The names of the different site types. *e.g.* ``[ \"cn2\", \"br42\" ]``\n * ``site_coordinates`` -- Pairs of real numbers specifying the “fractional coordinates” of each site\n in the unit cell. *e.g.* ``[ (0.123,0.894), (0.456,0.123) ]``\n * ``nearest_neighbors`` -- Defines the neighboring structure. *e.g.* ``[ (2,6), (2,4,7,8) ]``\n * ``cell_vectors`` -- Define the unit vectors. Optional\n\n Example:\n\n .. code:: python\n\n lattice = Lattice( site_types=[\"cn2\", \"br42\", \"cn4\", \"br42\", \"cn2\", \"br42\",\n \"br44\", \"br44\", \"br42\", \"cn4\", \"br44\", \"cn4\",\n \"br42\", \"br42\", \"cn2\"],\n site_coordinates=[[0.0000e+0, 0.0000e+0],\n [1.4425e+0, 0.0000e+0],\n [2.8850e+0, 0.0000e+0],\n [4.3275e+0, 0.0000e+0],\n [5.7700e+0, 0.0000e+0],\n [7.2125e-1, 1.2492e+0],\n [2.1637e+0, 1.2492e+0],\n [3.6062e+0, 1.2492e+0],\n [5.0487e+0, 1.2492e+0],\n [1.4425e+0, 2.4985e+0],\n [2.8850e+0, 2.4985e+0],\n [4.3275e+0, 2.4985e+0],\n [2.1637e+0, 3.7477e+0],\n [3.6062e+0, 3.7477e+0],\n [2.8850e+0, 4.9970e+0]],\n nearest_neighbors=[[ 1, 5],\n [ 0, 2],\n [ 1, 3, 6, 7],\n [ 2, 4],\n [ 3, 8],\n [ 0, 9],\n [ 2, 9],\n [ 2, 11],\n [ 4, 11],\n [ 5, 6, 10, 12],\n [ 9, 11],\n [ 7, 8, 10, 13],\n [ 9, 14],\n [11, 14],\n [12, 13]] )\n\n .. image:: ../../images/lattice_custom.png\n :align: center\n\n **From a Zacros input file:**\n\n * ``fileName`` -- Path to the zacros file name, typically ``lattice_input.dat``\n\n Example:\n\n .. code:: python\n\n lattice = Lattice( fileName='mypath/lattice_input.dat' )\n\n \"\"\"\n\n # Origin\n __FROM_DEFAULT = 0\n __FROM_UNIT_CELL = 1\n __FROM_EXPLICIT = 2\n\n # Default lattices\n TRIANGULAR = 3\n RECTANGULAR = 4\n HEXAGONAL = 6\n\n # Neighboring_structure\n SELF = (0,0)\n NORTH = (0,1)\n NORTHEAST = (1,1)\n EAST = (1,0)\n SOUTHEAST = (1,-1)\n\n __NeighboringToStr = { SELF:\"self\", NORTH:\"north\", NORTHEAST:\"northeast\", EAST:\"east\", SOUTHEAST:\"southeast\" }\n\n def __init__(self, **kwargs):\n self.cell_vectors = None\n self.site_types = None\n self.site_coordinates = None\n self.nearest_neighbors = None\n\n self.__origin = None\n\n # Default Lattices\n if( \"lattice_type\" in kwargs and\n \"lattice_constant\" in kwargs and\n \"repeat_cell\" in kwargs ):\n self.__origin = Lattice.__FROM_DEFAULT\n self.__lattice_type_default = None\n self.__lattice_constant_default = None\n self.__repeat_cell_default = None\n\n self.__fromDefaultLattices( kwargs[\"lattice_type\"], kwargs[\"lattice_constant\"], kwargs[\"repeat_cell\"] )\n\n # Unit-Cell-Defined Periodic Lattices\n elif( \"cell_vectors\" in kwargs and\n \"repeat_cell\" in kwargs and\n \"site_types\" in kwargs and\n \"site_coordinates\" in kwargs and\n \"neighboring_structure\" in kwargs ):\n self.__origin = Lattice.__FROM_UNIT_CELL\n self.__cell_vectors_unit_cell = None\n self.__repeat_cell_unit_cell = None\n self.__site_types_unit_cell = None\n self.__site_coordinates_unit_cell = None\n self.__neighboring_structure_unit_cell = None\n\n self.__fromUnitCellDefined( kwargs[\"cell_vectors\"], kwargs[\"repeat_cell\"], kwargs[\"site_types\"],\n kwargs[\"site_coordinates\"], kwargs[\"neighboring_structure\"] )\n\n # Explicitly Defined Custom Lattices\n elif( \"site_types\" in kwargs and\n \"site_coordinates\" in kwargs and\n \"nearest_neighbors\" in kwargs ):\n self.__origin = Lattice.__FROM_EXPLICIT\n\n self.__fromExplicitlyDefined( kwargs[\"site_types\"], kwargs[\"site_coordinates\"],\n kwargs[\"nearest_neighbors\"], cell_vectors=kwargs.get(\"cell_vectors\") )\n\n # From a zacros file lattice_input.dat\n elif( \"fileName\" in kwargs ):\n self.__fromZacrosFile( kwargs[\"fileName\"] )\n\n else:\n msg = \"\\nError: The constructor for Lattice with the parameters:\"+str(kwargs)+\" is not implemented!\\n\"\n msg += \" Available options:\\n\"\n msg += \" - Lattice( lattice_type, lattice_constant, repeat_cell )\\n\"\n msg += \" - Lattice( cell_vectors, repeat_cell, site_types, site_coordinates, neighboring_structure )\\n\"\n msg += \" - Lattice( site_types, site_coordinates, nearest_neighbors, cell_vectors=None )\\n\"\n msg += \" - Lattice( fileName )\\n\"\n raise Exception(msg)\n\n\n def __fromDefaultLattices(self, lattice_type, lattice_constant, repeat_cell):\n \"\"\"\n Creates a default Lattice\n \"\"\"\n self.__lattice_type_default = lattice_type\n self.__lattice_constant_default = lattice_constant\n self.__repeat_cell_default = repeat_cell\n\n if( self.__lattice_type_default == Lattice.TRIANGULAR ):\n\n cell_vectors = [[lattice_constant*math.sqrt(3.0), 0.0],[0.0,3.0*lattice_constant]]\n site_types = [\"StTp1\", \"StTp1\", \"StTp1\", \"StTp1\"]\n site_coordinates = [[0.0, 0.0],[1.0/2.0, 1.0/6.0],[1.0/2.0, 1.0/2.0],[0.0, 2.0/3.0]]\n neighboring_structure=[ [(0,1), Lattice.SELF],\n [(1,2), Lattice.SELF],\n [(2,3), Lattice.SELF],\n [(1,0), Lattice.EAST],\n [(2,3), Lattice.EAST],\n [(3,0), Lattice.NORTH] ]\n\n self.__fromUnitCellDefined(cell_vectors, repeat_cell, site_types, site_coordinates, neighboring_structure)\n\n elif( self.__lattice_type_default == Lattice.RECTANGULAR ):\n\n cell_vectors = [[lattice_constant, 0.0],[0.0,lattice_constant]]\n site_types = [\"StTp1\"]\n site_coordinates = [[0.0, 0.0]]\n neighboring_structure=[ [(0,0), Lattice.NORTH],\n [(0,0), Lattice.EAST] ]\n\n self.__fromUnitCellDefined(cell_vectors, repeat_cell, site_types, site_coordinates, neighboring_structure)\n\n elif( self.__lattice_type_default == Lattice.HEXAGONAL ):\n\n cell_vectors = [[lattice_constant*math.sqrt(3.0), 0.0],[0.0,lattice_constant]]\n site_types = [\"StTp1\", \"StTp1\"]\n site_coordinates = [[0.0, 0.0],[0.5, 0.5]]\n neighboring_structure=[ [(0,0), Lattice.NORTH],\n [(0,1), Lattice.SELF],\n [(1,0), Lattice.NORTH],\n [(1,1), Lattice.NORTH],\n [(1,0), Lattice.NORTHEAST],\n [(1,0), Lattice.EAST] ]\n\n self.__fromUnitCellDefined(cell_vectors, repeat_cell, site_types, site_coordinates, neighboring_structure)\n\n\n def __fromUnitCellDefined(self, cell_vectors, repeat_cell, site_types, site_coordinates, neighboring_structure):\n \"\"\"\n Creates a Unit-Cell-Defined periodic Lattice\n \"\"\"\n assert( len(site_types) == len(site_coordinates) )\n\n self.__cell_vectors_unit_cell = cell_vectors\n self.__repeat_cell_unit_cell = repeat_cell\n self.__site_types_unit_cell = site_types\n self.__site_coordinates_unit_cell = site_coordinates\n self.__neighboring_structure_unit_cell = neighboring_structure\n\n ncellsites = len(site_types)\n ncells = repeat_cell[0]*repeat_cell[1]\n nsites = ncells*ncellsites\n\n self.cell_vectors = [ [repeat_cell[0]*a,repeat_cell[1]*b] for a,b in cell_vectors ]\n self.site_coordinates = nsites*[None]\n self.site_types = nsites*[None]\n self.nearest_neighbors = nsites*[None]\n\n def getcellnumber(i, j):\n if( i < 0 or j < 0 or i >= repeat_cell[0] or j >= repeat_cell[1] ):\n return None\n return i*repeat_cell[1] + j\n\n v1 = cell_vectors[0]\n v2 = cell_vectors[1]\n\n for i in range(repeat_cell[0]):\n for j in range(repeat_cell[1]):\n\n id_cell = i*repeat_cell[1] + j # cell counter\n\n xcellpos = i*v1[0] + j*v2[0] # cell position x\n ycellpos = i*v1[1] + j*v2[1] # cell position y\n\n for k in range(ncellsites):\n\n id_site = ncellsites*id_cell + k\n\n # x-y coordinates of the site\n xsite = site_coordinates[k][0]*v1[0] + site_coordinates[k][1]*v2[0] + xcellpos\n ysite = site_coordinates[k][0]*v1[1] + site_coordinates[k][1]*v2[1] + ycellpos\n\n self.site_coordinates[id_site] = [xsite,ysite]\n self.site_types[id_site] = site_types[k]\n\n # neighboring structure\n for (id_1,id_2),lDisp in neighboring_structure: # ldisp=latteral displacements\n\n if( id_1 == k ):\n id_cell_2 = getcellnumber(i+lDisp[0],j+lDisp[1])\n if( id_cell_2 is not None ):\n id_2_shifted = ncellsites*id_cell_2 + id_2\n\n if( self.nearest_neighbors[id_site] is None ):\n self.nearest_neighbors[id_site] = set()\n\n self.nearest_neighbors[id_site].add( id_2_shifted )\n if( id_2 == k ):\n id_cell_1 = getcellnumber(i-lDisp[0],j-lDisp[1])\n if( id_cell_1 is not None ):\n id_1_shifted = ncellsites*id_cell_1 + id_1\n\n if ( self.nearest_neighbors[id_site] is None ):\n self.nearest_neighbors[id_site] = set()\n\n self.nearest_neighbors[id_site].add( id_1_shifted )\n\n\n\n def __fromExplicitlyDefined(self, site_types, site_coordinates, nearest_neighbors, cell_vectors=None):\n \"\"\"\n Creates a explicitly defined custom Lattice\n \"\"\"\n self.site_types = site_types\n self.site_coordinates = site_coordinates\n self.nearest_neighbors = nearest_neighbors\n self.cell_vectors = cell_vectors\n\n\n def __fromZacrosFile(self, fileName):\n \"\"\"\n Creates a Lattice from a Zacros input file lattice_input.dat\n \"\"\"\n if not os.path.isfile( fileName ):\n raise Exception( \"Trying to load a file that doen't exist: \"+fileName )\n\n with open( fileName, \"r\" ) as inp:\n file_content = inp.readlines()\n file_content = [line.split(\"#\")[0] for line in file_content if line.split(\"#\")[0].strip()] # Removes empty lines and comments\n\n nline = 0\n while( nline < len(file_content) ):\n tokens = file_content[nline].split()\n\n if( tokens[0].lower() == \"lattice\" and tokens[1].lower() == \"default_choice\" ):\n nline += 1\n tokens = file_content[nline].split()\n\n if( len(tokens) < 4 ):\n raise Exception( \"Format Error in line \"+str(nline)+\" of file \"+ZacrosJob._filenames['lattice'] )\n\n cases = {\n \"triangular_periodic\" : Lattice.TRIANGULAR,\n \"rectangular_periodic\" : Lattice.RECTANGULAR,\n \"hexagonal_periodic\" : Lattice.HEXAGONAL\n }\n\n lattice_type = cases.get( tokens[0].lower(), None )\n\n if( lattice_type is None ):\n raise Exception( \"Error: Keyword \"+tokens[0]+\" in file \"+ZacrosJob._filenames['lattice']+\" is not supported!\" )\n\n lattice_constant = float(tokens[1])\n repeat_cell = ( int(tokens[2]), int(tokens[3]) )\n\n parameters = { \"lattice_type\":lattice_type,\n \"lattice_constant\":lattice_constant,\n \"repeat_cell\":repeat_cell }\n\n self.__init__( **parameters )\n\n if( tokens[0] == \"lattice\" and tokens[1] == \"periodic_cell\" ):\n nline += 1\n\n parameters = {}\n\n while( nline < len(file_content) ):\n tokens = file_content[nline].split()\n\n cases = {\n \"repeat_cell\" : lambda sv: parameters.setdefault(\"repeat_cell\", (int(sv[0]),int(sv[1])) ),\n \"n_site_types\" : lambda sv: parameters.setdefault(\"n_site_types\", int(sv[0])),\n \"site_type_names\" : lambda sv: parameters.setdefault(\"site_type_names\", sv),\n \"n_cell_sites\" : lambda sv: parameters.setdefault(\"n_cell_sites\", int(sv[0])),\n \"site_types\" : lambda sv: parameters.setdefault(\"site_types\", sv),\n }\n cases.get( tokens[0], lambda sv: None )( tokens[1:] )\n\n if( tokens[0] == \"cell_vectors\" ):\n parameters[\"cell_vectors\"] = 2*[None]\n for n in [0,1]:\n nline += 1\n tokens = file_content[nline].split()\n parameters[\"cell_vectors\"][n] = [ float(tokens[i]) for i in [0,1] ]\n\n elif( tokens[0] == \"site_coordinates\" ):\n # WARNING. Here, I'm assuming that n_cell_sites is defined before site_coordinates\n parameters[\"site_coordinates\"] = parameters[\"n_cell_sites\"]*[None]\n\n for n in range(parameters[\"n_cell_sites\"]):\n nline += 1\n tokens = file_content[nline].split()\n parameters[\"site_coordinates\"][n] = [ float(tokens[i]) for i in [0,1] ]\n\n elif( tokens[0] == \"neighboring_structure\" ):\n parameters[\"neighboring_structure\"] = []\n\n while( nline < len(file_content) ):\n nline += 1\n tokens = file_content[nline].split()\n\n if( tokens[0] == \"end_neighboring_structure\" ):\n break\n\n cases = {\n \"self\" : Lattice.SELF,\n \"north\" : Lattice.NORTH,\n \"northeast\" : Lattice.NORTHEAST,\n \"east\" : Lattice.EAST,\n \"southeast\" : Lattice.SOUTHEAST\n }\n value = cases.get( tokens[1] )\n\n if( value is None ):\n raise Exception( \"Error: Keyword \"+tokens[1]+\" in file \"+ZacrosJob._filenames['lattice']+\" is not supported!\" )\n\n parameters[\"neighboring_structure\"].append( [ tuple( int(a)-1 for a in tokens[0].split(\"-\") ), value ] )\n\n nline += 1\n\n self.__init__( **parameters )\n\n if( tokens[0] == \"lattice\" and tokens[1] == \"explicit\" ):\n nline += 1\n\n parameters = {}\n\n while( nline < len(file_content) ):\n tokens = file_content[nline].split()\n\n cases = {\n \"n_sites\" : lambda sv: parameters.setdefault(\"n_sites\", int(sv[0])),\n \"max_coord\" : lambda sv: parameters.setdefault(\"max_coord\", int(sv[0])),\n \"n_site_types\" : lambda sv: parameters.setdefault(\"n_site_types\", int(sv[0])),\n \"site_type_names\" : lambda sv: parameters.setdefault(\"site_type_names\", sv)\n }\n cases.get( tokens[0], lambda sv: None )( tokens[1:] )\n\n if( tokens[0] == \"lattice_structure\" ):\n parameters[\"site_types\"] = []\n parameters[\"site_coordinates\"] = []\n parameters[\"nearest_neighbors\"] = []\n\n while( nline < len(file_content) ):\n nline += 1\n tokens = file_content[nline].split()\n\n if( tokens[0] == \"end_lattice_structure\" ):\n break\n\n if( len(tokens) < 5 ):\n raise Exception( \"Error: Format inconsistent in section lattice_structure!\" )\n\n parameters[\"site_coordinates\"].append( [ float(tokens[1]), float(tokens[2]) ] )\n parameters[\"site_types\"].append( tokens[3] )\n parameters[\"nearest_neighbors\"].append( [ int(tokens[i])-1 for i in range(5,len(tokens)) ] )\n\n nline += 1\n\n self.__init__( **parameters )\n\n nline += 1\n\n\n def add_site_type( self, site_type, coordinates, precision=0.01 ):\n \"\"\"\n Adds a new site only if this is not already included in the lattice.\n It returns the id of the site\n\n * ``site_type`` -- Site type name, e.g. 'StTp1'\n * ``coordinates`` -- 2D vector representing the site position, e.g. [0.0, 0.5]\n * ``precision`` -- Precision used to determine (based on the coordinates) if the site is already\n or not contained on the list of sites. Default: 0.01\n \"\"\"\n locId = None\n for i,(s,(x,y)) in enumerate(zip(self.site_types,self.site_coordinates)):\n\n if( math.sqrt( (x-coordinates[0])**2 + (y-coordinates[1])**2 ) < precision ):\n locId = i\n\n if( s != site_type ):\n msg = \"### Error ### RKFLoader.add_site_type(). Trying to add a site that already exists with a different label\\n\"\n msg += \" (s_old,s_new) = (\"+str(s)+\",\"+str(site_type)+\")\\n\"\n msg += \" coords_old = \"+str([x,y])+\"\\n\"\n msg += \" coords_new = \"+str(coordinates)+\"\\n\"\n raise Exception( msg )\n\n if locId is None:\n self.site_types.append( site_type )\n self.site_coordinates.append( coordinates )\n self.__origin = Lattice.__FROM_EXPLICIT\n locId = len(self.site_types)-1\n\n return locId\n\n\n def add_nearest_neighbor( self, id_site, id_neighbor ):\n \"\"\"\n Adds a new nearest-neighbor item to the lattice, e.g. (1,3)\n\n * ``id_site`` -- Site id, e.g. 1\n * ``id_neighbor`` -- id of the new site neighbor, e.g. 3\n \"\"\"\n self.nearest_neighbors[ id_site ].append( id_neighbor )\n self.__origin = Lattice.__FROM_EXPLICIT\n\n\n def extend( self, other, precision=0.1, cell_vectors_precision=0.01 ):\n \"\"\"\n Extends the sites and corresponding neighboring information by appending the equivalent items from another lattice.\n\n * ``other`` -- Lattice to append\n * ``precision`` -- Precision used to determine (based on the coordinates) if the site is already\n or not contained on the list of sites. Default: 0.1\n * ``cell_vectors_precision`` -- Precision used to determine cell_vectors are the same or not. Default: 0.01\n \"\"\"\n for i in range(len(self.cell_vectors)):\n for j in range(len(self.cell_vectors[0])):\n if( self.cell_vectors[i][j] - other.cell_vectors[i][j] > cell_vectors_precision ):\n raise Exception(\"### Error ### RKFLoader.extend(). Lattices not compatible\")\n\n #--------------------------------------------\n # Merging the general attributes\n #--------------------------------------------\n mapping = {}\n for old_id,(site_type,coordinates,neighbors) in enumerate(zip(other.site_types,other.site_coordinates,other.nearest_neighbors)):\n new_id = self.add_site_type( site_type, coordinates, precision )\n mapping[old_id] = new_id\n\n if( new_id > len(self.nearest_neighbors)-1 ):\n self.nearest_neighbors.append( set() )\n\n for old_id,nearest_neighbors in enumerate(other.nearest_neighbors):\n if nearest_neighbors is None: continue\n for id in nearest_neighbors:\n self.nearest_neighbors[mapping[old_id]].add( mapping[id] )\n\n #self.__origin = other.__origin\n #self.__cell_vectors_unit_cell = other.__cell_vectors_unit_cell\n #self.__repeat_cell_unit_cell = other.__repeat_cell_unit_cell\n #self.__site_types_unit_cell.extend( other.__site_types_unit_cell )\n #self.__site_coordinates_unit_cell.extend( other.__site_coordinates_unit_cell )\n #self.__neighboring_structure_unit_cell.extend( other.__neighboring_structure_unit_cell )\n\n self.__origin = Lattice.__FROM_EXPLICIT\n #self.__origin = Lattice.__FROM_UNIT_CELL\n\n\n def plot(self, pause=-1, show=True, color=None, ax=None, close=False, show_sites_ids=False, file_name=None):\n \"\"\"\n Uses Matplotlib to visualize the lattice. Be sure that Matplotlib is installed in your system; otherwise, the function does nothing.\n\n * ``pause`` -- After showing the figure, it will wait ``pause``-seconds before refreshing. This can be used for crude animation.\n * ``show`` -- Enables showing the figure on the screen.\n * ``color`` -- Uses the same color for both binding sites and connections; e.g. 'k'. See `matplotlib.colors `_.\n * ``ax`` -- The axes of the plot. It contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. See `matplotlib.axes `_.\n * ``close`` -- Closes the figure window after pause time.\n * ``show_sites_ids`` -- Shows the binding sites id on the figure.\n * ``file_name`` -- Saves the figure to the file ``file_name``. The format is inferred from the extension, and by default, ``.png`` is used.\n \"\"\"\n try:\n import math\n import matplotlib.pyplot as plt\n import numpy as np\n except ImportError as e:\n return # module doesn't exist, deal with it.\n\n if( ax is None ):\n fig,ax = plt.subplots()\n\n if( self.cell_vectors is not None ):\n v1 = self.cell_vectors[0]\n v2 = self.cell_vectors[1]\n xvalues = [0.0,v1[0], v1[0]+v2[0], v2[0], 0.0]\n yvalues = [0.0,v1[1], v1[1]+v2[1], v2[1], 0.0]\n\n lcolor = color if color is not None else 'k'\n ax.plot(xvalues, yvalues, color=lcolor, linestyle='dashed', linewidth=1, zorder=1)\n\n x_len = abs(v2[0]-v1[0])\n ax.set_xlim( [ 0.0-0.1*x_len, v1[0]+v2[0]+0.1*x_len ] )\n y_len = abs(v2[1]-v1[1])\n ax.set_ylim( [ 0.0-0.1*y_len, v1[1]+v2[1]+0.1*y_len ] )\n\n if( x_len > y_len ):\n ax.set_aspect(1.8*y_len/x_len)\n elif( y_len > x_len ):\n ax.set_aspect(1.8*x_len/y_len)\n elif( x_len == y_len ):\n ax.set_aspect(1.0)\n\n v1 = self.__cell_vectors_unit_cell[0]\n v2 = self.__cell_vectors_unit_cell[1]\n xvalues = [0.0,v1[0], v1[0]+v2[0], v2[0], 0.0]\n yvalues = [0.0,v1[1], v1[1]+v2[1], v2[1], 0.0]\n\n lcolor = color if color is not None else 'k'\n ax.plot(xvalues, yvalues, color=lcolor, linestyle='solid', linewidth=3, zorder=1)\n\n #ax.set_xlabel('x ($\\AA$)')\n #ax.set_ylabel('y ($\\AA$)')\n\n ax.set_xlabel('x (ang.)')\n ax.set_ylabel('y (ang.)')\n\n #markers = ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']\n markers = ['o', 's', 'v', '^', '+', '^']\n colors = ['r', 'g', 'b', 'm', 'c', 'k']\n\n for i,st_i in enumerate(sorted(list(set(self.site_types)))):\n xvalues = [ x for (x,y),st in zip(self.site_coordinates,self.site_types) if st==st_i ]\n yvalues = [ y for (x,y),st in zip(self.site_coordinates,self.site_types) if st==st_i ]\n\n lcolor = color if color is not None else colors[i]\n ax.scatter(xvalues, yvalues, color=lcolor, marker=markers[i],\n s=440/math.sqrt(len(self.site_coordinates)), zorder=2, label=st_i)\n\n if( show_sites_ids ):\n for i,(x,y) in enumerate(self.site_coordinates):\n plt.annotate(str(i), (x,y), ha='center', va='center', zorder=100)\n\n\n for i,ineigh in enumerate(self.nearest_neighbors):\n if( ineigh is None ): continue\n\n for k in ineigh:\n xvalues = np.array([ self.site_coordinates[i][0], self.site_coordinates[k][0] ])\n yvalues = np.array([ self.site_coordinates[i][1], self.site_coordinates[k][1] ])\n\n norm = math.sqrt( (xvalues[0]-xvalues[1])**2 + (yvalues[0]-yvalues[1])**2 )\n\n if( self.cell_vectors is not None ):\n if( norm > np.linalg.norm(1.5*np.array(v1)) ): continue\n if( norm > np.linalg.norm(1.5*np.array(v2)) ): continue\n\n lcolor = color if color is not None else 'k'\n ax.plot(xvalues, yvalues, color=lcolor, linestyle='solid',\n linewidth=1.5/math.sqrt(len(self.site_coordinates)), zorder=1)\n\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n plt.tight_layout()\n\n if( file_name is not None ):\n plt.savefig( file_name )\n\n if( show ):\n if( pause == -1 ):\n plt.show()\n else:\n plt.pause( pause )\n\n if( close ):\n plt.close(\"all\")\n\n\n def __str__(self):\n \"\"\"\n Translate the object to a string following the Zacros input files format\n \"\"\"\n output = \"\"\n\n if( self.__origin == Lattice.__FROM_DEFAULT ):\n output += \"lattice default_choice\\n\"\n\n if( self.__lattice_type_default == Lattice.TRIANGULAR ):\n output += \" triangular_periodic\"\n elif( self.__lattice_type_default == Lattice.RECTANGULAR ):\n output += \" rectangular_periodic\"\n elif( self.__lattice_type_default == Lattice.HEXAGONAL ):\n output += \" hexagonal_periodic\"\n else:\n raise Exception(\"Error: Default lattice not implemented yet! (\"+self.__lattice_type_default+\")\")\n\n output += \" \"+str(self.__lattice_constant_default)\n output += \" \"+str(self.__repeat_cell_default[0])\n output += \" \"+str(self.__repeat_cell_default[1])+\"\\n\"\n\n output += \"end_lattice\"\n\n elif( self.__origin == Lattice.__FROM_UNIT_CELL ):\n output += \"lattice periodic_cell\\n\"\n\n output += \" cell_vectors\\n\"\n for i in range(2):\n for j in range(2):\n output += \" \"+(\"%.8f\"%self.__cell_vectors_unit_cell[i][j])\n output += \"\\n\"\n\n output += \" repeat_cell \"+str(str(self.__repeat_cell_unit_cell)[1:-1]).replace(',', '')+\"\\n\"\n\n n_cell_sites = len(self.__site_coordinates_unit_cell)\n\n site_types = list(set(self.__site_types_unit_cell))\n site_types.sort()\n\n output += \" n_site_types \"+str(len(site_types))+\"\\n\"\n output += \" site_type_names \"+str(' '.join(str(x) for x in site_types))+\"\\n\"\n output += \" n_cell_sites \"+str(n_cell_sites)+\"\\n\"\n output += \" site_types \"+str(' '.join(str(x) for x in self.__site_types_unit_cell))+\"\\n\"\n\n output += \" site_coordinates\\n\"\n for i in range(n_cell_sites):\n for j in range(2):\n output += \" \"+(\"%.8f\"%self.__site_coordinates_unit_cell[i][j])\n output += \"\\n\"\n\n output += \" neighboring_structure\\n\"\n for i in range(len(self.__neighboring_structure_unit_cell)):\n output += \" \"+str('-'.join(str(self.__neighboring_structure_unit_cell[i][0][j]+1) for j in range(2)))\n output += \" \"+Lattice.__NeighboringToStr[self.__neighboring_structure_unit_cell[i][1]]+\"\\n\"\n output += \" end_neighboring_structure\\n\"\n\n output += \"end_lattice\"\n\n elif( self.__origin == Lattice.__FROM_EXPLICIT ):\n output += \"lattice explicit\\n\"\n\n if( self.cell_vectors is not None ):\n output += \" cell_vectors\\n\"\n for i in range(2):\n for j in range(2):\n output += \" \"+(\"%.8f\"%self.cell_vectors[i][j])\n output += \"\\n\"\n\n output += \" n_sites \"+str(len(self.site_types))+\"\\n\"\n output += \" max_coord \"+str(max([ len(neighbors) for neighbors in self.nearest_neighbors ]))+\"\\n\"\n\n site_types = list(set(self.site_types))\n site_types.sort()\n\n output += \" n_site_types \"+str(len(site_types))+\"\\n\"\n output += \" site_type_names \"+str(' '.join(str(x) for x in site_types))+\"\\n\"\n\n output += \" lattice_structure\\n\"\n\n for i in range(len(self.site_types)):\n output += \" \"+\"%4d\"%(i+1)\n output += \" \"+\"%15.8f\"%self.site_coordinates[i][0]+\" \"+\"%15.8f\"%self.site_coordinates[i][1]\n output += \" \"+\"%10s\"%self.site_types[i]\n output += \" \"+\"%4d\"%len(self.nearest_neighbors[i])\n\n for j in self.nearest_neighbors[i]:\n output += \"%6d\"%(j+1)\n\n output += \"\\n\"\n\n output += \" end_lattice_structure\\n\"\n\n output += \"end_lattice\"\n\n return output\n\n\n def number_of_sites( self ):\n \"\"\"\n Returns the total number of sites\n \"\"\"\n return len(self.site_types)\n\n\n def site_types_set( self ):\n \"\"\"\n Returns the set of the sites types\n \"\"\"\n if( self.__origin == Lattice.__FROM_DEFAULT ):\n return set([0])\n else:\n return set(self.site_types)\n\n\n def set_repeat_cell( self, repeat_cell ):\n \"\"\"\n Set the parameter repeat_cell and update all internal information\n\n * ``repeat_cell`` -- The number of repetitions of the unit cell in the directions of unit vectors. *e.g.* ``(10,10)``\n \"\"\"\n if( self.__origin == Lattice.__FROM_DEFAULT ):\n self.__fromDefaultLattices( self.__lattice_type_default, self.__lattice_constant_default, repeat_cell )\n\n elif( self.__origin == Lattice.__FROM_UNIT_CELL ):\n self.__fromUnitCellDefined( self.__cell_vectors_unit_cell, repeat_cell, self.__site_types_unit_cell,\n self.__site_coordinates_unit_cell, self.__neighboring_structure_unit_cell )\n\n elif( self.__origin == Lattice.__FROM_EXPLICIT ):\n pass\n\n\n def replace_site_types( self, site_types_old, site_types_new ):\n \"\"\"\n Replaces the site types names\n\n * ``site_types_old`` -- List of strings containing the old site_types to be replaced\n * ``site_types_new`` -- List of strings containing the new site_types which would replace old site_types_old.\n \"\"\"\n assert( len(site_types_old) == len(site_types_new) )\n\n for i in range(len(site_types_old)):\n for j in range(len(self.site_types)):\n if( self.site_types[j] == site_types_old[i] ):\n self.site_types[j] = site_types_new[i]\n\n for j in range(len(self.__site_types_unit_cell)):\n if( self.__site_types_unit_cell[j] == site_types_old[i] ):\n self.__site_types_unit_cell[j] = site_types_new[i]\n","repo_name":"SCM-NV/pyZacros","sub_path":"core/Lattice.py","file_name":"Lattice.py","file_ext":"py","file_size_in_byte":37212,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"41"} +{"seq_id":"70157328765","text":"import json as json\nimport requests as requests\nimport api_service as api_service\nimport data_service as data_service\nimport tkinter as tk\nfrom tkinter import messagebox\nimport time as time\nimport os as os\nimport re as re\nfrom datetime import datetime as datetime\n\nglobal globalConfig\nglobal configPortfolioFile\n\nwith open('config.json', 'r') as jsonConfigFile:\n globalConfig = json.load(jsonConfigFile)\n\nclass MainApp():\n\n #MAIN INITIALIZATION OF APP\n def __init__(self, master):\n self.master = master\n self.frameSecPrices = tk.Frame(self.master, borderwidth = 2, relief = 'sunken')\n self.frameApiConnectCheck = tk.Frame(self.master, borderwidth = 2, relief = 'sunken', padx = 300, pady = 10)\n self.frameCoinHoldings = tk.Frame(self.master, borderwidth = 2, relief = 'sunken')\n\n self.labelUpdateTime = tk.Label(self.frameSecPrices, text = '')\n self.labelcoingeckoApiGet = tk.Label(self.frameSecPrices, text = '')\n self.labelcoingeckoApiCheck = tk.Label(self.frameApiConnectCheck, text = '')\n self.labelbinanceApiCheck = tk.Label(self.frameApiConnectCheck, text = '')\n\n\n self.frameSecPrices.grid(row = 0, column = 0)\n self.frameApiConnectCheck.grid(row = 0, column = 1)\n self.frameCoinHoldings.grid(row = 1, column = 1)\n\n self.labelUpdateTime.pack()\n self.labelcoingeckoApiGet.pack()\n self.labelcoingeckoApiCheck.pack(side = 'left')\n self.labelbinanceApiCheck.pack(side = 'left')\n\n self.btcPriceSec()\n self.apiCheckSec()\n currentPortfolio = CoinHoldingsTable(self.frameCoinHoldings)\n\n def btcPriceSec(self):\n currentBtcPriceUSDJSON = api_service.coingeckoApiGet('/simple/price', 'JSON', {'ids':'bitcoin','vs_currencies':'usd'})\n currentBtcPriceUSD = currentBtcPriceUSDJSON['bitcoin']['usd']\n self.labelcoingeckoApiGet.configure(text = 'BTC: $' + str(currentBtcPriceUSD))\n self.labelUpdateTime.configure(text = 'Last updated: ' + datetime.now().strftime('%H:%M:%S'))\n self.frameSecPrices.after(5000, self.btcPriceSec)\n\n def apiCheckSec(self):\n binanceApiResponse = api_service.binanceApiCheck()\n coingeckoApiResponse = api_service.coingeckoApiCheck()\n\n if binanceApiResponse[0] == True:\n self.labelbinanceApiCheck.configure(text = 'Binance API: Okay')\n\n else:\n self.labelbinanceApiCheck.configure(text = 'Binance API: Error ' + str(binanceApiResponse[1]))\n\n if coingeckoApiResponse[0] == True:\n self.labelcoingeckoApiCheck.configure(text = 'Coingecko API: Okay')\n\n else:\n self.labelcoingeckoApiCheck.configure(text = 'Coingecko API: Error' + str(coingeckoApiResponse[1]))\n self.frameApiConnectCheck.after(5000, self.apiCheckSec)\n\n\nclass CoinHoldingsTable(tk.Frame):\n\n def __init__(self, master):\n tk.Frame.__init__(self, master)\n self.master = master\n\n self.arrHeadingTableLabel = []\n self.arrTableLabel = []\n self.arrTableData = []\n self.currentTableDisplayed = globalConfig[0].get('workingPortfolioFile')\n\n self.coinHasBeenChecked = False #FOR ADDING NEW COIN VALIDATION, REMOVE WHEN UPDATE VALIDATION METHOD\n self.checkedName = '' #FOR ADDING NEW COIN VALIDATION, REMOVE WHEN UPDATE VALIDATION METHOD\n self.checkedTicker = '' #FOR ADDING NEW COIN VALIDATION, REMOVE WHEN UPDATE VALIDATION METHOD\n\n self.frameUserCoinHoldingsTable = tk.Frame(self.master, borderwidth = 2, relief = 'sunken')\n self.labelCurrentTableDisplayed = tk.Label(self.master, borderwidth = 2, relief = 'sunken')\n self.buttonUpdateTablePrices = tk.Button(self.master, borderwidth = 2)\n self.buttonAddTestCoin = tk.Button(self.master, borderwidth = 2)\n\n self.labelCurrentTableDisplayed.configure(text = self.currentTableDisplayed)\n self.buttonUpdateTablePrices.configure(text = 'Update Current Prices', command = lambda: (self.updateCoinHoldingTableCurrentPrices()))\n self.buttonAddTestCoin.configure(text = 'Add New Coin', command = lambda: (self.addNewCoinForm()))\n\n self.createCoinHoldingsTable()\n self.updateCoinHoldingTableCurrentPrices()\n\n self.labelCurrentTableDisplayed.grid(row = 0, column = 0)\n\n self.buttonUpdateTablePrices.grid(row = 0, column = 1)\n self.buttonAddTestCoin.grid(row = 0, column = 2)\n\n self.frameUserCoinHoldingsTable.grid(row = 1, column = 0, columnspan = 2)\n\n def createCoinHoldingsTableHeadings(self):\n coinHoldingsKeys = Coin.currentCoinFields(False)\n listCoinHoldingsKeys = list(coinHoldingsKeys)\n for key in range(len(listCoinHoldingsKeys)):\n headingStr = re.sub(r\"(?<=\\w)([A-Z])\", r\" \\1\", listCoinHoldingsKeys[key]).title()\n self.headingTableLabel = tk.Label(self.frameUserCoinHoldingsTable, text = headingStr)\n self.headingTableLabel.grid(row = 0, column = key, padx = 1, pady = 1)\n self.arrHeadingTableLabel.append(listCoinHoldingsKeys[key])\n\n\n def createCoinHoldingsTable(self):\n\n self.createCoinHoldingsTableHeadings()\n\n rowInsert = 1\n columnInsert = 0\n self.arrTableLabel = []\n self.arrTableData = []\n\n for keyIndex in Coin.coinDict:\n columnInsert = 0\n currentRowLabel = []\n currentRowData = {}\n currentCoinDict = Coin.coinDict[keyIndex].dataDict(False)\n currentRowKeysList = Coin.currentCoinFields(False)\n for coinData in currentCoinDict.values():\n self.tableLabel = tk.Label(self.frameUserCoinHoldingsTable, text = coinData)\n self.tableLabel.grid(row = rowInsert, column = columnInsert, padx = 1, pady = 1)\n currentRowLabel.append(self.tableLabel)\n currentRowData.update({currentRowKeysList[columnInsert] : coinData})\n columnInsert += 1\n self.arrTableLabel.append(currentRowLabel)\n self.arrTableData.append(currentRowData)\n rowInsert += 1\n\n #def saveCoinHoldingsTable(self):\n #\n # fileToWriteTo = (globalConfig[0].get('workingPortfolioFile'))\n # print(self.arrTableData)\n # data_service.saveToJSONFile(fileToWriteTo, self.arrTableData)\n\n def updateCoinHoldingTableEntry(self, coinToUpdate, fieldToUpdate, updatedData, toSave):\n\n cTU = coinToUpdate\n fTU = fieldToUpdate\n uD = updatedData\n for i in range(len(self.arrTableData)):\n if self.arrTableData[i]['name'] == cTU:\n self.arrTableData[i].update({fTU : uD})\n break\n\n for j in range(len(self.arrTableLabel[i])):\n if self.arrHeadingTableLabel[j] == fTU:\n labelToUpdate = self.arrTableLabel[i][j]\n labelToUpdate.configure(text = uD)\n break\n\n if toSave == True:\n Coin.saveCoins()\n\n def updateCoinHoldingTableCurrentPrices(self):\n print('updating price')\n Coin.updateCoinPrices('coingecko')\n for key in Coin.coinDict.keys():\n if Coin.coinDict[key].inExchange == 'True':\n self.updateCoinHoldingTableEntry(Coin.coinDict[key].name, 'mostRecentPrice', Coin.coinDict[key].mostRecentPrice, False)\n self.updateCoinHoldingTableEntry(Coin.coinDict[key].name, 'mostRecentTime', Coin.coinDict[key].mostRecentTime, False)\n\n Coin.saveCoins()\n\n def addNewCoinForm(self): #REPLACE WITH tkinter validate\n def addNewCoin():\n updatedDataDict = {}\n name = entryNCWName.get()\n ticker = entryNCWTicker.get()\n amount = entryNCWAmount.get()\n currency = omCurrency.get()\n price = entryNCWPrice.get()\n time = entryNCWTime.get()\n\n varDict = {'name':name,'ticker':ticker,'amount':amount,'currency':currency,'price':price,'time':time}\n\n fieldTypeIncorrect = False\n emptyFields = False\n\n for varData in list(varDict.keys()):\n if varDict[varData] == '':\n emptyFields = True\n if varData == 'amount' or varData == 'price':\n try:\n int(varDict[varData])\n except:\n fieldTypeIncorrect = True\n\n coinAlreadyExist = False\n for keyToCheck in Coin.coinDict.keys():\n if keyToCheck == name:\n coinAlreadyExist = True\n if Coin.coinDict[keyToCheck].ticker == ticker:\n coinAlreadyExist = True\n\n try:\n if name != self.checkedName:\n self.coinHasBeenChecked = False\n except:\n self.coinHasBeenChecked = False\n\n try:\n if ticker != self.checkedTicker:\n self.coinHasBeenChecked = False\n except:\n self.coinHasBeenChecked = False\n\n if (coinAlreadyExist == False) and (emptyFields == False) and (fieldTypeIncorrect == False):\n if self.coinHasBeenChecked == True:\n Coin.addCoin(entryNCWName.get())\n updatedDataDict.clear()\n updatedDataDict.update({'ticker':ticker,'amount':amount,'currencyBoughtIn':currency,'boughtAtPrice':price,'boughtAtTime':time,'inExchange':'True'})\n Coin.coinDict[name].updateFields(updatedDataDict)\n self.createCoinHoldingsTable()\n Coin.saveCoins()\n labelNCVInfo.configure(text = 'Coin: ' + name + ' added succesfully!', fg = 'green')\n self.coinHasBeenChecked = False\n else:\n if messagebox.askyesno(\"Warning\",\"Coin: \" + name + \" has not been checked against Coingecko database, proceed?\"):\n newCoinWindow.lift()\n Coin.addCoin(entryNCWName.get())\n updatedDataDict.clear()\n updatedDataDict.update({'ticker':ticker,'amount':amount,'currencyBoughtIn':currency,'boughtAtPrice':price,'boughtAtTime':time})\n Coin.coinDict[name].updateFields(updatedDataDict)\n self.createCoinHoldingsTable()\n Coin.saveCoins()\n labelNCVInfo.configure(text = 'Coin: ' + name + ' added succesfully!', fg = 'green')\n self.coinHasBeenChecked = False\n else:\n newCoinWindow.lift()\n elif emptyFields == True:\n labelNCVInfo.configure(text = 'Not all Coin data fields have been filled!', fg = 'red')\n elif coinAlreadyExist == True:\n labelNCVInfo.configure(text = 'Coin: ' + name + ' already exists!', fg = 'red')\n elif fieldTypeIncorrect == True:\n labelNCVInfo.configure(text = 'One or more fields have incorrect data types!', fg = 'red')\n else:\n labelNCVInfo.configure(text = 'Unknown error, please check all fields!', fg = 'red')\n\n def checkCoinExists():\n name = entryNCWName.get()\n apiResponse = api_service.coingeckoApiGet('/coins/' + name, 'JSON', {'id':name,'localization':False,'tickers':False,'market_data':False,'community_data':False,'developer_data':False})\n if apiResponse.get('id') == name:\n labelNCVInfo.configure(text = 'Coin: ' + name + ' exists on Coingecko, added ticker!', fg = 'green')\n entryNCWTicker.delete(0,tk.END)\n entryNCWTicker.insert(0,apiResponse.get('symbol'))\n self.checkedName = name\n self.checkedTicker = apiResponse.get('symbol')\n self.coinHasBeenChecked = True\n else:\n labelNCVInfo.configure(text = 'Coin: ' + name + ' does not exist on Coingecko!', fg = 'red')\n self.coinHasBeenChecked = False\n\n newCoinWindow = tk.Toplevel()\n omCurrency = tk.StringVar(self)\n \n newCoinWindowLength = newCoinWindow.winfo_reqwidth()\n\n labelNCWName = tk.Label(newCoinWindow, text = 'Name:')\n labelNCWTicker = tk.Label(newCoinWindow, text = 'Ticker:')\n labelNCWAmount = tk.Label(newCoinWindow, text = 'Amount:')\n labelNCWCurrency = tk.Label(newCoinWindow, text = 'Currency:')\n labelNCWPrice = tk.Label(newCoinWindow, text = 'Price:')\n labelNCWTime = tk.Label(newCoinWindow, text = 'Time:')\n labelNCVInfo = tk.Label(newCoinWindow, text = '', wraplength = newCoinWindowLength)\n\n entryNCWName = tk.Entry(newCoinWindow)\n entryNCWTicker = tk.Entry(newCoinWindow)\n entryNCWAmount = tk.Entry(newCoinWindow)\n entryNCWPrice = tk.Entry(newCoinWindow)\n entryNCWTime = tk.Entry(newCoinWindow)\n\n optionmenuNCWCurrnency = tk.OptionMenu(newCoinWindow, omCurrency, 'usd')\n\n labelNCWName.grid(row = 0, column = 0, sticky = 'W')\n labelNCWTicker.grid(row = 1, column = 0, sticky = 'W')\n labelNCWAmount.grid(row = 2, column = 0, sticky = 'W')\n labelNCWCurrency.grid(row = 3, column = 0, sticky = 'W')\n labelNCWPrice.grid(row = 4, column = 0, sticky = 'W')\n labelNCWTime.grid(row = 5, column = 0, sticky = 'W')\n labelNCVInfo.grid(row = 6, column = 0, columnspan = 3, sticky = 'W')\n\n entryNCWName.grid(row = 0, column = 1)\n entryNCWTicker.grid(row = 1, column = 1)\n entryNCWAmount.grid(row = 2, column = 1)\n optionmenuNCWCurrnency.grid(row = 3, column = 1, sticky = 'E')\n entryNCWPrice.grid(row = 4, column = 1)\n entryNCWTime.grid(row = 5, column = 1)\n\n buttonNCWSendData = tk.Button(newCoinWindow, text='Add Coin', command = lambda: addNewCoin()).grid(row = 5, column = 2)\n buttonNCWCheckCoin = tk.Button(newCoinWindow, text='Check Coin', command = lambda: checkCoinExists()).grid(row = 0, column = 2)\n\n\n\nclass Coin():\n\n coinDict = {}\n\n @classmethod\n def totalCoins(cls):\n return len(Coin.coinDict)\n\n @classmethod\n def listCoinClasses(cls):\n return Coin.coinDict\n\n @classmethod\n def initializeCoins(cls, fileLocation):\n coinsDataJSON = data_service.readJSONFile(fileLocation)\n for i in range(len(coinsDataJSON)):\n Coin.coinDict.update({(coinsDataJSON[i]['name']):(Coin(coinsDataJSON[i]['name']))})\n\n @classmethod\n def addCoin(cls, coinName):\n if Coin.coinDict.get(coinName, False) == False:\n Coin.coinDict.update({(coinName):(Coin(coinName))})\n\n @classmethod\n def updateCoinPrices(cls, apiToUse):\n coinsToCheckList = []\n for key in Coin.coinDict.keys():\n coinsToCheckList.append(key)\n coinsToCheckStr = ','.join(coinsToCheckList)\n updatePriceJSON = api_service.coingeckoApiGet('/simple/price', 'JSON', {'ids':coinsToCheckStr,'vs_currencies':'usd'})\n for key in Coin.coinDict.keys():\n if Coin.coinDict[key].inExchange == 'True':\n Coin.coinDict[key].mostRecentPrice = updatePriceJSON.get(key).get('usd')\n Coin.coinDict[key].mostRecentTime = datetime.now().strftime('%H:%M:%S')\n\n @classmethod\n def currentCoinFields(cls, returnNonDataFields):\n fieldsToRetun = list(vars(Coin.coinDict[(list(Coin.coinDict.keys())[0])]))\n if returnNonDataFields == True:\n return fieldsToRetun\n else:\n try:\n fieldsToRetun.remove('isDeleted')\n fieldsToRetun.remove('inExchange')\n except:\n pass\n return fieldsToRetun\n\n @classmethod\n def saveCoins(cls):\n dataToSave = []\n for coinToSave in Coin.listCoinClasses():\n dataToSave.append(Coin.coinDict[coinToSave].dataDict(True))\n data_service.saveToJSONFile(globalConfig[0].get('workingPortfolioFile'), dataToSave)\n\n #@classmethod\n #def coinData(cls):\n\n\n def __init__(self, name):\n self.name = name\n coinFoundInJSON = False\n portfolioJSONData = data_service.readJSONFile(globalConfig[0].get('workingPortfolioFile'))\n for currentCoinIndex in range(len(portfolioJSONData)):\n if portfolioJSONData[currentCoinIndex]['name'] == self.name:\n self.ticker = portfolioJSONData[currentCoinIndex]['ticker']\n self.amount = portfolioJSONData[currentCoinIndex]['amount']\n self.boughtAtPrice = portfolioJSONData[currentCoinIndex]['boughtAtPrice']\n self.boughtAtTime = portfolioJSONData[currentCoinIndex]['boughtAtTime']\n self.currencyBoughtIn = portfolioJSONData[currentCoinIndex]['currencyBoughtIn']\n self.mostRecentPrice = portfolioJSONData[currentCoinIndex]['mostRecentPrice']\n self.mostRecentTime = portfolioJSONData[currentCoinIndex]['mostRecentTime']\n self.inExchange = portfolioJSONData[currentCoinIndex]['inExchange']\n coinFoundInJSON = True\n break\n\n if coinFoundInJSON == False:\n self.ticker = '-'\n self.amount = '0'\n self.boughtAtPrice = '0'\n self.boughtAtTime = '-'\n self.currencyBoughtIn = '-'\n self.mostRecentPrice = '0'\n self.mostRecentTime = '-'\n self.inExchange = \"False\"\n\n self.isDeleted = False\n\n def dataDict(self, returnNonDataFields):\n returnDict = vars(self).copy()\n if returnNonDataFields == True:\n return returnDict\n else:\n try:\n returnDict.pop('isDeleted')\n returnDict.pop('inExchange')\n except:\n pass\n return returnDict\n\n def updateFields(self, updatedDataDict):\n self.ticker = updatedDataDict.get('ticker')\n self.amount = updatedDataDict.get('amount')\n self.boughtAtPrice = updatedDataDict.get('boughtAtPrice')\n self.boughtAtTime = updatedDataDict.get('boughtAtTime')\n self.currencyBoughtIn = updatedDataDict.get('currencyBoughtIn')\n self.inExchange = updatedDataDict.get('inExchange')\n\n def changeInPriceAbsolute(self):\n priceChange = (self.currentPrice - self.boughtAtPrice)\n return priceChange\n\n def changeInPricePercentage(self, returnType):\n priceChange = (self.currentPrice - self.boughtAtPrice)\n percentageChange = (((priceChange/currentPrice)*100)-100)\n percentageChangeStr = percentageChange.str() + '%'\n if returnType == 'str':\n return percentageChangeStr\n elif returnType == 'int':\n return percentageChange\n else:\n return 'Invalid returnType'\n\n def delSelf(self):\n Coin.coinDict.pop(self.name)\n self.isDeleted = True\n\n\n\n\n #use this as main storage in program itself\n #use sqlite for database\n #make class methods for storage and organization of each Coin instance\n\n\n\ndef main():\n Coin.initializeCoins(globalConfig[0].get('workingPortfolioFile'))\n root = tk.Tk()\n MainAppInstance = MainApp(root)\n MainApp(root)\n root.tk.mainloop()\n\nif __name__ == '__main__':\n main()\n","repo_name":"jsweasey/anothercryptoclient","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":19240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"585253402","text":"# Objets\n\nimport array\nimport json\n\nfrom custom_errors import CustomError\n\n\nclass Answer():\n def __init__(self, id: int, text: str, isCorrect: bool, position: int):\n self.id = id\n self.text = text\n self.isCorrect = isCorrect\n self.position = position\n\n def toJSON(self):\n return {\n \"id\": self.id,\n \"text\": self.text,\n \"isCorrect\": bool(self.isCorrect),\n \"position\": self.position\n }\n\n def verifyCreate(self):\n missing_parameters = []\n if self.text == None:\n missing_parameters.append(\"text\")\n if self.isCorrect == None:\n missing_parameters.append(\"isCorrect\")\n if len(missing_parameters) > 0:\n raise CustomError(400, \"Missing values for : \" + ''.join([str(a) + \", \" for a in missing_parameters]))\n\n def loadFromDB(dbResult : object):\n return Answer(dbResult[0], dbResult[2], dbResult[3], dbResult[4])\n\nclass Question():\n def __init__(self, id: int, title: str, text: str, image: str, position: int, answers: object):\n self.id = id\n self.title = title\n self.text = text\n self.image = image\n self.position = position\n self.answers = answers\n\n def toJSON(self):\n return {\n \"id\": self.id,\n \"title\":self.title,\n \"text\":self.text,\n \"image\": self.image,\n \"position\": self.position,\n \"possibleAnswers\":[answer.toJSON() for answer in self.answers]\n }\n\n def getAnswerInPosition(self, pos: int):\n if pos < 1:\n raise CustomError(400, \"An answer is always at least in position 1 : \" + str(pos))\n if pos > len(self.answers):\n raise CustomError(400, \"There is no answer of that position : \" + str(pos))\n\n return self.answers[pos - 1]\n\n def answerIsTrueInPosition(self, pos: int):\n return self.getAnswerInPosition(pos).isCorrect\n\n def verifyCreate(self):\n missing_parameters = []\n if self.text == None:\n missing_parameters.append(\"text\")\n if self.title == None:\n missing_parameters.append(\"title\")\n if self.position == None:\n missing_parameters.append(\"position\")\n if self.image == None:\n missing_parameters.append(\"image\")\n if len(missing_parameters) > 0:\n raise CustomError(400,\"Missing values for : \"+ ''.join([str(a) + \", \" for a in missing_parameters]))\n\n def loadFromDB(dbResult: object):\n return Question(dbResult[0], dbResult[1], dbResult[2], dbResult[3], dbResult[4], None)\n\n\nclass Participation() :\n def __init__(self, id: int, playerName: str, score: int):\n self.id = id\n self.playerName = playerName\n self.score = score\n\n def toJSON(self):\n return {\n \"id\": self.id,\n \"playerName\": self.playerName,\n \"score\": self.score\n }\n\n def verifyCreate(self):\n missing_parameters = []\n if self.playerName == None:\n missing_parameters.append(\"playerName\")\n if self.score == None:\n missing_parameters.append(\"score\")\n if len(missing_parameters) > 0:\n raise CustomError(400,\"Missing values for : \"+ ''.join([str(a) + \", \" for a in missing_parameters]))\n\n\n def loadFromDB(dbResult: object):\n return Participation(dbResult[0], dbResult[1], dbResult[2])\n","repo_name":"ruuffo/Projet-Fullstack","sub_path":"quiz-app/quiz-api/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"35784470995","text":"\"\"\"\nPython Data Structures: Tuple Example\n\nTuples are ordered, immutable collections of items. They are similar to lists, but unlike lists, tuples cannot be modified once created.\n\nIn this script, we'll create and use tuples, demonstrating their immutability and common operations.\n\nAuthor: [Your Name]\nDate: [Date]\n\"\"\"\n\nfrom typing import Tuple\nfrom typing import Set\n\n# Create a tuple of fruits with type hints\nfruits: Tuple[str, str, str] = ('apple', 'banana', 'cherry')\n\n# Access elements in a tuple\nfirst_fruit: str = fruits[0]\nprint(\"First fruit:\", first_fruit) # Output: First fruit: apple\n\n# Attempt to modify a tuple (This will raise an error)\n# fruits[0] = 'orange' # TypeError: 'tuple' object does not support item assignment\n\n# Concatenate tuples\nmore_fruits: Tuple[str, str] = ('orange', 'grape')\ncombined_fruits: Tuple[str, str, str, str] = fruits + more_fruits\nprint(\"Combined fruits:\", combined_fruits) # Output: Combined fruits: ('apple', 'banana', 'cherry', 'orange', 'grape')\n\n# Slicing tuples\nsliced_fruits: Tuple[str, str] = combined_fruits[1:3]\nprint(\"Sliced fruits:\", sliced_fruits) # Output: Sliced fruits: ('banana', 'cherry')\n\n# ==========================================================================================================\n\n\"\"\"\nPython Sets: Class Example\n\nSets are unordered collections of unique elements. In this script, we'll create a class that uses sets to manage a list of unique students' IDs.\n\nAuthor: [Your Name]\nDate: [Date]\n\"\"\"\n\n\nclass StudentDatabase:\n def __init__(self):\n \"\"\"\n Initialize an empty student database.\n \"\"\"\n self.student_ids: Set[int] = set()\n\n def add_student(self, student_id: int) -> None:\n \"\"\"\n Add a student's ID to the database.\n\n Args:\n student_id (int): The unique ID of the student to be added.\n \"\"\"\n self.student_ids.add(student_id)\n\n def remove_student(self, student_id: int) -> None:\n \"\"\"\n Remove a student's ID from the database.\n\n Args:\n student_id (int): The unique ID of the student to be removed.\n \"\"\"\n self.student_ids.discard(student_id)\n\n def get_student_ids(self) -> Set[int]:\n \"\"\"\n Get the set of unique student IDs in the database.\n\n Returns:\n Set[int]: A set of unique student IDs.\n \"\"\"\n return self.student_ids\n\n\n# Create a StudentDatabase instance\nstudent_db = StudentDatabase()\n\n# Add student IDs to the database\nstudent_db.add_student(101)\nstudent_db.add_student(102)\nstudent_db.add_student(103)\nstudent_db.add_student(104)\nstudent_db.add_student(101) # Adding a duplicate ID (won't be stored)\n\n# Remove a student from the database\nstudent_db.remove_student(103)\n\n# Retrieve the set of unique student IDs\nunique_ids = student_db.get_student_ids()\n\nprint(\"Unique Student IDs:\", unique_ids) # Output: Unique Student IDs: {101, 102, 104}\n","repo_name":"shukranjs/Python-Data-Structures","sub_path":"data_structures/tuples.py","file_name":"tuples.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"8661496992","text":"import argparse\nimport os\nfrom tqdm import tqdm\nimport chardet\nimport numpy as np\nimport torch\nfrom transformers import BertTokenizer\nfrom sklearn.metrics import classification_report\n\nfrom torch.utils.data import Dataset, random_split\nfrom dataset import VistaDataset\nfrom model import VistaNet\nfrom model2 import SentimentClassifier\nfrom train_and_eval import train_with_model, predict, eval_with_ablation\n\n\n# 通过Bert的index转换将训练集的句子列表转成index,然后用创建的类别字典将数据集的标签转成index\ndef word_tag_to_index(true_sentences, tokenizer):\n sentences = []\n for sent in true_sentences:\n sent = sent.strip(\"\\n\")\n token_sentence = [tokenizer.tokenize(word) for word in sent]\n words = [i for word in token_sentence for i in word]\n words = ['[CLS]'] + words\n sentences.append(tokenizer.convert_tokens_to_ids(words))\n\n return sentences\n\n\ndef label_to_index(label_list, type2idx):\n label_idx = []\n for label in label_list:\n label_idx.append(type2idx[label])\n\n return label_idx\n\n\ndef get_data(data_path_root, train_txt_path):\n with open(train_txt_path, 'r') as f:\n txt = f.readlines()\n data_guid_and_label = []\n for i in range(1, len(txt)):\n data_guid_and_label.append(txt[i].strip(\"\\n\"))\n\n data_id_list = []\n text_list = []\n label_list = []\n\n for data in tqdm(data_guid_and_label):\n idx = data.split(',')\n data_id_list.append(idx[0])\n label_list.append(idx[1])\n\n with open(data_path_root + idx[0] + '.txt', 'rb') as f:\n r = f.read()\n f_charInfo = chardet.detect(r)\n if f_charInfo['encoding'] is not None:\n text_list.append(r.decode(f_charInfo['encoding'], errors='ignore'))\n else:\n data_id_list.pop()\n label_list.pop()\n\n return data_id_list, text_list, label_list\n\n\nif __name__ == '__main__':\n parse = argparse.ArgumentParser()\n parse.add_argument('-do_train', type=bool, default=False, help='True:train or Flase:not')\n parse.add_argument('-do_test', type=bool, default=False, help='True:test. tips:during testing, training and verificattion are not supported')\n parse.add_argument('-do_eval_ablation', type=bool, default=False, help='True: eval')\n parse.add_argument('-ablation', type=int, default=0, help='eval type:(0: Bimodal, 1: only text, 2: only image)')\n # 以下为模型和训练过程中使用的参数\n parse.add_argument('-epoch', type=int, default=20, help='train epoch num')\n parse.add_argument('-batch_size', type=int, default=8, help='batch size number')\n parse.add_argument('-lr', type=float, default=1e-3, help='learning rate')\n opt = parse.parse_args()\n\n type2idx = {'positive': 0, 'neutral': 1, 'negative': 2}\n idx2type = {0: 'positive', 1: 'neutral', 2: 'negative'}\n\n # 加载Bert\n tokenizer = BertTokenizer.from_pretrained('pretrained_bert_models/bert-base-uncased/', do_lower_case=True)\n\n data_path_root = './dataset/data/'\n train_txt_path = './dataset/train.txt'\n test_txt_path = './dataset/test_without_label.txt'\n\n batch_size = opt.batch_size\n model = SentimentClassifier()\n\n do_train, do_eval_ablation, do_test = True, False, False\n\n if opt.do_test:\n test_data_id_list, test_text_list, test_label_list = get_data(data_path_root, test_txt_path)\n\n test_dataset_word_idx = word_tag_to_index(test_text_list, tokenizer)\n test_dataset_label_idx = [0 for i in test_label_list]\n test_dataset = VistaDataset(test_dataset_word_idx, test_data_id_list, test_dataset_label_idx, data_path_root)\n\n test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=0,\n collate_fn=test_dataset.collate_fn)\n model_path = \"train_model/best-model.pth\"\n model.load_state_dict(torch.load(model_path, map_location='cpu'), strict=True)\n predict(model, test_dataloader)\n else:\n data_id_list, text_list, label_list = get_data(data_path_root, train_txt_path)\n\n dataset_word_idx = word_tag_to_index(text_list, tokenizer)\n dataset_label_idx = label_to_index(label_list, type2idx)\n dataset = VistaDataset(dataset_word_idx, data_id_list, dataset_label_idx, data_path_root)\n\n train_dataset, eval_dataset = random_split(dataset, [(len(data_id_list) - 500), 500])\n\n train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True,\n num_workers=0,\n collate_fn=dataset.collate_fn)\n eval_dataloader = torch.utils.data.DataLoader(eval_dataset, batch_size=batch_size, shuffle=False, num_workers=0,\n collate_fn=dataset.collate_fn)\n if opt.do_train:\n # model = VistaNet(768, len(type2idx))\n\n train_with_model(model, train_dataloader, eval_dataloader, opt.epoch, opt.lr)\n if opt.do_eval_ablation:\n model_path = \"train_model/best-model.pth\"\n model.load_state_dict(torch.load(model_path, map_location='cpu'), strict=True)\n\n if opt.ablation == 0:\n eval_with_ablation(model, eval_dataloader, torch.nn.CrossEntropyLoss(), 0, 0)\n elif opt.ablation == 1:\n eval_with_ablation(model, eval_dataloader, torch.nn.CrossEntropyLoss(), 0, 1)\n elif opt.ablation == 2:\n eval_with_ablation(model, eval_dataloader, torch.nn.CrossEntropyLoss(), 0, 2)\n\n","repo_name":"songtianmin/AIProject5","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"33319887612","text":"import filecmp\nimport os\nimport docker\nfrom docker.errors import BuildError, APIError\n\nimport pytest\n\nimport mlflow\nfrom mlflow.entities import RunStatus\nfrom mlflow.projects import _project_spec\nfrom mlflow.utils.file_utils import path_to_local_sqlite_uri\n\n\nTEST_DIR = \"tests\"\nTEST_PROJECT_DIR = os.path.join(TEST_DIR, \"resources\", \"example_project\")\nTEST_DOCKER_PROJECT_DIR = os.path.join(TEST_DIR, \"resources\", \"example_docker_project\")\nTEST_PROJECT_NAME = \"example_project\"\nTEST_NO_SPEC_PROJECT_DIR = os.path.join(TEST_DIR, \"resources\", \"example_project_no_spec\")\nGIT_PROJECT_URI = \"https://github.com/mlflow/mlflow-example\"\nSSH_PROJECT_URI = \"git@github.com:mlflow/mlflow-example.git\"\n\n\ndef load_project():\n \"\"\" Loads an example project for use in tests, returning an in-memory `Project` object. \"\"\"\n return _project_spec.load_project(TEST_PROJECT_DIR)\n\n\ndef validate_exit_status(status_str, expected):\n assert RunStatus.from_string(status_str) == expected\n\n\ndef assert_dirs_equal(expected, actual):\n dir_comparison = filecmp.dircmp(expected, actual)\n assert len(dir_comparison.left_only) == 0\n assert len(dir_comparison.right_only) == 0\n assert len(dir_comparison.diff_files) == 0\n assert len(dir_comparison.funny_files) == 0\n\n\ndef build_docker_example_base_image():\n print(os.path.join(TEST_DOCKER_PROJECT_DIR, 'Dockerfile'))\n client = docker.from_env()\n try:\n client.images.build(tag='mlflow-docker-example', forcerm=True,\n dockerfile='Dockerfile', path=TEST_DOCKER_PROJECT_DIR)\n except BuildError as build_error:\n for chunk in build_error.build_log:\n print(chunk)\n raise build_error\n except APIError as api_error:\n print(api_error.explanation)\n raise api_error\n\n\n@pytest.fixture()\ndef tracking_uri_mock(tmpdir):\n try:\n mlflow.set_tracking_uri(path_to_local_sqlite_uri(os.path.join(tmpdir.strpath, 'mlruns')))\n yield tmpdir\n finally:\n mlflow.set_tracking_uri(None)\n","repo_name":"azarnyx/mlflow-sqlserver","sub_path":"tests/projects/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"37552599921","text":"import asyncio\nimport asyncpg\nfrom aiogram import types\n\nfrom data import config\nfrom keyboards.inline.news import create_button_unsubscribe\nfrom utils.db_api.big_scripts import create_tab_companies, create_tab_users, add_comp, add_user, unsubscribe, \\\n check_if_exists, count_comps, delete, all_comps, comp_subscribers, set_hash\n\n\nclass Database:\n # connecting the DB\n def __init__(self, loop: asyncio.AbstractEventLoop):\n self.pool: asyncio.pool.Pool = loop.run_until_complete(\n asyncpg.create_pool(\n user=config.PGUSER,\n password=config.PGPASSWORD,\n host=config.IP, max_inactive_connection_lifetime=3\n )\n )\n\n async def create_table_companies(self):\n await self.pool.execute(create_tab_companies)\n\n async def create_table_users(self):\n await self.pool.execute(create_tab_users)\n\n async def add_company(self, name: str):\n try:\n await self.pool.execute(add_comp, name)\n except:\n print(\"The company is in the list already\")\n\n async def add_user(self, id: int, company_name: str, user_name: str, call: types.CallbackQuery):\n # check if the user already has a subscription to the company\n num = await self.pool.fetchval(check_if_exists, id, company_name)\n if num > 0:\n await call.message.answer(\"Вы уже подписаны на новости о данной компании!\",\n reply_markup=await create_button_unsubscribe(company_name))\n return False\n # if he doesnt we provide him with a subscription\n else:\n await self.pool.execute(add_user, id, company_name, user_name)\n return True\n\n async def unsubscribe(self, id: int, company: str):\n await self.pool.execute(unsubscribe, id, company)\n num = await self.pool.fetchval(count_comps, company)\n if num == 0:\n await self.pool.execute(delete, company)\n\n async def set_hash(self, new_hash: str, id: int, company):\n await self.pool.execute(set_hash, new_hash, id, company)\n\n async def subscribers_of_the_company(self, company: str):\n return await self.pool.fetch(comp_subscribers, company)\n\n async def all_comps(self):\n return await self.pool.fetch(all_comps)\n","repo_name":"bigfoot19982/NASDAQ-NYSE-bot","sub_path":"utils/db_api/postgresql.py","file_name":"postgresql.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"28636535742","text":"mtz = [[], [], []]\nsumpar = sum3c = 0\n \nfor i in range(0, 3):\n for c in range(0, 3):\n ins = int(input(f\"Valor para [{i}, {c}]: \"))\n mtz[i].append(ins)\n\n if ins % 2 == 0:\n sumpar += ins\n\nfor i in mtz:\n sum3c += i[2]\n\nprint() # Print para formatação\nfor i in range(0, 3):\n print(f\"[{mtz[i][0]:^5}][{mtz[i][1]:^5}][{mtz[i][2]:^5}]\")\n\nprint(f\"\"\"\\nSoma de todos os valores pares: {sumpar}\nSoma dos valores da terceira coluna: {sum3c}\nMaior valor da segunda linha: {max(mtz[1])}\"\"\")\n","repo_name":"DaviAUJ/Python","sub_path":"Exercícios 3/EX087.py","file_name":"EX087.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"18255815077","text":"from django import forms\n\nsymbolfile = open(\"analyze/symbols_with_names.txt\")\nsymbolslist = symbolfile.read()\nrealsymbolslist = symbolslist.split(\"\\n\")\nstocklengthlist = []\nnewsymbolslist = zip(realsymbolslist,realsymbolslist)\n\nclass StockChoiceForm(forms.Form):\n\tstock_choice = forms.ChoiceField(label=\"\",choices=newsymbolslist)\n\n\t","repo_name":"saitadikonda48/StockChek","sub_path":"analyze/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"14660536018","text":"# Server to implement simple program to get votes tallied from two different\n# clients. The server will wait until two different clients connect, before\n# sending a message down to each client.\n# Author: Marc Grant 2019-09-26\n# Version: 0.1\n#!/usr/bin/python3\nimport random\nimport string \nimport socket\nimport sys\n\n\ndef clientACK():\n \"\"\"Generates client acknowledgment\"\"\"\n status = \"200 OK\"\n return status\n\ndef candidatesHello(str1,str2):\n \"\"\"Generates client hello message\"\"\"\n status = \"105 Candidates \"+ str1 + \",\" + str2\n return status\n\n \ndef WinnerMsg(strWinner, votes):\n \"\"\"Sends message with winner identified\"\"\"\n status = \"220 Winner. \" + strWinner + \" \" + votes\n return status\n\ndef RunnerUpMsg(strRunnerUp, votes):\n \"\"\"Sends message with runner-up identified\"\"\"\n status = \"221 Runner-up. \" + strRunnerUp + \" \" + votes\n return status\n\nklist=[11,12]\n# s = socket\n# msg = initial message being processed\n# state = dictionary containing state variables\ndef processMsgs(s, msg, status):\n \"\"\"This function processes messages that are read through the socket. It\n returns a status, which is an integer indicating whether the operation\n was successful\"\"\"\n strWinner=''\n votes=''\n runnerup=''\n Rvote=''\n \n \n status =2\n str1=\"jack\"\n str2=\"jill\"\n if msg== \"100 Hello\":\n print(\"100 Hello.\")\n \n res= candidatesHello(str1,str2)\n s.send(res.encode())\n status=1\n\n msg = msg.split('. ')\n\n if msg[0]=='110 Vote':\n print(msg[0])\n if msg[1]== 'jack':\n klist.insert(0,klist[0]+1)\n klist.remove(klist[1])\n elif msg[1] == 'jill':\n klist.insert(1,klist[1]+1)\n klist.remove(klist[2])\n ty=clientACK()\n s.send(ty.encode())\n status =1\n\n \n \n\n\n \n \n if msg[0]=='120 Poll closed':\n print(msg[0])\n \n \n if klist[0]>klist[1]:\n strWinner=str1\n votes=str(klist[0])\n runnerup=str2\n Rvote=str(klist[1])\n elif klist[1]>klist[0]:\n strWinner=str2\n votes=str(klist[1])\n runnerup=str1\n Rvote=str(klist[0])\n \n\n \n\n des=WinnerMsg(strWinner, votes)\n des1=RunnerUpMsg(runnerup, Rvote)\n # print(des)\n s.send(des.encode())\n #print(des1)\n s.send(des1.encode())\n status=-1\n\n\n\n \n\n if status==-1:\n print(\"Thanks for voting\")\n \n return status\n\ndef main():\n \"\"\"Driver function for the project\"\"\"\n args = sys.argv#['localhost',12000]\n if len(args) != 2:\n print (\"Please supply a server port.\")\n sys.exit()\n HOST = 'localhost' # Symbolic name meaning all available interfaces\n PORT = int(args[1]) # The port on which the server is listening\n if PORT < 1023 or PORT > 65535:\n print(\"Invalid port specified.\")\n sys.exit()\n \n print(\"Server of MR. Brown\") \n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n \n s.bind((HOST, PORT))# Bind socket\n s.listen(1) # listen\n print(\"Waiting for 2 connections\")\n conn, addr = s.accept()# accept connection using socket\n print(\"Client_A has connected\")\n conn1,addr = s.accept()# accept connection1 using socket\n print(\"Client_B has connected\")\n \n\n\n \n with conn,conn1:\n print('Connected by', addr)\n status = 1\n while (status==1):\n msg = conn.recv(1024).decode('utf-8')\n msg = conn1.recv(1024).decode('utf-8')\n if not msg:\n status = -1\n else:\n status = processMsgs(conn, msg, status)\n status = processMsgs(conn1, msg, status)\n if status < 0:\n print(\"Invalid data received. Closing\")\n conn.close() \n print(\"Closed connection socket\")\n\n \n\nif __name__ == \"__main__\":\n main()\n","repo_name":"marcgrant21/Client_and_Server_Python","sub_path":"vote_server.py","file_name":"vote_server.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"28190146568","text":"from google.cloud import bigquery\nimport os\n\nSERVICE_ACCOUNT_JSON = os.environ['GCP_SERV_ACC']\n\n# Construct a BigQuery client object\nclient = bigquery.Client.from_service_account_json(SERVICE_ACCOUNT_JSON)\n\n# Set table_id to the ID of the table to create\ntable_id = 'bigquery-demo-354214.dataset_py.table_py'\n\njob_config = bigquery.LoadJobConfig(\n schema = [\n bigquery.SchemaField('name', 'STRING', mode='REQUIRED'),\n bigquery.SchemaField('gender', 'STRING', mode='NULLABLE'),\n bigquery.SchemaField('count', 'INTEGER', mode='NULLABLE')\n ],\n source_format=bigquery.SourceFormat.CSV, skip_leading_rows=1\n)\n\nfile_path = r'/home/alonsmd/Downloads/names/yob1880.txt'\n\nsource_file = open(file_path, \"rb\")\n\njob = client.load_table_from_file(source_file, table_id, job_config=job_config)\n\njob.result() # Waits for the job to complete\n\ntable = client.get_table(table_id)\n\nprint(f\"Loaded {table.num_rows} rows in {table_id}. \")\n","repo_name":"alonsomedo/BigQuery","sub_path":"App/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"12821974815","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport os\nimport numpy as np\nimport copy\nfrom local.pso.pso_atoms import PsoAtoms\nfrom local.pso.Pre_Relax import PreRelax\nfrom scipy.optimize import linear_sum_assignment\n\n\nclass Pso(object):\n \"\"\"Pso object.\n\n The Pso object contains the main process of PSO.\n It must contains a list of atoms objects for optimization,a parameters\n dictionary and a calculator object for dft calculation.\n The main Pso equation:v(t+1)=w*v(t)+c1*r1*(pbest-x)+c2*r2*(gbest-x)\n The default value of this parameters is:WEIGHT=0.6,c1=c2=2,r1 and r2 is two\n seperately generated random numbers is range [0,1].\n NPAR:number of particles.It increases with the size of the system.Default\n value is 20.\n EDIFF:If the energy difference between the neighbour gbest is lower than\n it,the Pso_evolution will stop.The lower,the more precise.\n Set this parameters' value by a pso_init file or using set_parameters().\n \"\"\"\n\n def __init__(self, atoms_list=None, parameters=None, calculator=None):\n\n self.set_atoms_list(atoms_list)\n self.default_parameters={'UNF':1.,'c1':2.0,'c2':2.0,'COC':0.7298,'NPAR':150,'EDIFF':1e-4,'LSS':3,'ELIR':0.4,'WEIGHT':0.9,'GER':1,'PREX':1,'FIX2':[0],'PATH':0.01,'VMAX':0.5,'SCO':0.05,'DCO':2.,'ZMAX':[1.,1.,1],'ZMIN':[0.,0.,0.],'VAC':[0.,0.,10.],'PBC':[0,0,0],'CUO':[0.8,1.6],'LPAIR':1,'LPRELAX':1}\n if parameters is None:#Use the default value\n parameters=self.default_parameters\n if 'pso_init' in os.listdir(os.getcwd()):\n from local.pso.Read_Pso_Init import PSO_INIT\n\n self.pso_init=PSO_INIT()\n tmp=self.default_parameters\n for key in tmp.keys():\n if key in self.pso_init.parameters.keys():\n tmp[key]=self.pso_init.parameters[key]\n parameters=tmp\n self.set_parameters(parameters)\n\n if calculator is None:\n from local.pso.nnmodel import Model\n nnmodel = Model()\n self.set_calc(nnmodel)\n self.set_calc(calculator)\n\n def set_calc(self,calculator):\n self._calc=calculator\n\n def get_calc(self):\n return self._calc\n\n def set_atoms_list(self,atoms_list=None):\n self._atoms_list=[]\n if atoms_list!=None:\n for atoms in atoms_list:\n self.add_atoms(atoms)\n\n def add_atoms(self,atoms=None):\n if not isinstance(atoms,PsoAtoms):\n raise TypeError('The given atoms is not a PsoAtoms object.')\n self._atoms_list.append(atoms)\n\n def del_atoms(self,atoms=None):\n self._atoms_list.remove(atoms)\n\n def get_atoms(self):\n return self._atoms\n\n def set_parameters(self,parameters):\n if not isinstance(parameters,dict):\n raise ValueError('The given format is not a dictionary')\n a=set(parameters.keys())\n b=set(self.default_parameters.keys())\n if not a<=b:\n raise ValueError\n c=self.default_parameters\n for key in parameters.keys():\n c[key]=parameters[key]\n self._parameters=c\n\n def get_parameters(self):\n return copy.deepcopy(self._parameters)\n\n\ndef pso_evo(pso=None, natoms=None):\n from local.pso.rand_stru import RandStru\n\n \"It is the main function of Pso.\"\n import os\n import shutil\n\n def write_pso_data():\n filename='pso_data_%03d'%GER\n atoms=pso._atoms_list[0]\n f=open(filename,'w')\n f.write('System\\n')\n f.write(atoms.get_system_name())\n f.write('\\n')\n f.write('Subs Atom\\n')\n for elem in atoms._subs_elements:\n f.write(elem+' ')\n f.write('\\n')\n for num in atoms._subs_numbers:\n f.write('%3d '%num)\n f.write('\\n')\n f.write('Abso Atom\\n')\n for elem in atoms._abso_elements:\n f.write(elem+' ')\n f.write('\\n')\n for num in atoms._abso_numbers:\n f.write('%3d '%num)\n f.write('\\n')\n f.write('Lattice Constant %.16f\\n'%atoms.get_lattice_constant())\n f.write('Cell\\n')\n for i in atoms.get_cell():\n for j in i:\n f.write('%.16f '%j)\n f.write('\\n')\n f.write('Pbc ')\n for i in atoms.get_pbc():\n f.write('%d '%i)\n f.write('\\n')\n f.write('Subs Mass\\n')\n for mass in atoms.get_subs_masses():\n f.write('%.4f '%mass)\n f.write('\\n')\n f.write('Abso Mass\\n')\n for mass in atoms.get_abso_masses():\n f.write('%.4f '%mass)\n f.write('\\n')\n f.write('Subs Radius\\n')\n for radius in atoms.get_subs_radius():\n f.write('%.4f '%radius)\n f.write('\\n')\n f.write('Abso Radius\\n')\n for radius in atoms.get_abso_radius():\n f.write('%.4f '%radius)\n f.write('\\n')\n f.write('Constraints\\n')\n for i in atoms.get_constraints():\n for j in i:\n f.write('%d '%j)\n f.write('\\n')\n f.write('Subs Structure\\n')\n for atom in atoms.get_subs_positions():\n for cord in atom:\n f.write('%.16f '%cord)\n f.write('\\n')\n f.write('Pso Parameters\\n')\n for key in pso._parameters.keys():\n f.write('%s '%key)\n value=pso._parameters[key]\n if isinstance(value,list):\n for i in value:\n f.write('%.8f '%i)\n f.write('\\n')\n else:\n f.write('%.8f \\n'%pso._parameters[key])\n f.write('Calculator '+pso._calc._name+'\\n')\n f.write('!!!!!!!!!!!!!!!!!!!!!!!\\n')\n f.write(' Generation %d\\n'%GER)\n f.write('\\n')\n if GER==1:\n f.write('Last Gbest %.16f\\n'%0)\n else:\n f.write('Last Gbest %.16f\\n'%gbest[1])\n f.write('\\n&&&&&&&&&&&&&&& Number of Eliminated structures &&&&&&&&&&&&&&&\\n')\n for i in elim_list:\n f.write('%2d '%i)\n f.write('\\n\\n')\n for i1,atoms in enumerate(pso._atoms_list):\n stru=atoms.get_abso_positions()\n f.write('----------Particle %d----------\\n'%i1)\n f.write('Positions\\n')\n for atom in stru:\n for cord in atom:\n f.write('%.16f '%cord)\n f.write('\\n')\n f.write('Velocities\\n')\n for i2 in range(len(stru)):\n for v in velocities[i1,i2,:]:\n f.write('%.16f '%v)\n f.write('\\n')\n f.write(' *******************************\\n')\n f.close()\n\n def new_velocity(atoms,v,pbest,gbest,lpair):\n from math import e\n v1,v2=[],[]\n c1,c2=pso._parameters['c1'],pso._parameters['c2']\n x=pso._parameters['COC']\n w=pso._parameters['WEIGHT']\n r1=np.random.rand()\n r2=np.random.rand()\n w = 0.4 + 0.5 / GER\n if np.abs(pbest[0]-gbest[1])<=5e-2:\n w=0.25\n f2.write('x %.3f; w %.3f; c1 %.3f; c2 %.3f; r1 %.3f; r2 %.3f\\n'%(x,w,c1,c2,r1,r2))\n f2.write('Last Velocities\\n')\n for i in v:\n for j in i:\n f2.write('%.16f '%j)\n f2.write('\\n')\n temp=0\n stru=atoms.get_abso_positions(cord_mod='r')\n pbest=pbest[1].get_abso_positions(cord_mod='r')\n gbest=gbest[2].get_abso_positions(cord_mod='r')\n f2.write('Pbest\\n')\n for n in atoms.get_abso_numbers():\n dist=[atoms.get_distance(atom1,atom2)[0] for atom1 in stru[temp:temp+n] for atom2 in pbest[temp:temp+n]]\n dist=np.array(dist)\n dist=dist.reshape(n,n)\n for i in dist:\n for j in i:\n f2.write('%.16f '%j)\n f2.write('\\n')\n if lpair:\n path1=get_pair(dist)[0]\n else:\n path1=range(len(dist))\n for i in path1:\n f2.write('%d '%i)\n f2.write('\\n')\n for i,j in enumerate(path1):\n v1.append(atoms.get_distance(pbest[temp+j],stru[temp+i])[1])\n temp+=n\n v1=np.array(v1)\n f2.write('v1\\n')\n for i in v1:\n for j in i:\n f2.write('%.16f '%j)\n f2.write('\\n')\n temp=0\n f2.write('Gbest\\n')\n for n in atoms.get_abso_numbers():\n dist=[atoms.get_distance(atom1,atom2)[0] for atom1 in stru[temp:temp+n] for atom2 in gbest[temp:temp+n] ]\n dist=np.array(dist)\n dist=dist.reshape(n,n)\n for i in dist:\n for j in i:\n f2.write('%.16f '%j)\n f2.write('\\n')\n if lpair:\n path1=get_pair(dist)[0]\n else:\n path1=range(len(dist))\n for i in path1:\n f2.write('%d '%i)\n f2.write('\\n')\n for i,j in enumerate(path1):\n v2.append(atoms.get_distance(gbest[temp+j],stru[temp+i])[1])\n temp+=n\n v2=np.array(v2)\n f2.write('v2\\n')\n for i in v2:\n for j in i:\n f2.write('%.16f '%j)\n f2.write('\\n')\n f2.write('\\n')\n new_velo=x*(c1*r1*v1+c2*r2*v2)+w*v\n return new_velo\n\n init_dir=os.getcwd()\n pbest=[]\n gbest=[0,1e5,None]\n\n # initialization, generate the initial velocity randomly in the range [-0.1,0.1]\n if pso is not None:\n if not isinstance(pso, Pso):\n raise ValueError('NO Pso Object')\n ediff=pso._parameters['EDIFF']\n npar=pso._parameters['NPAR']\n c1=pso._parameters['c1']\n c2=pso._parameters['c2']\n unf=pso._parameters['UNF']\n coc=pso._parameters['COC']\n lss=pso._parameters['LSS']\n elir=pso._parameters['ELIR']\n GER=pso._parameters['GER']\n vmax=pso._parameters['VMAX']\n vac=pso._parameters['VAC']\n dis_cutoff=pso._parameters['DCO']\n lprelax=pso._parameters['LPRELAX']\n lpair=pso._parameters['LPAIR']\n ntsubs=len(pso._atoms_list[0]._subs_symbols)\n ntabso=len(pso._atoms_list[0]._abso_symbols)\n f0 = open('pso_data','a')\n f0.write('%s\\n' % pso._atoms_list[0].get_system_name())\n f0.write('Parameters\\n')\n for key in pso._parameters.keys():\n f0.write('%s '%key)\n value = pso._parameters[key]\n if isinstance(value, list):\n for i in pso._parameters[key]:\n f0.write('%.3f ' % i)\n f0.write('\\n')\n else:\n f0.write('%.3f\\n' % pso._parameters[key])\n f0.write(\"--------Substrate's Atoms' Positions:--------\\n\")\n for atom in pso._atoms_list[0].get_subs_positions():\n for cord in atom:\n f0.write('%.16f '%cord)\n f0.write('\\n')\n f0.write('**********************************\\n')\n velocities = vmax-2*vmax*np.random.rand(npar, ntabso, 3)\n dirname = 'pso_'+'001'\n if lprelax:\n PreRelax(pso, filename='pre_relax_001', dirt=init_dir)\n if dirname in os.listdir(os.getcwd()):shutil.rmtree(dirname)\n os.mkdir(dirname)\n os.chdir(dirname)\n for n, atoms in enumerate(pso._atoms_list):\n dirname1 = dirname+'_'+'%04d'%n\n if dirname1 in os.listdir(os.getcwd()):shutil.rmtree(dirname1)\n os.mkdir(dirname1)\n os.chdir(dirname1)\n pso._calc.sp_run(atoms=atoms, input_dir=init_dir)\n os.chdir('..')\n write_pso_data()\n os.chdir('..')\n else:\n # Read information from pso_data\n from local.pso.Read_Pso_Init import PSO_INIT\n pso_init=PSO_INIT()\n GER=pso_init.parameters['GER']\n\n updated = pso_init.parameters['UPDATED']\n f0=open('pso_data','a')\n os.chdir('pso_%03d'%GER)\n pso,last_gbest,last_elim=read_data(filename='pso_data_%03d'%GER)\n ediff=pso._parameters['EDIFF']\n npar=pso._parameters['NPAR']\n c1=pso._parameters['c1']\n c2=pso._parameters['c2']\n unf=pso._parameters['UNF']\n coc=pso._parameters['COC']\n lss=pso._parameters['LSS']\n elir=pso._parameters['ELIR']\n vmax=pso._parameters['VMAX']\n vac=pso._parameters['VAC']\n zmax=pso._parameters['ZMAX']\n zmin=pso._parameters['ZMIN']\n sim_cutoff=pso._parameters['SCO']\n dis_cutoff=pso._parameters['DCO']\n lprelax=pso._parameters['LPRELAX']\n lpair=pso._parameters['LPAIR']\n gen =pso._parameters['GER']\n ntsubs=len(pso._atoms_list[0]._subs_symbols)\n ntabso=len(pso._atoms_list[0]._abso_symbols)\n\n # Main Loop\n # Read information from result\n os.chdir('..')\n os.chdir('pso_%03d'%GER)\n dir_list=os.listdir(os.getcwd())\n numofupdate = 0\n numofinit = 0\n numoftest = 0\n\n for n in range(int(npar)):\n print(\"it's a {0} particle\".format(n))\n dirname = 'pso_%03d'%GER+'_%04d'%n\n os.chdir(dirname)\n\n if not updated:\n from local.optimize_cluster import structure_optimization\n from local.error_indicator import read_trajectory\n if n == 0:\n if 'update_' + str(int(GER)).zfill(3) in os.listdir(\"../\"):\n shutil.rmtree('../update_' + str(int(GER)).zfill(3))\n os.mkdir('../update_' + str(int(GER)).zfill(3))\n\n if 'updating_' + str(int(GER)).zfill(3) in os.listdir('../'):\n os.system('rm -rf ../updating_' + str(int(GER)).zfill(3))\n if 'test_store_' + str(int(GER)).zfill(3) in os.listdir('../'):\n os.system('rm -rf ../test_store_' + str(int(GER)).zfill(3))\n\n structure_optimization(filename='POSCAR', gen=GER, natoms=natoms)\n numofupdate, numofinit, numoftest = \\\n read_trajectory(gen=GER, prev_update=numofupdate, prev_init=numofinit, prev_test=numoftest, natoms=natoms)\n os.system('cp ../../../clustertut/ase_calcs/optimization.poscar ./POSCAR_pbest')\n os.system('cp ./POSCAR_pbest ../update_' + str(int(GER)).zfill(3) + '/POSCAR_' + str(n).zfill(4))\n\n energy=pso._calc.get_energy(updated=updated, num=n, gen=GER)\n pso._atoms_list[n].set_atoms_energy(energy)\n pi = [energy, pso._atoms_list[0].copy()]\n abso_stru=pso._calc.get_stru(pi[1])\n pi[1].set_abso_positions(abso_stru, cord_mod='d')\n pbest.append(pi)\n os.chdir('..')\n\n\n if updated:\n energies=[i[0] for i in pbest]\n energies=np.array(energies)\n energy_sort=np.argsort(energies)\n gbest=[energies.argmin(),energies.min(),pbest[energies.argmin()][1].copy()]\n velocities=[atoms.get_atoms_velo() for atoms in pso._atoms_list]\n velocities=np.array(velocities)\n filename='pso_data_%03d'%GER\n f2=open(filename,'r')\n f3=open('tmp','w')\n count=0\n for line in f2:\n if 'Last Gbest' in line:\n f3.write('Energies sort list\\n')\n for i in energy_sort:\n f3.write('%d %.16f\\n'%(i,energies[i]))\n if ' *******************************' in line:\n f3.write('Pbest Positions and Energy\\n')\n for i in pbest[count][1].get_abso_positions():\n for j in i:\n f3.write('%.16f '%j)\n f3.write('\\n')\n f3.write('Pbest Free Energy %.16f\\n'%pbest[count][0])\n count+=1\n f3.write(line)\n\n f3.write('----------Gbest Positions and Energy----------\\n')\n f3.write('Gbest Positions\\n')\n for i in gbest[2].get_abso_positions():\n for j in i:\n f3.write('%.16f '%j)\n f3.write('\\n')\n f3.write('Gbest Free Energy %.16f\\n'%gbest[1])\n f3.write('Gbest Number %d\\n'%gbest[0])\n f3.close()\n f2.close()\n os.rename('tmp',filename)\n os.chdir(init_dir)\n if np.abs(gbest[1]-last_gbest)>=np.abs(ediff):\n GER+=1\n pso._parameters['GER']+=1\n # Update Swarm\n f2=open('velocities_%03d'%GER,'w')\n for n,atoms in enumerate(pso._atoms_list):\n f2.write('*************** Particle %d ***************\\n'%n)\n velocities[n]=new_velocity(atoms,velocities[n],pbest[n],gbest,lpair)\n f2.close()\n #eliminate the high energy structures,and substitute them by new random structures.\n neli=int(elir*npar)\n elim_list=energy_sort[-neli:]\n surv_list=energy_sort[:-neli]\n elim_list=list(elim_list)\n\n surv_list=list(surv_list)\n\n surv_list.reverse()\n tmp1=[]\n tmp2=[]\n #if one structure is both in last_elim and elim,we do not eliminate it and keep it oen generation!\n for n in elim_list:\n if n in last_elim:\n for m in surv_list:\n if m not in last_elim:\n surv_list.remove(m)\n tmp1.append(m)\n tmp2.append(n)\n break\n if m==surv_list[-1]:\n tmp1.append(n)\n else:\n tmp1.append(n)\n elim_list=tmp1\n surv_list.extend(tmp2)\n for n in elim_list:\n atoms=pso._atoms_list[n]\n RandStru(atoms, natoms=natoms)\n velocities[n]=vmax-vmax*2*np.random.rand(ntabso,3)\n for n in surv_list:\n atoms=pso._atoms_list[n]\n stru=atoms.get_abso_positions(cord_mod='r')\n stru=stru+velocities[n]\n atoms.set_abso_positions(stru,cord_mod='r')\n #Evaluate Swarm\n if lprelax:\n PreRelax(pso,filename='pre_relax_%03d'%GER,dirt=init_dir)\n f0.write('Generation %d\\n'%GER)\n dirname='pso_'+'%03d'%GER\n if dirname in os.listdir(os.getcwd()):shutil.rmtree(dirname)\n os.mkdir(dirname)\n os.chdir(dirname)\n for n,atoms in enumerate(pso._atoms_list):\n dirname1=dirname+'_'+'%04d'%n\n if dirname1 in os.listdir(os.getcwd()):shutil.rmtree(dirname1)\n os.mkdir(dirname1)\n os.chdir(dirname1)\n pso._calc.sp_run(atoms=atoms,input_dir=init_dir)\n os.chdir('..')\n temp = pso._atoms_list\n write_pso_data()\n print('Done!')\n os.chdir('..')\n else: # energy converge\n print('COMPLETED!')\n f0.write('\\n\\n***************Energy Converged!***************\\n')\n return gbest[2]\n f0.close()\n\n\ndef read_data(filename='pso_data_001'):\n # from vasp import Vasp\n from local.pso.nnmodel import Model\n 'read information from pso-data file and return a Pso object'\n f=open(filename,'r')\n print(filename)\n data=[line.strip() for line in f ]\n count=0\n last_elim=[]\n last_gbest=0.\n for n,line in enumerate(data):\n if 'System' in line:\n system_name=data[n+1]\n continue\n if 'Subs Atom' in line:\n subs_elements=data[n+1].split()\n subs_numbers=[int(i) for i in data[n+2].split()]\n nsubs=sum(subs_numbers)\n continue\n if 'Abso Atom' in line:\n abso_elements=data[n+1].split()\n abso_numbers=[int(i) for i in data[n+2].split()]\n nabso=sum(abso_numbers)\n continue\n if 'Lattice Constant' in line:\n lattice_constant=float(line.split()[2])\n continue\n if 'Cell' in line:\n cell=[float(j) for i in range(3) for j in data[n+i+1].split()]\n continue\n if 'Pbc' in line:\n pbc=[int(i) for i in line.split()[1:]]\n if 'Subs Mass' in line:\n subs_masses=[float(i) for i in data[n+1].split()]\n continue\n if 'Abso Mass' in line:\n abso_masses=[float(i) for i in data[n+1].split()]\n continue\n if 'Subs Radius' in line:\n subs_radius=[float(i) for i in data[n+1].split()]\n continue\n if 'Abso Radius' in line:\n abso_radius=[float(i) for i in data[n+1].split()]\n continue\n if 'Constraints' in line:\n const=[int(i) for i in data[n+1].split()]\n continue\n if 'Subs Structure' in line:\n subs_positions=[float(j) for i in range(nsubs) for j in data[n+1+i].split()]\n continue\n if 'Parameters' in line:\n parameters={}\n for i in data[n+1:]:\n if 'Calculator' in i:\n calc=i\n break\n key=i.split()[0]\n a=[float(j) for j in i.split()[1:]]\n if len(a)==1 and key!='FIX2':a=a[0]\n parameters[key]=a\n cot=1\n atoms_list=[]\n while cot<=parameters['NPAR']:\n subs_symbols=[]\n abso_symbols=[]\n for i,elem in enumerate(subs_elements):\n subs_symbols.extend([elem]*subs_numbers[i])\n for i,elem in enumerate(abso_elements):\n abso_symbols.extend([elem]*abso_numbers[i])\n atoms=PsoAtoms(name=system_name,subs_symbols=subs_symbols, abso_symbols=abso_symbols,subs_positions=subs_positions, subs_masses=subs_masses,abso_masses=abso_masses,\n subs_radius=subs_radius,abso_radius=abso_radius,cell=cell,\n lattice_constant=lattice_constant,constraints=const,pbc=pbc)\n atoms_list.append(atoms)\n cot+=1\n nnmodel = Model(lattice_parameter=lattice_constant)\n pso=Pso(atoms_list=atoms_list,calculator=nnmodel,parameters=parameters)\n print('Pso Object Done!')\n print(len(pso._atoms_list))\n if 'Last Gbest' in line:\n last_gbest=float(line.split()[2])\n continue\n if 'Number of Eliminated structures' in line:\n last_elim=[int(i) for i in data[n+1].split()]\n continue\n if 'Positions' in line and 'Pbest' not in line and 'Gbest' not in line:\n abso_positions=[float(j) for i in range(nabso) for j in data[n+1+i].split()]\n pso._atoms_list[count].set_abso_positions(abso_positions)\n continue\n if 'Velocities' in line:\n velocities=[float(j) for i in range(nabso) for j in data[n+1+i].split()]\n pso._atoms_list[count].set_atoms_velo(velocities)\n count+=1\n continue\n\n #print abso_elements,abso_numbers,abso_symbols\n return pso,last_gbest,last_elim\n\n\ndef get_pair(dist):\n\n row,col=linear_sum_assignment(dist)\n return col,dist[row,col].sum()\n","repo_name":"TongheYing/ML-Au","sub_path":"local/pso/pso_sp.py","file_name":"pso_sp.py","file_ext":"py","file_size_in_byte":25362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"32756929795","text":"# Import data from CSV.\n\nimport sys, collections, csv, rtyaml\n\n# Read existing data.\nwith open(\"legislators.yaml\") as f:\n\tguide = rtyaml.load(f)\n\n# Map GovTrack IDs to indexes of existing records.\nby_govtrack_id = {\n\tperson[\"id\"][\"govtrack\"]: i\n\tfor i, person in enumerate(guide)\n}\n\n# Map bioguide IDs to GovTrack IDs.\nbioguide_to_govtrack = {\n\tp[\"id\"][\"bioguide\"]: p[\"id\"][\"govtrack\"]\n\tfor p in rtyaml.load(open(\"../congress-legislators/legislators-current.yaml\"))\n\t + rtyaml.load(open(\"../congress-legislators/legislators-historical.yaml\")) # sometimes the timing of updates is off\n}\n\n# Read the CSV data.\nfor rec in csv.DictReader(sys.stdin):\n\tif rec[\"ID\"] not in bioguide_to_govtrack:\n\t\tprint(rec)\n\t\tcontinue\n\n\t# Make a new record.\n\tp = collections.OrderedDict([\n\t\t(\"id\", { \"govtrack\": bioguide_to_govtrack[rec[\"ID\"]] }),\n\t\t(\"name\", \"{} // {}\".format(rec['First'], rec['Last'])),\n\t\t(\"ipa\", \"{} // {}\".format(rec['IPAFirst'], rec['IPALast'])),\n\t\t(\"respell\", \"{} // {}\".format(rec['RespellFirst'], rec['RespellLast'])),\n\t\t(\"notes\", rec['Notes']),\n\t])\n\n\t# Replace legislator if already exists.\n\tif p[\"id\"][\"govtrack\"] in by_govtrack_id:\n\t\tguide[by_govtrack_id[p[\"id\"][\"govtrack\"]]] = p\n\telse:\n\t\t# Otherwise append.\n\t\tguide.append(p)\n\n# Write out update.\nwith open(\"legislators.yaml\", \"w\") as f:\n\tf.write(rtyaml.dump(guide))\n\n","repo_name":"govtrack/pronunciation","sub_path":"import_from_csv.py","file_name":"import_from_csv.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"41"} +{"seq_id":"72307693564","text":"from gym_exchange.trading_environment.basic_env.assets import Action\n\n# from gym_exchange.trading_environment.utils.action_wrapper import action_wrapper\nfrom gym_exchange.trading_environment.basic_env.interface_env import State # types\nfrom gym_exchange.trading_environment.basic_env.base_env import BaseEnv\n\n\n# *************************** 3 *************************** #\nclass MemoEnv(BaseEnv):\n # ========================== 01 ==========================\n def __init__(self):\n super().__init__()\n \n # ========================== 02 ==========================\n '''for reset'''\n def initial_state(self) -> State:\n state = super().initial_state()\n self.state_memos = []\n return state\n \n # ========================== 03 ==========================\n '''for step'''\n # --------------------- 03.01 ---------------------\n def state(self, action: Action) -> State:\n state = super().state(action)\n self.state_memos.append(state)\n return state\n \n # ========================== 04 ==========================\n '''for render'''\n def render(self, mode = 'human'):\n super().render()\n \nif __name__ == \"__main__\":\n # --------------------- 05.01 --------------------- \n # from stable_baselines3.common.env_checker import check_env\n # env = MemoEnv()\n # check_env(env)\n # print(\"++++ Finish Checking the Environment\")\n # import time; time.sleep(5)\n # --------------------- 05.02 --------------------- \n env = MemoEnv()\n env.reset()\n # print(\"++++ Finish Reseting the Environment\");import time; time.sleep(5)\n # breakpoint()#$\n for i in range(int(1e6)):\n # print(\"-\"*20) #$\n # action = None\n action = Action(side = 'bid', quantity = 1, price_delta = 1)\n # print(action) #$\n # breakpoint() #$\n state, reward, done, info = env.step(action)\n # print(state) #$\n # print(reward) #$\n # print(done) #$\n # print(info) #$\n env.render()\n if done:\n print(\"++++ Encounter Done\");import time;time.sleep(5)\n # env.reset();print(\"++++ Finish Reseting the Environment\");import time;time.sleep(5)\n break #$\n # --------------------- 05.02 --------------------- \n # env = MemoEnv()\n # env.reset()\n # for i in range(int(1e6)):\n # print(\"-\"*20) #$\n # action = Action(side = 'bid', quantity = 1, price_delta = 1)\n # print(action) #$\n # # breakpoint() #$\n # state, reward, done, info = env.step(action.to_array)\n # print(state) #$\n # print(reward) #$\n # print(done) #$\n # print(info) #$\n # env.render()\n # if done:\n # env.reset()\n # break #$\n","repo_name":"KangOxford/.dotfiles","sub_path":"src/gym_exchange/more_features/features_env/memory_env.py","file_name":"memory_env.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"21687612077","text":"\n# Author - James Dickson\n\n\nfrom __future__ import print_function\n# from future.standard_library import install_aliases\n# install_aliases()\n\nfrom urllib.parse import urlparse, urlencode\nfrom urllib.request import urlopen, Request\nfrom urllib.error import HTTPError\n\nimport requests\nimport time\nimport json\nimport os\n\nfrom flask import Flask\nfrom flask import request\nfrom flask import make_response\n\n# Flask app should start in global layout\napp = Flask(__name__)\n\n\n\n@app.route('/run_bot', methods=['POST'])\ndef msg_bot():\n req = request.get_json(silent=True, force=True)\n \n if(req.get(\"queryResult\").get(\"action\") == \"AbsenceRequest\"):\n name = req.get(\"queryResult\").get(\"parameters\").get(\"name\")\n startDateEntities = req.get(\"queryResult\").get(\"parameters\").get(\"dates\").get(\"startDate\")[:10].split('-')\n startDate = startDateEntities[1] + startDateEntities[2] + startDateEntities[0]\n endDateEntities = req.get(\"queryResult\").get(\"parameters\").get(\"dates\").get(\"endDate\")[:10].split('-')\n endDate = endDateEntities[1] + endDateEntities[2] + endDateEntities[0]\n type = req.get(\"queryResult\").get(\"parameters\").get(\"type\")\n deploymentId = Deploy(startDate, endDate, type)\n r = createResp(deploymentId)\n return r\n if(req.get(\"queryResult\").get(\"action\") == \"GetStatus\"):\n status = BotStatus()\n r = createStatusResp(status)\n return r\n\n \n\n\ndef CRauth():\n authurl = \"https://aa-saleseng-use-2.my.automationanywhere.digital/v1/authentication\"\n data = {\"username\": \"james.dickson.creator\",\"password\": \"8$BCAJimmyDenve\"}\n data_json = json.dumps(data)\n headers = {'Content-Type':'application/json'}\n response = requests.post(authurl, data=data_json, headers=headers)\n output = response.json()\n #print(output)\n token = output['token']\n return token\n\ndef Deploy(startDate, endDate, type):\n token = CRauth()\n crUrl = \"https://aa-saleseng-use-2.my.automationanywhere.digital/v3/automations/deploy\"\n data = { \"fileId\": 91099, \"callbackInfo\": {}, \"runAsUserIds\": [366], \"poolIds\": [42], \"overrideDefaultDevice\": False, \"botInput\": { \"startDate\": { \"type\": \"STRING\", \"string\": startDate }, \"endDate\": { \"type\": \"STRING\", \"string\": endDate }, \"type\": { \"type\": \"STRING\", \"string\": type } }}\n data_json = json.dumps(data)\n headers = {\"Content-Type\": \"application/json\", \"X-Authorization\":token}\n response = requests.post(crUrl, data=data_json, headers=headers)\n output = response.json()\n deploymentId = output['deploymentId']\n return deploymentId\n\ndef BotStatus():\n token = CRauth()\n crUrl = \"https://aa-saleseng-use-2.my.automationanywhere.digital/v2/activity/list\"\n data = {\"sort\":[{\"field\":\"startDateTime\",\"direction\":\"desc\"}],\"filter\": {\"operator\": \"eq\", \"field\": \"fileId\", \"value\": 91099}}\n data_json = json.dumps(data)\n headers = {\"Content-Type\": \"application/json\", \"X-Authorization\":token}\n response = requests.post(crUrl, data=data_json, headers=headers)\n output = response.json()\n status = output['list'][0]['status']\n return status\n \n\ndef createResp(Id):\n speech = \"Processing your request. Your time-off request is being submitted in Workday. Your request Id is: \" + str(Id)[:3] + \". Please check back in a few moments for final confirmation. Say or type: check status of my absence request.\"\n\n my_result = {\n\n \"fulfillmentText\": speech,\n \"source\": speech\n }\n\n res = json.dumps(my_result, indent=4)\n r = make_response(res)\n r.headers['Content-Type'] = 'application/json'\n return r\n\ndef createStatusResp(status):\n if status == \"UPDATE\":\n speech = \"Your bot is working hard to complete the request in Workday. Please check back in a few moments.\"\n else:\n speech = \"The request has been successfully submitted in Workday for your upcoming absence. Is there anything else I can do for you?\"\n my_result = {\n\n \"fulfillmentText\": speech,\n \"source\": speech\n }\n\n res = json.dumps(my_result, indent=4)\n r = make_response(res)\n r.headers['Content-Type'] = 'application/json'\n return r\n\n\n@app.route('/static_reply', methods=['POST'])\ndef static_reply():\n req = request.get_json(silent=True, force=True)\n speech = \"Processing your request. Your bot has been deployed successfully!\"\n string = \"You are awesome !!\"\n Message = \"this is the message\"\n\n my_result = {\n\n \"fulfillmentText\": speech,\n \"source\": speech\n }\n\n res = json.dumps(my_result, indent=4)\n r = make_response(res)\n r.headers['Content-Type'] = 'application/json'\n return r\n\n\nif __name__ == '__main__':\n port = int(os.getenv('PORT', 5000))\n\n print(\"Starting app on port %d\" % port)\n\n app.run(debug=True, port=port, host='0.0.0.0')\n\n","repo_name":"jms-dcksn/google-assistant-a360","sub_path":"assistant-bot-backend-server.py","file_name":"assistant-bot-backend-server.py","file_ext":"py","file_size_in_byte":4797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"6821082286","text":"def all_pairs(lst):\n if len(lst) < 2:\n yield []\n return\n if len(lst) % 2 == 1:\n # Handle odd length list\n for i in range(len(lst)):\n for result in all_pairs(lst[:i] + lst[i+1:]):\n yield result\n else:\n a = lst[0]\n for i in range(1,len(lst)):\n pair = (a,lst[i])\n for rest in all_pairs(lst[1:i]+lst[i+1:]):\n yield [pair] + rest\n\ncnt1=0\ncnt2=0\nfor x in all_pairs([1,2,3,4]):\n paisi=0\n cnt1+=1\n ashche=0\n print(x,end=\" \")\n store=[]\n for i in range(len(x)):\n store.append(x[i][0])\n store.append(x[i][1])\n for i in range(len(store)):\n for j in range(i+1,len(store)):\n for k in range(j+1,len(store)):\n for l in range(k+1,len(store)):\n a=store[i]\n b=store[j]\n c=store[k]\n d=store[l]\n ashche+=1\n if(d>b and a>c):\n paisi=1\n break\n if(paisi==1):\n break\n if(paisi==1):\n break\n if(paisi==1):\n break\n if(paisi==1):\n cnt2+=1\n print(\"==>Invalid\")\n else:\n print(\"==>Valid\")\n print(ashche)\nprint(cnt1-cnt2)\n","repo_name":"rayhan50001/Additional_Codes","sub_path":"Python/split list into pairwise all possible ways..py","file_name":"split list into pairwise all possible ways..py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"3029096978","text":"\nclass Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n\n # A dictionary to store the count of occurrences for each unique element\n count_dict = {}\n\n # Count occurrences of each unique element in the array\n for num in arr:\n if num in count_dict:\n count_dict[num] += 1\n else:\n count_dict[num] = 1\n\n # Find the key with the maximum count\n max_count = 0\n max_count_key = 0\n\n for key, count in count_dict.items():\n if count > max_count:\n max_count = count\n max_count_key = key \n\n # Return the key with the maximum count\n return max_count_key\n","repo_name":"Anil-Gehlot/LeetCode-Solutions","sub_path":"1287-element-appearing-more-than-25-in-sorted-array/1287-element-appearing-more-than-25-in-sorted-array.py","file_name":"1287-element-appearing-more-than-25-in-sorted-array.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"12041051596","text":"import multiprocessing\nfrom multiprocessing import Manager, freeze_support\n\n\ndef worker(procnum, return_dict):\n '''worker function'''\n print(str(procnum) + ' represent!')\n return_dict[procnum] = procnum\n\n\nif __name__ == '__main__':\n freeze_support()\n manager = Manager()\n return_dict = manager.dict()\n jobs = []\n for i in range(5000000):\n p = multiprocessing.Process(target=worker, args=(i, return_dict))\n jobs.append(p)\n p.start()\n\n for proc in jobs:\n proc.join()\n # 最后的结果是多个进程返回值的集合\n print(return_dict.values())\n","repo_name":"FanNotFan/2019_pycharm_python_test","sub_path":"multi_progress/process_primary.py","file_name":"process_primary.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"41"} +{"seq_id":"6006362085","text":"from home.models import Product\n\n\ndef general_inventory_analysis_data(request, shop):\n\n data = {\n \"instock\": 1000, \"stockin\": 8900,\n \"stock_out\": 1000, \"inventory_turnover\": 8900,\n }\n return data\n\n\ndef top_selling_items_data(request, shop):\n data = []\n for dx in Product.objects.all():\n if dx.shop in shop:\n data.append({\n \"product_name\": dx.product_name,\n \"thumbnail\": \"\",\n \"is_out_stock\": True,\n \"total_items_sold\": 890,\n \"margin\": \"77%\",\n \"unit\": \"box\",\n \"quantity\": dx.quantity,\n })\n\n return data\n","repo_name":"Raj067/patoapp","sub_path":"patowave/home/others/api/serializers/inventory_analysis.py","file_name":"inventory_analysis.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"10197172347","text":"######################\r\n#Michael Nweke #\r\n#Student ID: 16278575#\r\n#Lab13 #\r\n######################\r\n#Import time as it will be used later in the program\r\nimport time\r\n#Define a class that takes numbers and dissplays them in a 'time format'\r\nclass Clock(object):\r\n def __init__(self, hour, minute, second, clock_type = 0):\r\n self.hour = hour\r\n self.minute = minute\r\n self.second = second\r\n self.clock_type=clock_type\r\n def __str__(self):\r\n if self.clock_type == 0:\r\n return ('{:02}:{:02}:{:02}'.format(self.hour, self.minute, self.second))\r\n else:\r\n if self.hour<12:\r\n ampm= 'am'\r\n else:\r\n ampm='pm'\r\n hour=self.hour\r\n if hour < 1:\r\n hour=12\r\n \r\n return ('{:02}:{:02}:{:02} {}'.format(self.hour, self.minute, self.second, ampm))\r\n def tick(self):\r\n self.second += 1\r\n if self.second >60:\r\n self.second = 0\r\n self.minute += 1\r\n elif self.minute > 59:\r\n self.minute = 0\r\n self.hour += 1\r\n\r\n\r\nhour=int(input('What is the current hour? ==>'))\r\nminute=int(input('What is the current minute? ==>'))\r\nsecond=int(input('What is the current second? ==>'))\r\nclock=Clock(hour,minute,second, 1)\r\nwhile True:\r\n print(clock)\r\n clock.tick()\r\n time.sleep(0.1)\r\n","repo_name":"m-nweke/ProjectsToDate","sub_path":"lab13.py","file_name":"lab13.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"904935795","text":"from .. materials.Base import EmissionChannelMaterial, BumpChannelMaterial, NormalChannelMaterial, DisplacementChannelMaterial, TransmittanceChannelMaterial, MaterialBase\n\nclass DoubleSidedThinMaterial(\n EmissionChannelMaterial,\n BumpChannelMaterial,\n NormalChannelMaterial,\n DisplacementChannelMaterial,\n TransmittanceChannelMaterial,\n \n # MaterialBase needs to be last in this list\n MaterialBase\n ):\n \n def get_format(self):\n element_name = 'double_sided_thin'\n \n fmt = {\n 'name': [self.material_name],\n 'backface_emit': [str(self.material_group.indigo_material_emission.backface_emit).lower()],\n 'emission_sampling_factor': [self.material_group.indigo_material_emission.em_sampling_mult],\n element_name: {\n 'ior': [self.property_group.ior],\n 'front_roughness': {\n 'constant': [self.property_group.front_roughness]\n },\n 'back_roughness': {\n 'constant': [self.property_group.back_roughness]\n },\n 'r_f': {\n 'constant': [self.property_group.r_f]\n },\n 'front_fresnel_scale': {\n 'constant': [self.property_group.front_fresnel_scale]\n },\n 'back_fresnel_scale': {\n 'constant': [self.property_group.back_fresnel_scale]\n },\n 'front_material_name': [self.property_group.front_material_index],\n 'back_material_name': [self.property_group.back_material_index],\n }\n }\n \n fmt[element_name].update(self.get_channels())\n \n return fmt\n","repo_name":"glaretechnologies/blendigo","sub_path":"sources/indigo_exporter/export/materials/DoubleSidedThin.py","file_name":"DoubleSidedThin.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"41"} +{"seq_id":"18385596908","text":"# Library includes\nimport os\nimport argparse\nfrom topgisviz.mosaic_generator import process\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-c\",\n \"--config\",\n help=\"Path to the config file.\"\n )\n\n args = parser.parse_args()\n config = args.config\n\n process(config) # Calls the function(fle) process.py from mosaic_generator\n # Pass the config file to the function\n\"\"\"\nTopGIS Dataset Visualization\n\nIn this assignment, you will work with satellite images downloaded along a GPS route from TopGIS service. You can download the dataset here: http://download.mykkro.cz/valeo/route.zip .\n\n1. Create a new Python module (package) named topgis-viz. This module will have this basic directory structure:\n\ntopgis-viz/\n config/ # this will contain your YAML configuration files (if any is necessary)\n config.yaml # a default configuration file\n data/ # unpack the dataset into this directory (so it contains a subdirectory named topgis with images)\n target/ # this folder will contain all of your outputs\n topgisviz/ # this folder will contain the module code\n __init__.py\n # all the other stuff\n setup.py # the setup script for the package\n requirements.txt\n README.md # a documentation page, with a short description of the module and usage instructions\n topgis-test.py\n .gitignore # don't forget to .gitignore data/ and target/ folders\n\nYou will use the module by calling it from command line as follows:\n\npython topgis-test.py [--config=config/config.yaml]\n\nThe --config parameter is optional, if not used, the default value config/config.yaml will be used. Use argparse library to read the command line arguments, like this:\n\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-c\",\n \"--config\",\n help=\"Path to the config file.\"\n )\n\n args = parser.parse_args()\n config = args.config\n\nWhen run, this script will read the configuration file in YAML format (read about YAML here: https://yaml.org/) into a Python dictionary. You can use this code:\n\ndef load_yaml(yaml_path):\n with open(yaml_path, \"r\", encoding=\"utf-8\") as infile:\n return yaml.load(infile, Loader=yaml.FullLoader)\n\nThe configuration file will look similarly to this:\n\n# configuration file for topgis-viz\n\n# glob pattern for finding the source files\nsources: \"data/topgis/utm_*.jpg\"\noutput_dir: \"target/mosaic/\"\nmosaic:\n columns: 5\n rows: 2\n cell_width: 250\n cell_height: 250\npipeline:\n - \"A0 = src\"\n - \"A1 = greyscale A0\"\n - \"A2 = red A0\"\n - \"A3 = green A0\"\n - \"A4 = blue A0\"\n - \"B0 = equalized A0\"\n - \"B1 = equalized_greyscale A1\"\n - \"B2 = equalized A2\"\n - \"B3 = equalized A3\"\n - \"B4 = equalized A4\"\n\nThese parameters govern what the script will do with the images. The script will:\n\n get a list of available images (based on sources parameter, via glob.glob function) and sort it alphabetically in increasing order\n iterate over the list of images and for each of those source images:\n create an empty RGB image with specified number of cells (rows, columns)\n the cells of the grid are denoted by letter-number code indicating column and row. E.g. A0 is top-left cell.\n run a processing pipeline on the source image. The pipeline is defined by a list of strings, which are evaluated in sequence. The format of each string is as follows: CELL = FUNCTION [ARGS]. E.g. string B0 = equalized A0 means that cell B0 of the grid will be filled with an image that comes as result of calling image function equalized on an image in cell A0.\n the original size of the images is 1000x1000 pixels. Do the pipeline operations on images with this original size. Resize the images (to cell_width * cell_height) only when putting them into the big mosaic image.\n the result of the pipeline will be stored in the specified output directory as a JPG image (Use this naming pattern: f\"{index:05}.jpg\").\n\nThe following pipeline functions should be supported:\n\n src - just the source image\n greyscale RGB_IMAGE - returns a greyscale image constructed from RGB_IMAGE\n red RGB_IMAGE - returns a color image that contains only red channel\n green RGB_IMAGE - returns a color image that contains only green channel\n blue RGB_IMAGE - returns a color image that contains only blue channel\n equalized RGB_IMAGE - returns a color image with equalized intensities\n equalized_greyscale BW_IMAGE - returns a greyscale image with equalized intensities\n\nMost of the functions should be easy to implement. For equalization of colored images, use this function:\n\ndef equalize_histogram_rgb(rgb_img):\n # convert from RGB color-space to YCrCb\n ycrcb_img = cv2.cvtColor(rgb_img, cv2.COLOR_BGR2YCrCb)\n\n # equalize the histogram of the Y channel\n ycrcb_img[:, :, 0] = cv2.equalizeHist(ycrcb_img[:, :, 0])\n\n # convert back to RGB color-space from YCrCb\n equalized_img = cv2.cvtColor(ycrcb_img, cv2.COLOR_YCrCb2BGR)\n\n return equalized_img\n\nThe cv2.equalizeHist function can be used for equalization of black and white images.\n\nRunning this script should result with the target/mosaic directory populated with 624 of JPEG images named 00000.jpg to 00623.jpg. Each of these images should be 1250 pixels wide and 500 pixels high and contain a mosaic of images, first row containing original, greyscale, red, green and blue images and the second row should contain the equalized versions of these images.\n\"\"\"","repo_name":"ArakelTheDragon/Library_Python","sub_path":"satelite-viz/topgis-test.py","file_name":"topgis-test.py","file_ext":"py","file_size_in_byte":5589,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"3284359149","text":"# find all the Game objects in here\n\n# import project modules\nfrom .spells import *\nfrom global_utilites.utilits import in_rect, define_rect\nfrom objects.statics.static_areas import WALLS\nfrom settings.global_constants import window_heigth, window_width\n\n# TODO: Create exchangeable spell casts\n\n\nclass Player:\n\n def __init__(self, x, y, width, height, color, attributes, player_id):\n self.id = player_id\n self.x = x # defines position on x-axis\n self.y = y # defines position on y-axis\n self.target = (self.x, self.y) # This is the goal (x, y) coordinate\n\n self.width = width # defines the width of the character\n self.height = height # defines the height of the character\n self.color = color # defines the color of the player rectangle\n self.rect = (x, y, width, height) # defines the rectangle as player object defined height*width\n self.speed = 50 * 60/1000\n self.x_vel = 0 # defines the speed of the object when pressing key\n self.y_vel = 0 # defines the speed of the object when pressing key\n\n self.direction = 0 # defines in which the direction the player is going\n self.spells = [] # includes all spells created for the character\n self.walk_count = 0 # keeps track of the steps - needed for the sprites\n\n # this defines the player conditions\n self.start_health = attributes[0]\n self.health = attributes[0]\n\n self.magic = attributes[1]\n self.magic_available = attributes[1]\n self.hitbox = (self.x + 20, self.y + 10, 60, 100)\n self.aim_mode = [False, 0]\n self.spell_collection = {1: Stupor(round(self.x + self.width // 2), round(self.y + self.height // 2), 6, (0, 255, 0), 1, self.id)}\n\n def draw(self, win):\n pygame.draw.rect(win, self.color, self.rect)\n\n def update_spell(self):\n \"\"\"\n This function loop over all existing spells the player has casted and removes them the list\n whenever the attribute damage_dealt was set to True. The update happens within the main loop\n of the client. Nevertheless has the spell to be removed on the player object. In case the spell\n did not hit an enemy object, it will be removed when it leave the battlefield.\n :return: None - it does have a return value\n \"\"\"\n\n # loop over all objects in the spells list\n for spell in self.spells:\n\n # remove the spell form the list, in case it dealt damage to an enemy - spell is not needed anymore\n if spell.damage_dealt:\n self.spells.pop(self.spells.index(spell))\n\n # remove the spell in case it did not hurt anyone but is also outside of the battlefield\n if (spell.x > window_width) or (spell.x < 0) or (spell.y > window_heigth) or (spell.y < 0):\n self.spells.pop(self.spells.index(spell))\n\n def update(self):\n \"\"\"\n This function updates important counts and minor parts. Is starts with the rectangle position of the player.\n However, it will also return the walk count to zero is case it reached the limit of 4. This is important,\n because the spites only count to 4 and it would return an index out of range error. Also the function checks\n for the current spells and returns the magic load.\n :return: None. The function has no need to return a value\n \"\"\"\n # update the players rectangle position which is the baseline for displaying and moving the player object\n self.rect = (self.x, self.y, self.width, self.height)\n\n # set the walk count back in case it reached the index limit\n #if self.walk_count + 1 >= 4:\n # self.walk_count = 0\n\n # check if spells need to be removed from the spells list\n self.update_spell()\n\n # fill up the magic energy\n if self.magic_available < self.magic:\n self.magic_available += 1\n\n def cast_spell(self, spell_to_cast):\n \"\"\"\n This function simply takes a spell object and appends it to the spells list.\n However, it will also reduce the magic by the magic costs of the spell\n :param spell_to_cast: (object): the spell which needs to be append to the list\n :return: None - The function needs no return value\n \"\"\"\n self.spells.append(spell_to_cast)\n self.magic_available -= spell_to_cast.magic_cost\n\n def hit(self, damage):\n \"\"\"\n In case the player was hit by an enemy spell the function will reduce the players health by the dealt damage.\n Be aware, that this function will only be called in the main loop of the client. The dealt damage depends\n on the spell of the enemy\n :param damage: (int): Number of health by which the players health gets reduced\n :return: None - Function needs no return value\n \"\"\"\n if self.health > 0:\n self.health -= damage\n\n def get_direct_indicators(self):\n \"\"\"\n This function creates to parameters which will be indicators for the direction of the movement.\n Therefore a parameter will be 1 or -1. 1 indicates a movement in the positive direction, while -1 stands\n for the negative case. This is calculated for the x and y coordinate.\n\n :return: (tuple): with two values (x, y). Both will be default 1. But can have 1 or -1 as explained above\n \"\"\"\n\n # create a pair of x and y values: e.g[(x start, x goal), (y start, y goal)]\n coordinate_pairs = list(zip([self.x, self.y], list(self.target)))\n\n # set return values with default value\n xd, yd = 1, 1\n\n # loop through both pairs of coordinates\n for coordinate in coordinate_pairs:\n\n # get index of coordinate pairs to decide if x or y axis is relevant\n ix = coordinate_pairs.index(coordinate)\n\n # check if distance between points is not zero and if x or y has to be updated\n if ((coordinate[1] - coordinate[0]) != 0) and (ix == 0):\n\n # calculate the distance and devide by the abs of distance to get 1 with the positive or negative sign\n xd = (self.target[0] - self.x)/abs((self.target[0] - self.x))\n\n # same as above but just for y\n if ((coordinate[1] - coordinate[0]) != 0) and (ix == 1):\n yd = (self.target[1] - self.y)/abs((self.target[1] - self.y))\n\n return xd, yd\n\n def update_aim_mode(self):\n \"\"\"\n This function creates a lane which indicates the direction in which a spell will fly. This is supports the\n to aim in the right direction. This means that the player will not be able to choose a new direction to walk\n to as long as the aim mode is on. The lane points into the direction of the mouse cursor.\n :return:\n \"\"\"\n pass\n\n def update_key_presses(self):\n \"\"\"\n This function updates all pressed keys. This is relevant to cast new spells and to check for\n player actions beside the movement.\n\n :return: Does not return anything\n \"\"\"\n\n # keys is a list of keys and if they are pressed the value will be a one\n keys = pygame.key.get_pressed()\n\n if keys[pygame.K_s]:\n if self.magic_available >= self.spell_collection[1].magic_cost:\n self.aim_mode = [True, 1]\n\n def move(self):\n \"\"\"\n This function handles the whole movement behavior of the player and is therefore pretty important for the whole\n game. In a nutshell do we compare the starting vector with the end vector. The speed is set by the speed\n attribute. This get multiplied with the x and y velocity for each data point x and y. But before that we\n create an direction indicator to observe the behavior of the movement.\n\n At the end we just update all other behaviors as well, like health, magic, walk count, hitbox and key presses\n which lead to casting spells.\n\n :return: Does not return anything\n \"\"\"\n\n # this is meant to calculate the direction of the movement\n xd, yd = self.get_direct_indicators()\n\n # check if the target is already reached and if the distance is larger then a movement\n if (self.target[0] - self.x) != 0 and abs(self.target[0] - self.x) > self.x_vel:\n\n # check if increasing the step size would lead to a violation of a walls territory via boolean map\n wall_map = [in_rect(((self.x + xd * self.x_vel), self.y), w.rect) for w in WALLS]\n print(wall_map)\n if not all(wall_map):\n\n # update the current x position with predefined movement * direction indicator\n # x_vel gets predefined in the client for each new target vector\n self.x += xd * self.x_vel\n\n # update the walk count this you moved in this function\n # self.walk_count += 1\n\n # in case the distance is smaller then one move, just return the rest of the distance\n else:\n self.x += (self.target[0] - self.x)\n # self.walk_count += 1\n\n # same as above but just for the y coordinate\n if (self.target[1] - self.y) != 0 and abs(self.target[1] - self.y) > self.y_vel:\n\n # check if increasing the step size would lead to a violation of a walls territory via boolean map\n wall_map = [in_rect(((self.x + xd * self.x_vel), self.y), define_rect(w.rect)) for w in WALLS]\n if not all(wall_map):\n self.y += yd * self.y_vel\n # self.walk_count += 1\n\n else:\n self.y += (self.target[1] - self.y)\n # self.walk_count += 1\n\n # update the hitbox. It is important to move the hitbox with the player. So the player can be damaged.\n self.hitbox = (self.x + 20, self.y + 10, 28, 50)\n\n # update other key presses for castings portions and so on\n self.update_key_presses()\n\n # update the player attributes\n self.update()\n\n\n\n\n\n\n","repo_name":"Perledition/DarkArts","sub_path":"objects/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":10049,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"41"} +{"seq_id":"39998740758","text":"# question https://atcoder.jp/contests/tessoku-book/tasks/tessoku_book_bp\n# answer https://github.com/E869120/kyopro-tessoku/blob/main/codes/python/chap09/answer_A68.py\n\n# 教訓\n\n# 参考HP:\n# https://www.momoyama-usagi.com/entry/math-risan15\n\n# 用語解説\n# 深さ優先探索:「とにかく行けるとこまで行ってそれ以上進めなくなったら一歩戻ってそこから探索する」という探索方法。\n# 幅優先探索とは「出発点に近い点から順に探索する」という探索方法。\n\n# 最大フロー用の辺の構造体 ※残余グラフ作成のための値を格納\nclass maxflow_edge:\n def __init__(self, to, cap, rev):\n self.to = to # A→Bとすると,Bを示す。\n self.cap = cap # capacity:流せる残りの容量を示す\n self.rev = rev # reverse: 逆辺の頂点を示す。\n # 1 → 2の場合、行先である頂点2の隣接リストG[2]の何番目に1が入っているかを返す。\n\n\n# 深さ優先探索\n# pos:positionの略。行き先を示す。F:増加道の容量 G:隣接リスト used:訪問済みフラグリスト\ndef dfs(pos, goal, F, G, used):\n if pos == goal:\n return F # ゴールに到着:フローを流せる!\n # 探索する\n used[pos] = True # used[各頂点]:深さ優先探索で訪問済みか否かを示すフラグのリスト。\n for e in G[pos]:\n # 容量が 1 以上でかつ、まだ訪問していない頂点にのみ行く\n if e.cap > 0 and not used[e.to]:\n flow = dfs(e.to, goal, min(F, e.cap), G, used)\n # フローを流せる場合、残余グラフの容量を flow だけ増減させる\n if flow >= 1:\n e.cap -= flow\n G[e.to][e.rev].cap += flow\n return flow\n # すべての辺を探索しても見つからなかった…\n return 0\n\n\n# 頂点 s から頂点 t までの最大フローの総流量を返す(頂点数 N、辺のリスト edges)\ndef maxflow(N, s, t, edges):\n # 初期状態の残余グラフを構築\n # (ここは書籍とは少し異なる実装をしているため、8 行目は G[a] に追加された後なので len(G[a]) - 1 となっていることに注意)\n G = [list() for i in range(N + 1)]\n # G(隣接リスト)内に残余グラフに必要な値を入れてい���\n for a, b, c in edges: # lenの解釈:revは隣接している頂点の隣接しているノードの数\n G[a].append(maxflow_edge(b, c, len(G[b]))) # a → b の矢印\n G[b].append(maxflow_edge(a, 0, len(G[a]) - 1)) # b → a の矢印\n\n # ※maxflow_edgeの第三引数 lenの解釈\n # len(G[b])は逆辺の頂点であるbの隣接リスト内にaが何番目に来るかを示す。\n # aは直後にG[b]隣接リスト内へ追加されるため、最後の要素になるはず。→ 隣接リストの長さで要素番号を取得\n # bも同様に最後の要素になるはず。しかし直前にG[a]隣接リスト内へ追加されたため、要素番号はlen-1.\n\n # (a, b, c) = (1, 2, 5)の時のG\n # G: [[], [<__main__.maxflow_ed...093FFD210>], [<__main__.maxflow_ed...0948C0890>], [], [], [], []]\n # Gの中にはmaxflow_edgeクラスで生成されたインスタンスがそれぞれリストの中に格納される。\n # G[1]: [<__main__.maxflow_ed...093FFD210>] ※リスト内にインスタンスが格納されている点に注意\n # G[1][0]: <__main__.maxflow_ed...093FFD210>\n # ・G[1][0].to: 2 ・G[1][0].cap: 5 ・G[1][0].rev: 0 ※1 → 2のフローを示す\n # ・G[2][0].to: 1 ・G[2][0].cap: 0 ・G[2][0].rev: 0 ※2 → 1のフローを示す\n\n INF = 10**10 # フローが流せなくなるごとにdfsで0が返る。F=0になるまで繰り返すのでINFの初期値は無限大にしておく。\n # Fは深さ優先探索にてmin(F, e.cap)となり、どんどん小さい値へ更新されていく。→初期値は無限大にしておく。\n total_flow = 0\n while True:\n used = [False] * (N + 1)\n F = dfs(s, t, INF, G, used)\n if F > 0:\n total_flow += F\n else:\n break # フローを流せなくなったら、操作終了\n return total_flow\n\n\n# 入力\nN, M = map(int, input().split())\nedges = [list(map(int, input().split())) for i in range(M)]\n# print(edges)\n# 出力結果: [[1, 2, 5], [1, 4, 4], [2, 3, 4], [2, 5, 7], [3, 6, 3], [4, 5, 3], [5, 6, 5]]\n\n# 答えを求めて出力\nanswer = maxflow(N, 1, N, edges)\nprint(answer)\n","repo_name":"usma11dia0/training_of_atcoder","sub_path":"kyopro-tessoku/chap09/submit_a68_maximum_flow.py","file_name":"submit_a68_maximum_flow.py","file_ext":"py","file_size_in_byte":4639,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"} +{"seq_id":"24354410830","text":"\nimport random\n\ndef random_zn_star(n):\n # r in Zn* i.e. gcd(r,n) =1\n r = random.randint(2, n-1)\n while xgcd(r,n)[0] != 1:\n r = random.randint(2, n-1)\n return r\n\ndef xgcd(a, b):\n # Function return (gcd, x, y)\n if a == 0:\n return b, 0, 1\n if b == 0:\n return a, 1, 0\n x2, x1, y2, y1 = 1, 0, 0, 1\n while b > 0:\n q = a/b\n x = x2 - q * x1\n y = y2 - q * y1\n a, b = b, a%b\n x2, x1, y2, y1 = x1, x, y1, y\n return a, x2, y2\n\ndef modinv(a, n):\n g, x, y = xgcd(a, n)\n if g != 1:\n return None\n return x % n\n\ndef rsa_sign(n, d, msg):\n return pow(msg, d, n)\n\ndef rsa_msg_blind(n, e, msg):\n r = random_zn_star(n)\n return (pow(r, e, n)*msg)%n, r\n\ndef rsa_blind_sign(r, n, s):\n return (s*modinv(r,n))%n\n\ndef rsa_commod(n, e1, c1, e2, c2):\n '''\n RSA Common modulus attack with gcd(e1, e2) == 1\n '''\n _, x, y = xgcd(e1, e2)\n if x < 0:\n c1, x = modinv(c1, n), x*(-1)\n elif y < 0:\n c2, y = modinv(c2, n), y*(-1)\n if (not c1) or (not c2):\n return 'MODINV Error!'\n m = (pow(c1, x, n) * pow(c2, y, n))%n\n return str(m)","repo_name":"PhoeniXkrypT/CryptoUtils","sub_path":"utils/crack.py","file_name":"crack.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"41"}