diff --git "a/4959.jsonl" "b/4959.jsonl" new file mode 100644--- /dev/null +++ "b/4959.jsonl" @@ -0,0 +1,629 @@ +{"seq_id":"452016138","text":"class UF:\n def __init__(self,N):# create a set of nodes and initialize them with incremental numbers\n self.parent = {} # parent of each node\n self.sz = {} # size of each tree\n \n def find(self,p,q): # is node p connected to node q?\n return self.root(p) == self.root(q)\n \n def union(self,p,q): # connect node p and q \n rootp,rootq = self.root(p),self.root(q) \n if self.sz[rootp] <= self.sz[rootq]: # always link the smaller tree's root to the larger tree's root\n self.parent[rootp] = rootq # connect p's root to q's root\n self.sz[rootq] = self.sz[rootq]+self.sz[rootp]\n else:\n self.parent[rootq] = rootp # connect q's root to p's root\n self.sz[rootp] = self.sz[rootp]+self.sz[rootq] \n \n def root(self,p): # which node is the root of node p?\n if p not in self.parent:\n self.parent[p] = p\n self.sz[p] = 1\n else:\n old_p = p\n while self.parent[p] != p:\n p = self.parent[p]\n self.parent[old_p] = p # compress path\n return self.parent[p]\n","sub_path":"UnionFind.py","file_name":"UnionFind.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"21828206","text":"import numpy as np\nfrom scipy.io import loadmat\nimport matplotlib.pyplot as plt\n\nfigname = '../../fig/EDF/TI_baseflow.pdf'\nprintfig = True\nfigwidth = 12/2.54\nfigaspect = 2.2\nu_ref = 0.55\nwidth = 1.5\nheight = 0.8\n\nlevels = np.linspace(4., 12, 25)\ncolormap = 'hot_r'\n\ndatafile = '../../data/EDF_exp/Data/Baseflow/U1TI0.mat'\ndata = loadmat(datafile)\n\ny = data['flow'][0]['Z'][0]\nz = data['flow'][0]['Y'][0]\nu = data['flow'][0]['u_bar'][0]\nv = data['flow'][0]['w_bar'][0]\nw = data['flow'][0]['v_bar'][0]\nTI = data['flow'][0]['TI'][0]\n\nplt.close('all')\nplt.rcParams['text.usetex'] = printfig\nplt.figure(figsize=(figwidth, figwidth/figaspect))\nhcont = plt.contourf(y/width, z/height, TI, levels, cmap=colormap)\nQ = plt.quiver(y/width, z/height, v/u_ref, w/u_ref)\n\nh_ax = plt.colorbar(hcont)\nh_ax.set_ticks([5, 7.5, 10])\nh_ax.set_label(r'$TI$ [\\%]')\n\nplt.xlabel(r'$y/s$')\nplt.ylabel(r'$z/h$')\n\nplt.xlim(-0.5, 0.5)\nplt.ylim(0., 1)\nplt.tight_layout(pad=0.25)\nplt.show()\n\nif printfig==True:\n plt.savefig(figname)\n","sub_path":"methods/script/baseflow/TI_baseflow.py","file_name":"TI_baseflow.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"453701285","text":"from django.shortcuts import render, redirect, HttpResponse\nfrom django.http import Http404\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.conf import settings\nfrom django.core.files.storage import FileSystemStorage\nfrom django.contrib import messages\nfrom base.models import Patient, Scan\nfrom subprocess import call\nfrom threading import Thread, active_count\nfrom django.conf import settings\nimport pdb\nimport sys\nimport os\nfrom io import BytesIO\nfrom glob import glob\nimport json\nimport zipfile\nimport requests\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\n\n# sys.path.append(os.path.abspath('BraTS'))\n# from BraTS import testBraTS\n\nDL_SERVER = settings.DL_SERVER\n\n\ndef extract_zip(zipscanpath):\n scan_id = zipscanpath.split(\"/\")[-1].split(\".\")[0]\n patient_id = zipscanpath.split(\"/\")[-2]\n extraction_path = os.path.join(\"files/scans\", patient_id, scan_id)\n with zipfile.ZipFile(zipscanpath, \"r\") as zip_ref:\n zip_ref.extractall(extraction_path) # footnote 1\n\n\n@login_required(login_url=\"/login\")\ndef index(request):\n patients = Patient.objects.filter(doctor=request.user)\n context = {\"patients\": patients}\n return render(request, \"patient_list.html\", context)\n\n\ndef postScan(scan):\n \"\"\"Post scan to DL_server\"\"\"\n scanpath = scan.file.path\n patient_id = scan.patient.id\n data = {\"patient_id\": patient_id}\n url = DL_SERVER + \"postScans\"\n with open(scanpath, \"rb\") as scans:\n r = requests.post(url, files={\"scans\": scans}, params=data)\n print(r.status_code)\n response = json.loads(r.text)\n if response[\"success\"]:\n print(\"Scan post Successful!\")\n else:\n print(\"Error in posting scans\")\n\n\ndef itkSnap(request, patient_id, scan_id):\n if request.user.is_authenticated:\n patient = Patient.objects.get(id=patient_id)\n scan = Scan.objects.get(patient=patient, scan_id=scan_id)\n patient_id = scan.patient.id\n scan_id = scan.scan_id\n file = glob(\"files/scans/%s/%s/*t1ce.nii.gz\" % (patient_id, scan_id))[0]\n t1file = glob(\"files/scans/%s/%s/*t1.nii.gz\" % (patient_id, scan_id))[0]\n t2file = glob(\"files/scans/%s/%s/*t2.nii.gz\" % (patient_id, scan_id))[0]\n flairfile = glob(\"files/scans/%s/%s/*flair.nii.gz\" % (patient_id, scan_id))[0]\n\n if scan.seg_file:\n seg_file = scan.seg_file.path\n cmd = \"itksnap -g %s -s %s -o %s %s %s -l %s\" % (\n file,\n seg_file,\n t1file,\n t2file,\n flairfile,\n \"files/labels.txt\",\n )\n else:\n cmd = \"itksnap -g %s\" % file\n out = call(cmd.split())\n return HttpResponse(\"Done\")\n else:\n raise Http404()\n\n\n@login_required(login_url=\"/login\")\ndef patientsView(request, pid):\n try:\n patient = Patient.objects.get(id=pid)\n # scan = Scan.objects.filter(patient=patient)[0]\n # Thread(target=postScan, args=(scan,)).start()\n\n except Exception as e:\n raise Http404(e)\n if request.method == \"POST\" and request.FILES[\"scans\"]:\n patient_id = patient.id\n files = request.FILES.getlist(\"scans\")\n bytes_obj = BytesIO()\n zf = zipfile.ZipFile(bytes_obj, \"w\")\n\n for file in files:\n fpath = file.temporary_file_path() # django stores them at /tmp\n fname = file.name\n zf.write(fpath, fname)\n zf.close()\n tempzipfile = InMemoryUploadedFile(\n file=bytes_obj,\n field_name=None,\n name=\"lol\",\n content_type=\"application/zip\",\n size=bytes_obj.__sizeof__(),\n charset=None,\n )\n description = request.POST.get(\"description\", None)\n scan = Scan.objects.create(\n patient=patient, file=tempzipfile, description=description\n )\n Thread(target=postScan, args=(scan,)).start()\n Thread(target=extract_zip, args=(scan.file.path,)).start()\n return redirect(\"/patients/%s\" % pid)\n patient = Patient.objects.get(id=pid)\n scans = Scan.objects.filter(patient=patient)\n context = {\"patient\": patient, \"scans\": scans}\n return render(request, \"patient_profile.html\", context)\n\n\ndef loginView(request):\n if request.user.is_authenticated:\n return redirect(\"/\")\n if request.method == \"POST\":\n username = request.POST[\"username\"]\n password = request.POST[\"password\"]\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n messages.add_message(request, messages.INFO, \"Login Successful!\")\n return redirect(\"/\")\n else:\n messages.add_message(request, messages.INFO, \"Invalid Login Credentials!\")\n return render(request, \"login.html\")\n\n\ndef editPatientProfile(request):\n try:\n if request.method == \"POST\":\n patient_id = request.POST[\"patient_id\"]\n patient = Patient.objects.get(id=patient_id)\n patient.name = request.POST[\"name\"]\n patient.email = request.POST[\"email\"]\n patient.age = request.POST[\"age\"]\n patient.gender = request.POST[\"gender\"]\n patient.address = request.POST[\"address\"]\n patient.mobile_number = request.POST[\"mobile_number\"]\n patient.description = request.POST[\"description\"]\n patient.save()\n print(\"Updated profile\")\n return redirect(\"/patients/%s\" % patient_id)\n except Exception as e:\n print(e)\n return redirect(\"/\")\n\n\ndef newPatient(request):\n if request.method == \"POST\":\n print(request.POST)\n print(request.FILES)\n # pdb.set_trace()\n doctor = request.user\n name = request.POST['name']\n gender = request.POST['gender']\n age = request.POST['age']\n mobile_number = request.POST['mobile_number']\n description = request.POST['description']\n picture = request.FILES['picture']\n email = request.POST['email']\n patient = Patient.objects.create(\n doctor=doctor,\n name=name,\n gender=gender,\n age=age,\n mobile_number=mobile_number,\n description=description,\n picture=picture,\n email=email\n )\n print(patient)\n return redirect('/')\n return render(request, 'new_patient.html')\n\n\n@login_required(login_url=\"/login\")\ndef logoutView(request):\n logout(request)\n messages.add_message(request, messages.INFO, \"Logout Successful!\")\n return redirect(\"/\")\n","sub_path":"local/base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"289379535","text":"from __future__ import division\nfrom builtins import str\nfrom builtins import range\nfrom past.utils import old_div\nimport unittest\nimport numpy as np\nimport pandas as pd\nfrom sklearn.feature_selection import chi2\nfrom kmerprediction.feature_selection import variance_threshold, remove_constant\nfrom kmerprediction.feature_selection import select_k_best, select_percentile\n\n\nclass VarianceThreshold(unittest.TestCase):\n def setUp(self):\n self.classes = 3\n x_train = np.random.randint(15, size=(12, 6))\n y_train = np.random.randint(self.classes, size=(12))\n x_test = np.random.randint(15, size=(12, 6))\n y_test = np.random.randint(self.classes, size=(12))\n self.data = [x_train, y_train, x_test, y_test]\n self.threshold = 0.75 * x_train[0][0].var()\n train_df = pd.DataFrame(x_train)\n test_df = pd.DataFrame(x_test)\n train_df = train_df.drop(train_df.var()[train_df.var() <\n self.threshold].index.values, axis=1)\n test_df = test_df[train_df.columns]\n new_x_train = train_df.values\n new_x_test = test_df.values\n self.correct_data = [new_x_train, y_train, new_x_test, y_test]\n self.new_data, self.fn, self.fa = variance_threshold(self.data, None,\n self.threshold)\n\n def test_dimensions(self):\n count1 = 0\n count2 = 0\n for x in range(len(self.correct_data)):\n count2 += 1\n if self.new_data[x].shape == self.correct_data[x].shape:\n count1 += 1\n self.assertEqual(count1, count2)\n\n def test_values(self):\n count1 = 0\n count2 = 0\n for x in range(len(self.correct_data)):\n count2 += 1\n if np.array_equal(self.new_data[x], self.correct_data[x]):\n count1 += 1\n self.assertEqual(count1, count2)\n\n def test_variances(self):\n count1 = 0\n count2 = 0\n for elem in np.var(self.new_data[0], axis=0):\n count2 += 1\n if elem >= self.threshold:\n count1 += 1\n for elem in np.var(self.new_data[2], axis=0):\n count2 += 1\n if elem >= self.threshold:\n count1 += 1\n self.assertEqual(count1, count2)\n\n\nclass RemoveConstantFeatures(unittest.TestCase):\n def setUp(self):\n a = np.zeros((12, 1))\n b = np.random.randint(15, size=(12, 4))\n self.x_train = np.hstack((a, b, a))\n self.x_test = np.random.randint(15, size=(6, 6))\n self.data = (self.x_train, [], self.x_test, [])\n self.new_data, self.feat_name, self.final_args = remove_constant(self.data, None)\n self.correct_x_train = b\n self.correct_x_test = np.delete(self.x_test, [0, 5], axis=1)\n\n def test_values(self):\n val1 = np.array_equal(self.new_data[0], self.correct_x_train)\n val2 = np.array_equal(self.new_data[2], self.correct_x_test)\n self.assertTrue(val1 and val2, msg='\\n' + str(self.new_data[2]) + '\\n'\n + str(self.correct_x_test))\n\n def test_feature_extraction(self):\n features_before = np.array(['a', 'b', 'c', 'd', 'e', 'f'])\n features_after = np.array(['b', 'c', 'd', 'e'])\n data, features, args = remove_constant(self.data, features_before)\n if np.array_equal(features_after, features):\n val = True\n else:\n val = False\n self.assertTrue(val)\n\n\nclass SelectKBest(unittest.TestCase):\n def setUp(self):\n self.score_func = chi2\n self.classes = 3\n self.features = 1000\n best = np.zeros((self.features * self.classes, 1))\n for x in range(self.classes):\n best[x * self.features: (x + 1) * self.features] = x\n c = np.random.randint(2, size=(self.features * self.classes,\n self.features - 2))\n x_train = np.hstack((best, c, best))\n y_train = best.reshape(self.features * self.classes)\n x_test = np.random.randint(15, size=(10, self.features))\n y_test = np.random.randint(self.classes, size=(10))\n self.data = [x_train, y_train, x_test, y_test]\n self.new_data, self.fn, self.fa = select_k_best(self.data, None,\n score_func=self.score_func, k=2)\n correct_x_train = np.delete(x_train, np.arange(1, self.features - 1),\n axis=1)\n correct_x_test = np.delete(x_test, np.arange(1, self.features - 1),\n axis=1)\n self.correct_data = [correct_x_train, y_train, correct_x_test, y_test]\n\n def test_values(self):\n count1 = 0\n count2 = 0\n for x in range(len(self.correct_data)):\n count2 += 1\n if np.array_equal(self.new_data[x], self.correct_data[x]):\n count1 += 1\n self.assertEqual(count1, count2)\n\n def test_feature_extraction(self):\n features_before = np.random.randint(self.features, size=self.features)\n features_after = features_before[[0, -1]]\n data, features, args = select_k_best(self.data, features_before,\n score_func=self.score_func, k=2)\n if np.array_equal(features_after, features):\n val = True\n else:\n val = False\n self.assertTrue(val)\n\n\nclass SelectPercentile(unittest.TestCase):\n def setUp(self):\n self.score_func = chi2\n self.classes = 3\n self.features = 5\n best = np.zeros((self.features * self.classes, 1))\n for x in range(self.classes):\n best[x * self.features: (x + 1) * self.features] = x\n c = np.random.randint(2, size=(self.features * self.classes,\n self.features - 2))\n x_train = np.hstack((best, c, best))\n y_train = best.reshape(self.features * self.classes)\n x_test = np.random.randint(15, size=(10, self.features))\n y_test = np.random.randint(self.classes, size=(10))\n self.data = [x_train, y_train, x_test, y_test]\n p = old_div(200, self.features)\n self.new_data, self.f, self.fa = select_percentile(self.data, None,\n score_func=self.score_func,\n percentile=p)\n correct_x_train = np.delete(x_train, np.arange(1, self.features - 1),\n axis=1)\n correct_x_test = np.delete(x_test, np.arange(1, self.features - 1),\n axis=1)\n self.correct_data = [correct_x_train, y_train, correct_x_test, y_test]\n\n def test_values(self):\n count1 = 0\n count2 = 0\n for x in range(len(self.correct_data)):\n count2 += 1\n if np.array_equal(self.new_data[x], self.correct_data[x]):\n count1 += 1\n self.assertEqual(count1, count2, msg=str(self.score_func) + '\\n' +\n str(self.classes))\n\n def test_feature_extraction(self):\n features_before = np.random.randint(self.features,\n size=(self.features))\n features_after = features_before[[0, -1]]\n p = old_div(200, self.features)\n sf = self.score_func\n fn = features_before\n data, features, args = select_percentile(self.data, fn, score_func=sf,\n percentile=p)\n if np.array_equal(features_after, features):\n val = True\n else:\n val = False\n self.assertTrue(val)\n\n\nif __name__ == \"__main__\":\n loader = unittest.TestLoader()\n all_tests = loader.discover('.', pattern='test_feature_selection.py')\n runner = unittest.TextTestRunner()\n runner.run(all_tests)\n","sub_path":"Tests/test_feature_selection.py","file_name":"test_feature_selection.py","file_ext":"py","file_size_in_byte":7901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"93566302","text":"import time\nimport numpy as np\nimport math\nimport calattr\nimport csv\n# 节点个数(要修改)\nNODE_NUM=100\nDNA_SIZE = NODE_NUM+1 # DNA length\nPOP_SIZE = 64 # population size\nCROSS_RATE = 0.5 # mating probability (DNA crossover)\nMUTATION_RATE = 0.2 # mutation probability\n\n#迭代次数\nN_GENERATIONS =6000 # 4000\ncalattr = calattr.Calattr()\n\ndef Get_numservice(f):\n num_service = []\n f.readline()\n line = f.readline()\n candidates_c = line.split(' ')\n candidates = []\n for index in range(len(candidates_c)):\n candidates.append(candidates_c[index])\n for candidate in candidates:\n num = 0\n # rows = 0 # 使得服务限制在2个\n f1 = open('julei_result/' + candidate + '.txt')\n line1 = f1.readline()\n while line1:\n num = num + 1\n line1 = f1.readline()\n num_service.append(num)\n return num_service\n\n\n\n\n#########\nnum_service = []\n\n#遗传算法的编码方法\ndef translateDNA(x,num_service):\n x_out=[]\n for i in range(NODE_NUM):\n x_out.append(np.maximum(int(\n np.floor(x[i] * num_service[i]-0.0001)\n ),0))\n return x_out\n\n\ndef get_fcost(pop,num_service):\n out=[]\n for k in range(len(pop)):\n temp=[]\n for n in range(NODE_NUM):\n temp.append(pop[k][n]/num_service[n])\n temp.append(pop[k][-1])\n out.append(temp)\n return out\n\n#遗传\ndef crossover(i,n,pop):\n c1=np.zeros(DNA_SIZE)\n c2=np.zeros(DNA_SIZE)\n c1[0:int(NODE_NUM/2)]=pop[i][0:int(NODE_NUM/2)]\n c1[int(NODE_NUM/2):NODE_NUM]=pop[n][int(NODE_NUM/2):NODE_NUM]\n c2[0:int(NODE_NUM/2)]=pop[n][0:int(NODE_NUM/2)]\n c2[int(NODE_NUM/2):NODE_NUM]=pop[i][int(NODE_NUM/2):NODE_NUM]\n return c1,c2\n\n#变异\ndef mutate(i,pop):\n c1=np.zeros(DNA_SIZE)\n for m in range(DNA_SIZE-1):\n if np.random.rand() < MUTATION_RATE:\n c1[m]=np.random.rand()\n else:\n c1[m]=pop[i][m]\n return c1\n\n#遗传算法入口\ndef GA(number,num_service,startTime):\n # path ='test/10/%d/nodeSet.txt'%number\n # f = open(path)\n # num_service = Get_numservice(f)\n\n #初始化(要修改)\n\n calattr.init('test//%d'%NODE_NUM,number,NODE_NUM)\n #pop = np.random.random(size=(POP_SIZE ,DNA_SIZE))#[50,31] 这里是随机的算子\n pop_before=[]\n T1_cost=[]\n with open('init_data//init_data.csv', \"r\") as csvfile:\n reader = csv.reader(csvfile)\n before_result = list(reader)\n for q in range(before_result.__len__()):\n b_re = before_result[q]\n T1_cost.append(float(b_re[-1]))\n\n int_line = list(map(float, b_re[:NODE_NUM]))\n int_line.append(float(b_re[-1]))\n pop_before.append(int_line)\n\n pop=get_fcost(pop_before,num_service)\n off_pop =pop\n getfit = 0\n calNum=0\n for g in range(N_GENERATIONS):\n print('iter '+str(g+1))\n pop = off_pop\n T3_cost=[]\n for i in range(1,int(len(pop)/2)):\n n = np.random.randint(0, POP_SIZE)\n if (np.random.rand() < CROSS_RATE):\n child1,child2=crossover(i,n,pop)\n else:\n child1=mutate(i,pop)\n child2=mutate(n,pop)\n\n child1[-1]=calattr.receive(translateDNA(child1,num_service))\n child2[-1] = calattr.receive(translateDNA(child2,num_service))\n\n pop = np.vstack((pop, child1))\n pop = np.vstack((pop, child2))\n print(i)\n\n for i in range(len(pop)):\n T3_cost.append(pop[i][ -1])\n T3_cost.sort()\n\n p = 0\n for i in range(len(pop)):\n if (T3_cost.index(pop[i][-1])>int(len(T3_cost)/2)):\n off_pop[p]=pop[i]\n p=p+1\n\n for i in range(len(pop)):\n if (pop[i][-1]==T3_cost[-1]):\n fitness=pop[i].copy()#这是引用!!!!!!!!!!!!!!!\n\n\n #解码过程\n for i in range(NODE_NUM):\n position=np.maximum(int(np.floor(fitness[i] * num_service[i]-0.0001)),0)\n fitness[i]=position\n print('the Gen is:%d' % g)\n print(fitness)\n if(fitness[-1]>getfit):\n timeresult = time.time() - startTime\n pathResult ='./result/result'+str(NODE_NUM)+'_%d.txt'%number\n insert_Set=[]\n m = len(fitness)\n for i in range(m-1):\n insert_Set.append((int)(fitness[i]))\n insert_Set.append(fitness[-1])\n insert_Set.append(timeresult)\n insert_Set.append(g*POP_SIZE)\n\n\n try:\n fobj = open(pathResult, 'a') # 这里的a意思是追加,这样在加了之后就不会覆盖掉源文件中的内容,如果是w则会覆盖。\n except IOError:\n print('file open error:')\n else:\n # 这里的\\n的意思是在源文件末尾换行,即新加内容另起一行插入。\n fobj.write(str(insert_Set))\n fobj.write('\\n')\n print(\"insert ok\")\n fobj.close()\n getfit = fitness[-1]\n # csvFile2 = open(pathResult, 'a',newline='') # 设置newline,否则两行之间会空一行\n # writer = csv.writer(csvFile2)\n # writer.writerow(insert_Set)\n # print(\"change ok !\")\n #getfit =fitness[-1]\n # #calNum =g;\n # csvFile2.close()\n\n return fitness , calNum\n\n\n\n","sub_path":"GA/main/newga.py","file_name":"newga.py","file_ext":"py","file_size_in_byte":5463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"39563315","text":"from math import sqrt\n\n\nclass Reader:\n\n def __init__(self, filename):\n self.__filename = filename\n\n @staticmethod\n def _distance(a, b):\n return sqrt((b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]))\n\n def readNetwork(self):\n network = {}\n if self.__filename == \"berlin52.txt\" or self.__filename == \"hardE.txt\":\n f = open(self.__filename, \"r\")\n text = f.read().split(\"\\n\")\n\n length = int(text[3].split(':')[1])\n network['noNodes'] = length\n f.readline()\n f.readline()\n lines = []\n for i in range(6, length + 6):\n line = text[i].split(\" \")\n lines.append((float(line[1]), float(line[2])))\n mat = [[0.0 for i in range(length)] for i in range(length)]\n\n for i in range(0, length - 1):\n for j in range(i + 1, length):\n mat[j][i] = mat[i][j] = self._distance(lines[i], lines[j])\n network['mat'] = mat\n\n else:\n f = open(self.__filename, \"r\")\n text = f.read()\n lines = text.split(\"\\n\")\n length = int(lines[0])\n network['noNodes'] = length\n mat = []\n for i in range(1, length + 1):\n line = lines[i].split(\",\")\n matrix = []\n for j in line:\n matrix.append(int(j))\n mat.append(matrix)\n network['mat'] = mat\n\n return network","sub_path":"TSP_ACO/repo/Reader.py","file_name":"Reader.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"192725746","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom qutip import *\nfrom Constants import *\nfrom math import *\nimport time\nimport datetime\nimport Constants as cons\nimport os\n\ndef H1_sin(t,*args):\n\treturn cos((omega * t) + 0.5 * PI)\n\ndef H1_cos(t,*args):\n\treturn cos(omega * t)\ndef H1_rot1(t,*args):\n\treturn (cos(omegad1 * t + 0.5*PI) + cos(omegad2*t + 0.5*PI) + 1*cos(omegad3*t + 0.5*0) + 1*cos(omegad4*t+ 0.5*PI))*(cos(omega1 * t) + (0+1j)*sin(omega1*t) )\ndef H1_rot1d(t,*args):\n\treturn (cos(omegad1 * t + 0.5*PI) + cos(omegad2*t + 0.5*PI) + 1*cos(omegad3*t + 0.5*0) + 1*cos(omegad4*t+ 0.5*PI))*(cos(omega1 * t) - (0+1j)*sin(omega1*t) )\ndef H1_rot2(t,*args):\n\treturn (cos(omegad1 * t + 0.5*PI) + cos(omegad2*t + 0.5*PI) + 1*cos(omegad3*t + 0.5*0) + 1*cos(omegad4*t+ 0.5*PI))*(cos(omega2 * t) + (0+1j)*sin(omega2*t) )\ndef H1_rot2d(t,*args):\n\treturn (cos(omegad1 * t + 0.5*PI) + cos(omegad2*t + 0.5*PI) + 1*cos(omegad3*t + 0.5*0) + 1*cos(omegad4*t+ 0.5*PI))*(cos(omega2 * t) - (0+1j)*sin(omega2*t) )\ndef H1_rotpp(t,*args):\n\treturn (cos(omegad1 * t + 0.5*PI) + cos(omegad2*t + 0.5*PI) + 1*cos(omegad3*t + 0.5*0) + 1*cos(omegad4*t+ 0.5*PI))*(cos(omega1 * t) + (0+1j)*sin(omega1*t) )*(cos(omega2 * t) + (0+1j)*sin(omega2*t) )\ndef H1_rotpm(t,*args):\n\treturn (cos(omegad1 * t + 0.5*PI) + cos(omegad2*t + 0.5*PI) + 1*cos(omegad3*t + 0.5*0) + 1*cos(omegad4*t+ 0.5*PI))*(cos(omega1 * t) + (0+1j)*sin(omega1*t) )*(cos(omega2 * t) - (0+1j)*sin(omega2*t) )\ndef H1_rotmp(t,*args):\n\treturn (cos(omegad1 * t + 0.5*PI) + cos(omegad2*t + 0.5*PI) + 1*cos(omegad3*t + 0.5*0) + 1*cos(omegad4*t+ 0.5*PI))*(cos(omega1 * t) - (0+1j)*sin(omega1*t) )*(cos(omega2 * t) + (0+1j)*sin(omega2*t) )\ndef H1_rotmm(t,*args):\n\treturn (cos(omegad1 * t + 0.5*PI) + cos(omegad2*t + 0.5*PI) + 1*cos(omegad3*t + 0.5*0) + 1*cos(omegad4*t+ 0.5*PI))*(cos(omega1 * t) - (0+1j)*sin(omega1*t) )*(cos(omega2 * t) - (0+1j)*sin(omega2*t) )\n\n\nomega1 = 10\nomega2 = 23\nomegad1 = omega1 + omega2\nomegad2 = omega1 - omega2\nomegad3 = omega1\nomegad4 = omega2\n\nR = 1/sqrt(2) * (sigmay() + sigmaz())\n#R=1\n\none = R*basis(2,1)\nzero = R*basis(2,0)\n\na = R * sigmap() * R\n\nq1 = tensor(a, qeye(2))\nq2 = tensor(qeye(2),a)\n\nH0 = 0 * tensor(a,a)\n\ng = 0.05\n\nH = [H0,[q1,H1_rot1],[q1.dag(),H1_rot1d],[q2,H1_rot2],[q2.dag(),H1_rot2d],[g * q1*q2,H1_rotpp],[g * q1*q2.dag(),H1_rotpm],[g * q1.dag()*q2,H1_rotmp],[g * q1.dag()*q2.dag(),H1_rotmm]]\n\ntlist = np.linspace(0,2**9,2**10)\nR=1\nsx1 = tensor(R * sigmax() * R,qeye(2))\nsx2 = tensor(qeye(2), R * sigmax() * R)\n\nsy1 = tensor(R * sigmay() * R,qeye(2))\nsy2 = tensor(qeye(2), R * sigmay() * R)\n\nsz1 = tensor(R * sigmaz() * R,qeye(2))\nsz2 = tensor(qeye(2), R * sigmaz() * R)\n\nc_ops = [0.001*q1,0.001*q2,0.002*sz1,0.002*sz2]\n\nfreqs = np.genfromtxt('Frequencies2')\n\nstart = time.time()\nMax_minFid = []\nfor j in freqs:\n\tprint(j)\n\tfor i in range(0,4):\n\t\tomega1 = j[0]\n\t\tomega2 = j[1]\n\t\tomegad1 = omega1 + omega2\n\t\tomegad2 = omega1 - omega2\n\t\tomegad3 = omega1\n\t\tomegad4 = omega2\n\t\tif i == 0:\n\t\t\tpsi0 = tensor(zero,zero);Tdm = tensor(zero,zero)\n\t\t\toutputstr = 'Output/CNOT_18-03-19/fidelity00-' + str(omega1) + '_' + str(omega2) + '.dat'\n\t\t\t#print('1')\n\t\tif i == 1:\n\t\t\tpsi0 = tensor(zero,one);Tdm = tensor(zero,one)\n\t\t\toutputstr = 'Output/CNOT_18-03-19/fidelity10-' + str(omega1) + '_' + str(omega2) + '.dat'\n\t\t\t#print('2')\n\t\tif i == 2:\n\t\t\tpsi0 = tensor(one,zero);Tdm = tensor(one,one)\n\t\t\toutputstr = 'Output/CNOT_18-03-19/fidelity01-' + str(omega1) + '_' + str(omega2) + '.dat'\n\t\t\t#print('3')\n\t\tif i == 3:\n\t\t\tpsi0 = tensor(one,one);Tdm = tensor(one,zero)\n\t\t\toutputstr = 'Output/CNOT_18-03-19/fidelity11-' + str(omega1) + '_' + str(omega2) + '.dat'\n\t\t\t#print('4')\n\n\t\tresult = mesolve(H,psi0,tlist,c_ops,[sx1,sy1,sz1,sx2,sy2,sz2],options = Options(nsteps = 8000,store_states = True,store_final_state = True))\n\n\n\t\tfidelity_dat = []\n\t\tfor k in range(0,len(tlist)):\n\t\t \t\tfidelity_dat.append(fidelity(result.states[k],Tdm))\n\n\t\twith open(outputstr,'w') as f1:\n\t\t\tfor k in fidelity_dat:\n\t\t\t\tf1.write(str(k) + \"\\n\")\n\n\n\tx11 = np.genfromtxt('Output/CNOT_18-03-19/fidelity11-' + str(omega1) + '_' + str(omega2) + '.dat')\n\tx10 = np.genfromtxt('Output/CNOT_18-03-19/fidelity10-' + str(omega1) + '_' + str(omega2) + '.dat')\n\tx01 = np.genfromtxt('Output/CNOT_18-03-19/fidelity01-' + str(omega1) + '_' + str(omega2) + '.dat')\n\tx00 = np.genfromtxt('Output/CNOT_18-03-19/fidelity00-' + str(omega1) + '_' + str(omega2) + '.dat')\n\n\n\ttmp = []\n\tMin = []\n\n\tfor k in range(0,len(x11)):\n\t\ttmp.append(x11[k])\n\t\ttmp.append(x10[k])\n\t\ttmp.append(x01[k])\n\t\ttmp.append(x00[k])\n\t\tMin.append(min(tmp))\n\t\ttmp = []\n\t#print('Fidelity Achieved:' + str(max(Min)))\n\tMax_minFid.append(max(Min))\n\n\toutputstr = 'Output/CNOT_18-03-19/Minimum-' + str(omega1) + '_' + str(omega2) + '.dat'\n\n\twith open(outputstr,'w') as f2:\n\t\tfor k in Min:\n\t\t\tf2.write(str(k) + \"\\n\")\n\nend = time.time()\nprint('Time Taken for Simulation:')\nprint(end - start)\n\noutputstr = 'Output/CNOT_18-03-19/__Max_Fidelity__.dat'\n\nwith open(outputstr,'w') as f3:\n\tfor k in Max_minFid:\n\t\tf3.write(str(k) + \"\\n\")\n\n","sub_path":"Legacy/src_transformed/Two_Qubit.py","file_name":"Two_Qubit.py","file_ext":"py","file_size_in_byte":5009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"13747777","text":"\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('add',views.add,name='add'),\n path('insertEmp',views.insertEmp,name='insertEmp'),\n path('show',views.show,name='show'),\n path('editEmp/',views.editEmp,name='editEmp'),\n path('updateEmp/',views.updateEmp,name='updateEmp'),\n path('deleteEmp/',views.deleteEmp,name='deleteEmp')\n]\n\n\n\n","sub_path":"adminpanel/employee/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"32675730","text":"import numpy as np\nimport datetime\nimport os\n\nclass ObjFns:\n def __init__(self) -> None:\n pass\n \n # def obj_fns(obj_fn, sims, obds):\n # return obj_fn(sims, obds)\n @staticmethod\n def nse(sims, obds):\n \"\"\"Nash-Sutcliffe Efficiency (NSE) as per `Nash and Sutcliffe, 1970\n `_.\n\n :Calculation Details:\n .. math::\n E_{\\\\text{NSE}} = 1 - \\\\frac{\\\\sum_{i=1}^{N}[e_{i}-s_{i}]^2}\n {\\\\sum_{i=1}^{N}[e_{i}-\\\\mu(e)]^2}\n\n where *N* is the length of the *sims* and *obds*\n periods, *e* is the *obds* series, *s* is (one of) the\n *sims* series, and *μ* is the arithmetic mean.\n\n \"\"\"\n nse_ = 1 - (\n np.sum((obds - sims) ** 2, axis=0, dtype=np.float64)\n / np.sum((obds - np.mean(obds)) ** 2, dtype=np.float64)\n )\n return round(nse_, 4)\n\n @staticmethod\n def rmse(sims, obds):\n \"\"\"Root Mean Square Error (RMSE).\n\n :Calculation Details:\n .. math::\n E_{\\\\text{RMSE}} = \\\\sqrt{\\\\frac{1}{N}\\\\sum_{i=1}^{N}[e_i-s_i]^2}\n\n where *N* is the length of the *sims* and *obds*\n periods, *e* is the *obds* series, *s* is (one of) the\n *sims* series.\n\n \"\"\"\n rmse_ = np.sqrt(np.mean((obds - sims) ** 2,\n axis=0, dtype=np.float64))\n\n return round(rmse_, 4)\n\n @staticmethod\n def pbias(sims, obds):\n \"\"\"Percent Bias (PBias).\n\n :Calculation Details:\n .. math::\n E_{\\\\text{PBias}} = 100 × \\\\frac{\\\\sum_{i=1}^{N}(e_{i}-s_{i})}{\\\\sum_{i=1}^{N}e_{i}}\n\n where *N* is the length of the *sims* and *obds*\n periods, *e* is the *obds* series, and *s* is (one of)\n the *sims* series.\n\n \"\"\"\n pbias_ = (100 * np.sum(obds - sims, axis=0, dtype=np.float64)\n / np.sum(obds))\n\n return round(pbias_, 4)\n\n @staticmethod\n def rsq(sims, obds):\n ## R-squared\n rsq_ = (\n (\n (sum((obds - obds.mean())*(sims-sims.mean())))**2\n ) \n /\n (\n (sum((obds - obds.mean())**2)* (sum((sims-sims.mean())**2))\n ))\n )\n return round(rsq_, 4)\n\nclass DefineTime:\n\n def __init__(self) -> None:\n pass\n\n def get_start_end_time(self):\n APEXMOD_path_dict = self.dirs_and_paths()\n wd = APEXMOD_path_dict['apexmf_model']\n if os.path.isfile(os.path.join(wd, \"APEXCONT.DAT\")):\n with open(os.path.join(wd, 'APEXCONT.DAT'), \"r\") as f:\n data = [x.strip().split() for x in f if x.strip()]\n numyr = int(data[0][0])\n styr = int(data[0][1])\n stmon = int(data[0][2])\n stday = int(data[0][3])\n ptcode = int(data[0][4])\n edyr = styr + numyr -1\n stdate = datetime.datetime(styr, stmon, 1) + datetime.timedelta(stday - 1)\n eddate = datetime.datetime(edyr, 12, 31)\n stdate_ = stdate.strftime(\"%m/%d/%Y\")\n eddate_ = eddate.strftime(\"%m/%d/%Y\")\n return stdate_, eddate_, ptcode","sub_path":"apexmf/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"277730578","text":"import math\nimport pdb\n\nclass TokenException(Exception):pass\n\nclass token:\n op_dict = {\n '+' : lambda l, r : l + r,\n '-' : lambda l, r : l - r,\n '*' : lambda l, r : l * r,\n '/' : lambda l, r : l / r,\n '**' : lambda l, r : l ** r,\n }\n\n func_dict = {\n 'sin' : math.sin,\n 'cos' : math.cos,\n 'tan' : math.tan,\n 'asin' : math.asin,\n 'acos' : math.acos,\n 'atan' : math.atan,\n 'cosh' : math.cosh,\n 'sinh' : math.sinh,\n 'tanh' : math.tanh,\n 'exp' : math.exp,\n }\n\n handlers = {\n 'int' : lambda string, **kwarsg : int(string),\n 'float' : lambda string, **kwargs : float(string),\n 'op' : lambda string, **kwargs : token.op_dict[string](\n kwargs['left'],\n kwargs['right']\n ),\n 'func' : lambda string, **kwargs : token.func_dict[string](*kwargs['args']),\n 'var' : lambda string, **kwargs : kwargs['rules'][string]\\\n if len(kwargs) != 0 and\n kwargs.get('rules') and\n string in kwargs['rules'] else string,\n }\n\n def __init__(self, string, token_type):\n if token_type not in token.handlers: raise TokenException('{0} is not a valid token type'.format(token_type))\n self.token_type, self.string = token_type, string\n\nclass expression_node(token):\n def __init__(self, string, token_type, left=None, right=None, args=[]):\n token.__init__(self, string, token_type)\n self.left, self.right, self.args = left, right, args\n left, right, args = None, None, []\n\n def get_value(self, rules={}):\n rslt = token.handlers[self.token_type](self.string,\n rules=rules,\n left=self.left.get_value(rules=rules) if self.left else None,\n right=self.right.get_value(rules=rules) if self.right else None,\n args = [x.get_value(rules=rules) for x in self.args] if hasattr(self, 'args') else None\n )\n rules = {}\n return rslt\n\n def __repr__(self):\n return \"\".format(self.string, self.token_type)\n","sub_path":"expressions/expression.py","file_name":"expression.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"585590549","text":"# Author: Sebastian Fabig\nimport os\nimport csv\n\ntrain_data = './ProstateData/TrainImages'\ntrain_mask_data = './ProstateData/MaskTrainOne'\ntest_data = './ProstateData/TestImages'\ntest_mask_data = './ProstateData/MaskTestOne'\n\ntrain_files = os.listdir(train_data)\ntrain_masks = os.listdir(train_mask_data)\ntest_files = os.listdir(test_data)\ntest_masks = os.listdir(test_mask_data)\n\ncsv_list = list()\ncsv_list.append(['img', 'mask'])\nfor i in range(len(train_files)):\n csv_list.append([os.path.relpath(train_data + \"/\" + train_files[i]), os.path.relpath(train_mask_data + \"/\" + train_masks[i])])\n\nwith open('./prostate_training.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerows(csv_list)\n\ncsv_list = list()\ncsv_list.append(['img', 'mask'])\nfor i in range(len(test_files)):\n csv_list.append([os.path.relpath(test_data + \"/\" + test_files[i]),\n os.path.relpath(test_mask_data + \"/\" + test_masks[i])])\n\nwith open('./prostate_test.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerows(csv_list)\n\nprint(len(train_files))\nprint(len(train_masks))","sub_path":"Code/create_csv.py","file_name":"create_csv.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"10325037","text":"import sys\n\nDEBUG = False # debugging flag\nQUIET = True # don't print output\nOUTPUT = [] # accumulated return values\nRETVAL = None # return value: last output instruction\nRBOFFSET = 0 # offset to be used in relative base mode\n\noperation_types = {\n 1: {\n 'name': 'sum',\n 'nparams': 3,\n 'opcode': 1,\n },\n 2: {\n 'name': 'mult',\n 'nparams': 3,\n 'opcode': 2,\n },\n 3: {\n 'name': 'input',\n 'nparams': 1,\n 'opcode': 3,\n },\n 4: {\n 'name': 'output',\n 'nparams': 1,\n 'opcode': 4,\n },\n 5: {\n 'name': 'jump-if-true',\n 'nparams': 2,\n 'opcode': 5,\n },\n 6: {\n 'name': 'jump-if-false',\n 'nparams': 2,\n 'opcode': 6,\n },\n 7: {\n 'name': 'less than',\n 'nparams': 3,\n 'opcode': 7,\n },\n 8: {\n 'name': 'equals',\n 'nparams': 3,\n 'opcode': 8,\n },\n 9: {\n 'name': 'ajdust rb offset',\n 'nparams': 1,\n 'opcode': 9,\n },\n 99: {\n 'name': 'halt',\n 'nparams': 0,\n 'opcode': 99,\n },\n}\n\ndef _get_modes(instructions, idx):\n instruction = instructions[idx]\n\n mode3 = instruction // 10000\n instruction -= 10000*mode3\n\n mode2 = instruction // 1000\n instruction -= 1000*mode2\n\n mode1 = instruction // 100\n instruction -= 100*mode1\n\n opcode = instruction\n\n return opcode, [mode1, mode2, mode3]\n\n\ndef _get_params(instructions, idx, opcode, modes):\n params = []\n for i in range(operation_types[opcode]['nparams']):\n if modes[i] == 0:\n params.append(instructions[idx+i+1])\n elif modes[i] == 1:\n params.append(idx+i+1)\n elif modes[i] == 2:\n params.append(instructions[idx+i+1]+RBOFFSET)\n\n return params\n\n\ndef _interpret(instructions, idx, inputdata):\n opcode, modes = _get_modes(instructions, idx)\n params = _get_params(instructions, idx, opcode, modes)\n\n if DEBUG:\n print('===============')\n print(\"Operation type:\", operation_types[opcode])\n print(\"Raw instruction:\", instructions[idx])\n print(\"Idx:\", idx)\n print(\"Opcode:\", opcode)\n print(\"Params:\", params)\n print(\"Modes:\", modes)\n\n if opcode == 1: # sum\n instructions[params[2]] = instructions[params[0]] + instructions[params[1]]\n return idx+4\n\n elif opcode == 2: # mult\n instructions[params[2]] = instructions[params[0]] * instructions[params[1]]\n return idx+4\n\n elif opcode == 3: # input\n if inputdata is None:\n instructions[params[0]] = int(input(\"INPUT > \"))\n else:\n if len(inputdata) == 0:\n return idx # stop execution\n else:\n instructions[params[0]] = inputdata.pop(0)\n return idx+2\n\n elif opcode == 4: # output\n if not QUIET:\n print(\"OUTPUT:\", instructions[params[0]])\n global RETVAL\n global OUTPUT\n RETVAL = instructions[params[0]] # set return value\n OUTPUT.append(RETVAL)\n return idx+2\n\n elif opcode == 5: # jump-if-true\n if instructions[params[0]] != 0:\n return instructions[params[1]]\n return idx+3\n\n elif opcode == 6: # jump-if-false\n if instructions[params[0]] == 0:\n return instructions[params[1]]\n return idx+3\n\n elif opcode == 7: # less than\n if instructions[params[0]] < instructions[params[1]]:\n instructions[params[2]] = 1\n else:\n instructions[params[2]] = 0\n return idx+4\n\n elif opcode == 8: # equals\n if instructions[params[0]] == instructions[params[1]]:\n instructions[params[2]] = 1\n else:\n instructions[params[2]] = 0\n return idx+4\n\n elif opcode == 9: # adjust relative base offset\n global RBOFFSET\n RBOFFSET += instructions[params[0]]\n if DEBUG:\n print('RBOFFSET:', RBOFFSET)\n return idx+2\n\n elif opcode == 99:\n return -1\n\n else:\n print(\"Unexpected opcode \", opcode)\n print(instructions)\n exit(1)\n\n\ndef execute(instructions, startidx=0, rboffset=0, inputdata=None):\n\n global RBOFFSET\n RBOFFSET = rboffset\n\n idx = startidx\n old_idx = -1\n while idx != -1 and idx != old_idx:\n old_idx = idx\n idx = _interpret(instructions, idx, inputdata)\n\n if DEBUG:\n print(\"FINISHED\")\n\n return idx, RBOFFSET\n\n\ndef load_instructions(filename):\n with open(filename) as fp:\n for line in fp:\n instructions = [int(a) for a in line.strip().split(',')]\n\n # add more memory to instructions queue\n instructions += [0]*1000\n\n return instructions\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2 and len(sys.argv) != 3:\n print(\"usage: python3 intcode.py [input_file]\")\n exit(1)\n\n instructions = load_instructions(sys.argv[1])\n\n if len(sys.argv) == 3:\n data = []\n with open(sys.argv[2]) as inputfile:\n for line in fp:\n data.append(int(line.strip()))\n execute(instructions, inputdata=data)\n else:\n execute(instructions)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"day15/part1/intcode.py","file_name":"intcode.py","file_ext":"py","file_size_in_byte":5232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"239944874","text":"import requests, json\r\n# from json import loads\r\nfrom elasticsearch import Elasticsearch\r\n\r\n\r\nHOST = '66.3.125.43'\r\nport = '9200'\r\napi_infor = '_cluster/stats?pretty'\r\nurl = 'http://' + HOST + ':' + port + '/' + api_infor\r\ncluster_infor = requests.get(url) # get到的是response\r\n\r\n# 将response对象转换为json\r\ninfo_json = cluster_infor.json()\r\n\r\n# get方法查询集群状态\r\nes_healthy = json.loads(cluster_infor.text).get(\"status\")\r\nprint(es_healthy)\r\n","sub_path":"api_test.py","file_name":"api_test.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"540012591","text":"#! /usr/bin/env python\nimport argparse,textwrap\nimport pyperclip\n\n# for multi-line description\nclass SaneFormatter(argparse.RawTextHelpFormatter, \n argparse.ArgumentDefaultsHelpFormatter):\n pass\n\ndef run(args):\n res=''\n s=args.strInput\n caseInput=args.caseInput\n if caseInput=='u':\n s=s.upper()\n elif caseInput=='l':\n s=s.lower()\n elif caseInput=='t':\n s=s.title()\n elif caseInput=='a':\n for i in range(len(s)):\n if not i%2==0:\n res+=s[i].upper()\n else:\n res+=s[i].lower()\n s=res\n elif caseInput=='i':\n s=s.swapcase()\n elif caseInput=='s':\n firstLetter=s[0]\n firstLetter=firstLetter.upper()\n s=firstLetter+s[1:]\n print(s)\n pyperclip.copy(s)\ndef main():\n parser=argparse.ArgumentParser(description='''Convert The case of a given string. The tool automatically copies the output to your clipboard.\n-u Convert given string to upper Case. eg python app.py -str \"hello world\" -to \"u\" -> HELLO WORLD\n-l Convert given string to lower Case. eg python app.py -str \"hEllO woRld\" -to \"l\" -> hello world\n-t Convert given string to title Case. eg python app.py -str \"hello world\" -to \"t\" -> Hello World\n-a Convert given string to alternate Case. eg python app.py -str \"hello world\" -to \"a\" -> hElLo wOrLd\n-i Convert given string to inverse Case. eg python app.py -str \"hEllo WOrld\" -to \"i\" -> HeLLO woRLD\n-s Convert given string to sentence Case. eg python app.py -str \"hello world\" -to \"s\" -> Hello world\n''', formatter_class=SaneFormatter)\n parser.add_argument(\"-str\",help=\"input string\" ,dest=\"strInput\", type=str, required=True)\n parser.add_argument(\"-to\",help=\"To upper case\" ,dest=\"caseInput\", type=str, required=True)\n parser.set_defaults(func=run)\n args=parser.parse_args()\n args.func(args)\n\nif __name__==\"__main__\":\n\tmain()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"642237142","text":"from flask import Flask\nfrom flask import render_template\nfrom flask_sqlalchemy import SQLAlchemy\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///officials_data.db'\ndb = SQLAlchemy(app)\n\nclass Official(db.Model):\n __tablename__ = 'officials_data'\n __table_args__ = {\n 'autoload': True,\n 'autoload_with': db.engine\n }\n officialNumber = db.Column(db.String, primary_key=True)\n\n@app.route(\"/\")\ndef list():\n officials = Official.query.all()\n return render_template(\"list.html\", officials=officials)\n\n\n@app.route(\"//\")\ndef show(officialNumber):\n official = Official.query.filter_by(officialNumber=officialNumber).first()\n return render_template(\"show.html\", official=official) \n\n#@app.route(\"/officials/sanctions\") \n#def show():\n# official = Official.query.all().first()\n# return render_template(\"show.html\", official=official)\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"Sanctioned_officers/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"22660627","text":"import json\nimport SensorLib\nfrom time import sleep\nfrom datetime import datetime\n\nclass Log:\n\n def __init__(self):\n self.file = None\n self.l = SensorLib.LCD()\n\n def LogLurk(self):\n self.file = open(\"/home/pi/Documents/GRN-HSE/log/log.json\", \"w\")\n self.file.write(\"\\n\\n\")\n self.file.write(datetime.today().strftime('%Y-%m-%d %H:%M:%S'))\n self.file.write(\"\\n\")\n self.l.printData(\"Log\",\"Open Log File\")\n sleep(.5)\n\n def StopLog(self):\n self.l.printData(\"Log\",\"Stop Logging\")\n self.file = open(\"/home/pi/Documents/GRN-HSE/log/log.json\", \"a\")\n self.file.close()\n \n def LogInfo(self,data):\n\n # dump output in JSON\n jsonData = json.dumps(str(data))\n\n # write to file\n self.file = open(\"/home/pi/Documents/GRN-HSE/log/log.json\", \"a\")\n self.file.write(\"\\n\")\n self.file.write(jsonData)\n self.file.write(\"\\n\")","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"381337193","text":"#TKinter Death Certificate\n#2018\n#Nathan Jones\n\nfrom tkinter import messagebox, Label, Button, FALSE, Tk, Entry\nfrom tkinter import *\nfrom PIL import Image, ImageTk\nfrom datetime import datetime\nfrom uuid import getnode as get_mac\n\nimport time\nimport socket\nimport sys\nimport os.path\nimport os\nimport string \nimport getpass\nimport random\nimport statistics\nimport itertools\nimport datetime\nimport pyglet\n\n#global variables - GREETINGS\n\n\n\nwindow = Tk()\n\nl0 = Label(window, text=\"\",bg=\"AntiqueWhite2\")\nl0.pack()\n\nalbum = ImageTk.PhotoImage(Image.open(\"C:\\\\Users\\\\natda\\\\OneDrive\\\\Sixth Form\\\\Computer Science\\\\CODE\\GRAND CENTRAL v3\\\\GRAND_CENTRAL_v3-MSTR\\\\albums\\\\DC.jpg\"))\n\nlabel = Label(window, image=album)\nlabel.pack()\n\nl2 = Label(window, text=\"\",bg=\"AntiqueWhite2\")\nl2.pack()\n\n\nl2 = Label(window, text=\"Ice Cube - Death Certificate\",font='Helvetica 18 bold',bg=\"AntiqueWhite2\")\nl2.pack()\n\nl1 = Label(window, text=\"\",bg=\"AntiqueWhite2\")\nl1.pack()\n\nl1 = Label(window, text=\"\"\"Death Certificate is the second studio album by American rapper Ice Cube,\nreleased on October 29, 1991 by Priority Records and EMI.\nThe album was re-released for the 25th anniversary edition\non June 9, 2017 by Interscope Records after Cube announced\nsigning to the label in late May 2017.\n\"\"\",bg=\"AntiqueWhite2\")\nl1.pack()\n\ndef donothing():\n pass\n\ndef close_window (root): \n root.destroy()\n\n#CREATING VARIOUS BUTTONS FOR THE VARIOUS PROGRAMS THAT ARE WITHIN GRAND CENTRAL - WILL VARY DEPENDING ON THE USER \n\ndef option():\n\n option1()\n\nb1 = Button(window, text=\"PLAY ALL\", command=option)\nb1.pack()\n\n\nl2 = Label(window, text=\"\",bg=\"AntiqueWhite2\")\nl2.pack()\n\ndef option1():\n #1\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - The Funeral.mp3')\n song.play()\n time.sleep(97)\n option2()\n pyglet.app.run()\n \n\nb1 = Button(window, text=\" The Funeral \", command=option1)\nb1.pack()\n\ndef option2():\n #2\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - The Wrong Nigga To Fuck Wit.mp3')\n song.play()\n time.sleep(168)\n option3()\n pyglet.app.run()\n \n\nb1 = Button(window, text=\" The Wrong Nigga To Fuck Wit \", command=option2)\nb1.pack()\n\ndef option3():\n #3\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - My Summer Vacation.mp3')\n song.play()\n time.sleep(236)\n option4()\n pyglet.app.run()\n \n\nb1 = Button(window, text=\" My Summer Vacation \", command=option3)\nb1.pack()\n\ndef option4():\n #4\n song = pyglet.media.load('''C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - Steady Mobbin'.mp3''')\n song.play()\n time.sleep(250)\n option5()\n pyglet.app.run()\n \n\nb1 = Button(window, text=\" Steady Mobbin' \", command=option4)\nb1.pack()\n\ndef option5():\n #5\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - Robin Lench.mp3')\n song.play()\n time.sleep(73)\n option6()\n pyglet.app.run()\n \nb1 = Button(window, text=\" Robin Lench \", command=option5)\nb1.pack()\n\ndef option6():\n #6\n song = pyglet.media.load('''C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - Givin' Up The Nappy Dug Out.mp3''')\n song.play()\n time.sleep(255)\n option7()\n pyglet.app.run()\n\nb1 = Button(window, text=\" Givin' Up The Nappy Dug Out \", command=option6)\nb1.pack()\n\ndef option7():\n #7\n song = pyglet.media.load('''C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - Look Who's Burnin'.mp3''')\n song.play()\n time.sleep(233)\n option8()\n pyglet.app.run()\n\nb1 = Button(window, text=\" Look Who's Burnin' \", command=option7)\nb1.pack()\n\ndef option8():\n #8\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - A Bird In The Hand.mp3')\n song.play()\n time.sleep(137)\n option9()\n pyglet.app.run()\n\nb1 = Button(window, text=\" A Bird In The Hand \", command=option8)\nb1.pack()\n\ndef option9():\n #9\n song = pyglet.media.load('''C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - Man's Best Friend.mp3''')\n song.play()\n time.sleep(126)\n option10()\n pyglet.app.run()\n\nb1 = Button(window, text=\" Man's Best Friend \", command=option9)\nb1.pack()\n\ndef option10():\n #10\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - Alive On Arrival.mp3')\n song.play()\n time.sleep(191)\n option11()\n pyglet.app.run()\n\nb1 = Button(window, text=\" Alive On Arrival \", command=option10)\nb1.pack()\n\ndef option11():\n #11\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - Death.mp3')\n song.play()\n time.sleep(63)\n option12()\n pyglet.app.run()\n\nb1 = Button(window, text=\" Death \", command=option11)\nb1.pack()\n\ndef option12():\n #12\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - The Birth.mp3')\n song.play()\n time.sleep(81)\n option13()\n pyglet.app.run()\n\nb1 = Button(window, text=\" The Birth \", command=option12)\nb1.pack()\n\ndef option13():\n #13\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - I Wanna Kill Sam.mp3')\n song.play()\n time.sleep(202)\n option14()\n pyglet.app.run()\n\nb1 = Button(window, text=\" I Wanna Kill Sam \", command=option13)\nb1.pack()\n\ndef option14():\n #14\n song = pyglet.media.load('''C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - Horny Lil' Devil.mp3''')\n song.play()\n time.sleep(222)\n option15()\n pyglet.app.run()\n\nb1 = Button(window, text=\" Horny Lil' Devil \", command=option14)\nb1.pack()\n\ndef option15():\n #15\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - Black Korea.mp3')\n song.play()\n time.sleep(46)\n option16()\n pyglet.app.run()\n\nb1 = Button(window, text=\" Black Korea \", command=option15)\nb1.pack()\n\ndef option16():\n #16\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - True To The Game.mp3')\n song.play()\n time.sleep(250)\n option17()\n pyglet.app.run()\n\nb1 = Button(window, text=\" True To The Game \", command=option16)\nb1.pack()\n \ndef option17():\n #17\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - Color Blind.mp3')\n song.play()\n time.sleep(269)\n option18()\n pyglet.app.run()\n\nb1 = Button(window, text=\" Color Blind \", command=option17)\nb1.pack()\n\ndef option18():\n #18\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - Doing Dumb Shit.mp3')\n song.play()\n time.sleep(225)\n option19()\n pyglet.app.run()\n\nb1 = Button(window, text=\" Doing Dumb Shit \", command=option18)\nb1.pack()\n\ndef option19():\n #19\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - Us.mp3')\n song.play()\n time.sleep(223)\n option20()\n pyglet.app.run()\n\nb1 = Button(window, text=\" Us \", command=option19)\nb1.pack()\n\ndef option20():\n #20\n song = pyglet.media.load('C:\\\\Users\\\\natda\\\\OneDrive\\\\Music\\\\Ice Cube\\\\Death Certificate\\\\Ice Cube - No Vaseline.mp3')\n song.play()\n time.sleep(312)\n os.startfile(\"C:\\\\Users\\\\natda\\\\OneDrive\\\\Sixth Form\\\\Computer Science\\\\CODE\\GRAND CENTRAL v3\\\\GRAND_CENTRAL_v3-MSTR\\\\ARTISTS\\\\ALBUMS - ICE CUBE\\\\DC.py\")\n window.destroy()\n pyglet.app.run()\n\nb1 = Button(window, text=\" No Vaseline \", command=option20)\nb1.pack() \n\nl2 = Label(window, text=\"\",bg=\"AntiqueWhite2\")\nl2.pack()\n\ndef option14():\n os.startfile(\"C:\\\\Users\\\\natda\\\\OneDrive\\\\Sixth Form\\\\Computer Science\\\\CODE\\GRAND CENTRAL v3\\\\GRAND_CENTRAL_v3-MSTR\\\\ARTISTS\\\\IceCube.py\")\n window.destroy()\n\nb15 = Button(window, text=\"BACK\",command=option14)\nb15.pack()\n\nwindow.resizable(0,0)\nwindow.resizable(width=FALSE, height=FALSE)\nwindow.title(\"Death Certificate - MSTR\")\nwindow.geometry(\"500x970\")\nwindow.configure(background='AntiqueWhite2')\n\n\n\n\nmainloop()\n","sub_path":"GRAND_CENTRAL_v3-MSTR/ARTISTS/ALBUMS - ICE CUBE/DC.py","file_name":"DC.py","file_ext":"py","file_size_in_byte":8976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"236423490","text":"import pandas as pd\nimport os\nimport pickle\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport nltk\nfrom nltk import tokenize\nimport seaborn as sns\nfrom string import punctuation\nimport unidecode \nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom nltk import ngrams\nimport random\n\n'''from nltk.tokenize import word_tokenize\nfrom nltk import pos_tag\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.preprocessing import LabelEncoder'''\nfrom collections import defaultdict\nfrom nltk.corpus import wordnet as wn\nfrom sklearn import model_selection, naive_bayes, svm\nfrom sklearn.metrics import accuracy_score\n\nimport spacy\nimport fnmatch\nfrom collections import Counter\nimport subprocess\nimport re\nimport gensim\nfrom enelvo import normaliser\nfrom ftfy import fix_encoding\n\ndef most_commom(lst):\n data = Counter(lst)\n return(data.most_common())\n\ndef corpus_treino_teste(tipo, save=False):\n try:\n with(open(os.path.join(\"Corpus_reduzido\", tipo+\"_corpus.p\"), \"rb\")) as file:\n corpus = pickle.load(file)\n with(open(os.path.join(\"Corpus_reduzido\", tipo+\"_polaridade.p\"), \"rb\")) as file:\n polaridade = pickle.load(file)\n \n except:\n\n with open(os.path.join(\"Corpus_reduzido\", \"corpus.p\"), \"rb\") as file:\n reviews = pickle.load(file) \n\n with open(os.path.join(\"Corpus_reduzido\", \"corpus_polaridade.p\"), \"rb\") as file:\n pol = pickle.load(file)\n\n dados = pd.DataFrame(data=reviews, index=range(0,len(reviews)), columns=['corpus'])\n dados['polaridade'] = pol\n #print(dados)\n #print(type(dados))\n #print(dados.polaridade.value_counts())\n\n treino, teste, classe_treino, classe_teste = train_test_split(dados.corpus,\n dados.polaridade,\n test_size = 0.3,\n random_state = 42)\n\n treino = treino.values.tolist()\n teste = teste.values.tolist()\n classe_treino = classe_treino.values.tolist()\n classe_teste = classe_teste.values.tolist()\n\n classe_treino = [(str(classe)).replace(\"0\", \"-1\") for classe in classe_treino]\n classe_teste = [(str(classe)).replace(\"0\", \"-1\") for classe in classe_teste]\n \n \n if save:\n with open(os.path.join(\"Corpus_reduzido\", \"train_corpus.p\"), \"wb\") as file:\n pickle.dump(treino, file)\n\n with open(os.path.join(\"Corpus_reduzido\", \"test_corpus.p\"), \"wb\") as file:\n pickle.dump(teste, file)\n\n with open(os.path.join(\"Corpus_reduzido\", \"train_polaridade.p\"), \"wb\") as file:\n pickle.dump(classe_treino, file)\n\n with open(os.path.join(\"Corpus_reduzido\", \"test_polaridade.p\"), \"wb\") as file:\n pickle.dump(classe_teste, file)\n\n if tipo == \"train\":\n corpus = treino\n polaridade = classe_treino\n else:\n corpus = teste\n polaridade = classe_teste\n \n return corpus, polaridade\n\ndef corpus_normalizado(tipo, save=\"False\"):\n \n try:\n with(open(os.path.join(\"Corpus_reduzido\", tipo+\"_corpus_normalized.p\"), \"rb\")) as file:\n all_reviews_normalizado = pickle.load(file)\n with open(os.path.join(\"Corpus_reduzido\", \"corpus_polaridade.p\"), \"rb\") as file:\n polaridade = pickle.load(file)\n \n except:\n all_reviews, polaridade = corpus_treino_teste(tipo)\n all_reviews_normalizado = []\n for i, review in enumerate(all_reviews):\n print(i)\n norm = normaliser.Normaliser()\n review = norm.normalise(review)\n all_reviews_normalizado.append(review)\n \n \n if save:\n with open(os.path.join(\"Corpus_reduzido\", tipo+\"_corpus_normalized.p\"), \"wb\") as file:\n pickle.dump(all_reviews_normalizado, file)\n\n \n return all_reviews_normalizado, polaridade\n \n\ndef pre_processing_text(text):\n\n text = text.lower()\n\n input_chars = [\"\\n\", \".\", \"!\", \"?\", \"ç\", \" / \", \" - \", \"|\", \"ã\", \"õ\", \"á\", \"é\", \"í\", \"ó\", \"ú\", \"â\", \"ê\", \"î\", \"ô\", \"û\", \"à\", \"è\", \"ì\", \"ò\", \"ù\"]\n output_chars = [\" . \", \" . \", \" . \", \" . \", \"c\", \"/\", \"-\", \"\", \"a\", \"o\", \"a\", \"e\", \"i\", \"o\", \"u\", \"a\", \"e\", \"i\", \"o\", \"u\", \"a\", \"e\", \"i\", \"o\", \"u\"]\n\n for i in range(len(input_chars)):\n text = text.replace(input_chars[i], output_chars[i]) \n\n text.strip()\n\n return text\n\ndef pre_processamento(text):\n text = text.lower()\n\n input_chars = [\"\\n\", \".\", \"!\", \"?\", \" / \", \" - \", \"|\", '``', \"''\"]\n output_chars = [\" . \", \" . \", \" . \", \" . \", \"/\", \"-\", \"\", \"\", \"\"]\n\n for i in range(len(input_chars)):\n text = text.replace(input_chars[i], output_chars[i]) \n\n text.strip()\n\n return text\n\ndef pre_processamento2(corpus, remover_stopwords = \"False\", remover_acentos = \"False\", remover_pontuacao = \"False\", blabla = \"False\"): \n\n token_pontuacao = tokenize.WordPunctTokenizer()\n token_espaco = tokenize.WhitespaceTokenizer()\n \n reviews = corpus\n\n frase_processada = list()\n\n for opiniao in reviews:\n nova_frase = list()\n opiniao = opiniao.lower()\n palavras_texto = token_pontuacao.tokenize(opiniao)\n for palavra in palavras_texto: \n nova_frase.append(palavra)\n frase_processada.append(' '.join(nova_frase))\n\n reviews = frase_processada\n\n StopWords_ = nltk.corpus.stopwords.words(\"portuguese\")\n stopwords_sem_acento = [unidecode.unidecode(texto) for texto in StopWords_]\n stopwords_ = (StopWords_ + stopwords_sem_acento)\n \n if remover_acentos: \n\n sem_acento = [unidecode.unidecode(texto) for texto in reviews]\n reviews = sem_acento\n\n if remover_stopwords:\n frase_processada = list()\n\n for opiniao in reviews:\n nova_frase = list()\n palavras_texto = token_espaco.tokenize(opiniao)\n for palavra in palavras_texto:\n if palavra not in stopwords_:\n nova_frase.append(palavra)\n frase_processada.append(' '.join(nova_frase))\n\n reviews = frase_processada \n \n\n if remover_pontuacao:\n \n pontuacao = list()\n for ponto in punctuation:\n pontuacao.append(ponto)\n \n frase_processada = list()\n for opiniao in reviews:\n nova_frase = list()\n palavras_texto = token_espaco.tokenize(opiniao)\n for palavra in palavras_texto:\n if palavra not in pontuacao:\n nova_frase.append(palavra)\n frase_processada.append(' '.join(nova_frase))\n \n reviews = frase_processada\n return reviews\n\n if blabla:\n stemmer = nltk.RSLPStemmer()\n frase_processada = list()\n \n for opiniao in reviews:\n nova_frase = list()\n palavras_texto = token_espaco.tokenize(opiniao)\n for palavra in palavras_texto:\n nova_frase.append(stemmer.stem(palavra))\n frase_processada.append(' '.join(nova_frase))\n \n reviews = frase_processada\n\n return reviews\n\n\n\n\n\ndef TreeTagger(texto):\n \n file = open(os.path.join(\"C:\\TreeTagger\", \"texto.txt\"), \"w\", encoding=\"utf8\" )\n file.writelines(texto) \n file.close()\n\n process = subprocess.Popen([r'\\TreeTagger\\executar.bat'],\n shell = True,\n stdout=subprocess.PIPE, \n stderr=subprocess.PIPE,\n universal_newlines=True)\n stdout, stderr = process.communicate()\n #print(stdout)\n result = stdout.split('\\n')\n pos_tag = []\n for x in result:\n word = fix_encoding(x)\n pos_tag.append(word.split('\\t'))\n \n return pos_tag\n\n\ndef aspecto_substantivo_TreeTagger(save = \"False\"):\n\n try:\n with(open(\"Nounprocessed_Reviews_TreeTagger.p\", \"rb\")) as f:\n all_reviews = pickle.load(f)\n except:\n all_reviews, polaridade = corpus_treino_teste(\"train\")\n reviews = []\n for review in all_reviews:\n reviews.append(pre_processamento(review))\n all_reviews = reviews\n with open(\"Nounprocessed_Reviews_TreeTagger.p\", \"wb\") as f:\n pickle.dump(all_reviews, f)\n\n \n mais_comum = []\n subst = []\n aspects = []\n for i, text in enumerate(all_reviews[:2000]):\n print(i)\n pos_tag = TreeTagger(text)\n pos_tag.remove([''])\n for token in pos_tag: \n if (token[1] == 'NCMS') or (token[1] == 'NCMP') or (token[1] == 'NCFS') or (token[1] == 'NCFP') or (token[1] == 'NCCP') or (token[1] == 'NCCS') or (token[1] == 'NCCI'):\n palavra = pre_processing_text(token[0])\n #token = unidecode.unidecode(token.norm_) \n #subst.append(str(token.lemma_))\n subst.append(str(palavra))\n\n mais_comum = most_commom(subst)\n #freq = (len(mais_comum))*0.02\n #mais_comum = (mais_comum[:(int(freq))])\n print(\"\\n\",mais_comum[:200])\n \n for tupla in mais_comum:\n aspects.append(tupla[0])\n \n print(aspects[:200])\n\n if save:\n with open(os.path.join(\"Aspectos\",\"noun_aspects_TreeTagger.p\"), \"wb\") as f:\n pickle.dump(aspects, f)\n\n return aspects\n\n\ndef aspecto_substantivo_NLTK(frequency_cut=0.03, save=False):\n reviews = []\n with open(\"tagger.pkl\", \"rb\") as f:\n tagger = pickle.load(f)\n\n try:\n with(open(\"Nounprocessed_Reviews_NLTK.p\", \"rb\")) as f:\n all_reviews = pickle.load(f)\n except:\n all_reviews, polaridade = corpus_treino_teste(\"train\")\n for review in all_reviews:\n reviews.append(pre_processamento(review))\n all_reviews = reviews\n with open(\"Nounprocessed_Reviews_NLTK.p\", \"wb\") as f:\n pickle.dump(all_reviews, f)\n \n portuguese_sent_tokenizer = nltk.data.load(\"tokenizers/punkt/portuguese.pickle\")\n \n noun_words = {}\n aspects =[]\n subst = []\n mais_comum = []\n for i, review in enumerate(all_reviews):\n #print(i)\n sentences = portuguese_sent_tokenizer.tokenize(review)\n tag_review = [tagger.tag(nltk.word_tokenize(sentence)) for sentence in sentences]\n for tag_sentence in tag_review:\n for tag in tag_sentence:\n if tag[1] == \"NOUN\":\n word = pre_processing_text(tag[0])\n subst.append(word)\n\n mais_comum = most_commom(subst)\n #freq = (len(mais_comum))*0.02\n #mais_comum = (mais_comum[:(int(freq))])\n #print(\"\\n\",mais_comum[:200])\n \n for tupla in mais_comum:\n aspects.append(tupla[0])\n \n print(aspects[:250])\n \n if save:\n with open(os.path.join(\"Aspectos\",\"noun_aspects_NLTK.p\"), \"wb\") as f:\n pickle.dump(aspects, f)\n return aspects\n\n'''def aspecto_substantivo_TreeTagger(save = \"False\"):\n file = open(\"Corpus_TreeTagger.txt\", \"r\", encoding=\"utf8\")\n corpus = file.read()\n all_reviews = corpus.split('id_')\n file.close()\n all_reviews.remove('')\n mais_comum = []\n subst = []\n aspects = []\n for i, text in enumerate(all_reviews):\n #print(i)\n text = text.split('\\n')\n pos_tag = [] \n for line in text:\n pos_tag.append(line.split('\\t'))\n\n #print(pos_tag)\n pos_tag.remove([''])\n for token in pos_tag:\n if (token[1] == 'NCMS') or (token[1] == 'NCFS') or (token[1] == 'NCFP') or (token[1] == 'NCCP') or (token[1] == 'NCCS') or (token[1] == 'NCCI'):\n \n palavra = pre_processing_text(token[0])\n subst.append(str(palavra))\n\n mais_comum = most_commom(subst)\n #print(\"\\n\",mais_comum[:200])\n \n for tupla in mais_comum:\n aspects.append(tupla[0])\n \n print(aspects[:200])\n\n if save:\n with open(os.path.join(\"Aspectos\",\"noun_aspects_TreeTagger.p\"), \"wb\") as f:\n pickle.dump(aspects, f)\n\n return aspects'''\n \ndef aspecto_substantivo_spacy(save = \"False\"):\n\n try:\n with(open(\"Nounprocessed_Reviews_Spacy.p\", \"rb\")) as f:\n all_reviews = pickle.load(f)\n except:\n all_reviews, polaridade = corpus_treino_teste(\"train\")\n reviews = []\n for review in all_reviews:\n reviews.append(pre_processamento(review))\n all_reviews = reviews\n\n with open(\"Nounprocessed_Reviews_Spacy.p\", \"wb\") as f:\n pickle.dump(all_reviews, f)\n\n \n mais_comum = []\n subst = []\n aspects = []\n for i,text in enumerate(all_reviews):\n print(i)\n nlp = spacy.load(\"pt_core_news_sm\")\n doc = nlp(text)\n for token in doc:\n if token.pos_ == 'NOUN':\n token = pre_processing_text(token.norm_)\n #token = unidecode.unidecode(token.norm_) \n #subst.append(str(token.lemma_))\n subst.append(str(token))\n\n mais_comum = most_commom(subst)\n #freq = (len(mais_comum))*0.02\n #mais_comum = (mais_comum[:(int(freq))])\n print(\"\\n\",mais_comum[:200])\n \n for tupla in mais_comum:\n aspects.append(tupla[0])\n \n print(aspects[:200])\n\n if save:\n with open(os.path.join(\"Aspectos\",\"noun_aspects_Spacy.p\"), \"wb\") as f:\n pickle.dump(aspects, f)\n\n return aspects\n\ndef create_aspects_lexicon_ontologies():\n \"\"\"Create a list of the aspects indicated in the groups file\"\"\"\n aspects = []\n with open(\"Hontology.xml\", \"r\", encoding=\"utf8\") as file:\n text = file.readlines()\n for line in text:\n if \"pt\" in line:\n word = line.split('>')[1].split('<')[0]\n if word != \"\\n\":\n aspects.append(pre_processing_text(word))\n \n print(aspects)\n \n with open(os.path.join(\"Aspectos\",\"ontology_aspects.p\"), \"wb\") as f:\n pickle.dump(aspects, f)\n return aspects\n\ndef create_aspects_lexicon_embeddings(seeds, seeds_type, number_synonym=3,save=False):\n aspects_list = []\n model = gensim.models.Word2Vec.load(\"word2vec.model\")\n for word in seeds:\n aspects_list.append(word)\n if word in model.wv.vocab:\n out = model.wv.most_similar(positive=word, topn=number_synonym) \n aspects_list.append(out[0][0].lower())\n aspects_list.append(out[1][0].lower())\n aspects_list.append(out[2][0].lower())\n aspects_list = list(set(aspects_list))\n if save:\n with open(os.path.join(\"Aspectos\",seeds_type+\"_embedding_aspects.p\"), \"wb\") as file:\n pickle.dump(aspects_list, file)\n return aspects_list\n\n#def implicito_explicido_aspectos():\n \n\n#aspecto_substantivo_NLTK(save = 'True')\n#aspecto_substantivo_TreeTagger('True')\n#aspecto_substantivo_spacy(save = 'True')\n#create_aspects_lexicon_ontologies()\n\n#all_reviews, polaridade = corpus_normalizado(\"train\", save=\"True\")\n\nwith open(os.path.join(\"Aspectos\",\"noun_aspects_TreeTagger.p\"), \"rb\") as f:\n seeds = pickle.load(f)\n\nprint(seeds[:10])\n \naspects_list = create_aspects_lexicon_embeddings(seeds[:10], 'noun_TreeTagger_agora',save=True)\nprint(aspects_list)\n\n\n\n'''all_reviews, polaridade = corpus_treino_teste(\"train\")\nTreeTagger(all_reviews[0])'''\n\n","sub_path":"Extracao_Aspectos.py","file_name":"Extracao_Aspectos.py","file_ext":"py","file_size_in_byte":15694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"187140843","text":"\"\"\"\nUpload cifar-10 data to the mongoDB to access it via that mongoDB reader for training and inference\nCifar-10 data is available here: https://www.cs.toronto.edu/~kriz/cifar.html (download the python version)\nWorking directory is expected to be mlpipe root folder\n\"\"\"\nimport numpy as np\nimport cv2\nfrom pymongo import MongoClient\nimport argparse\nfrom numba import jit\nimport pickle\n\n\n# MongoDB connection\nCONNECTION_STRING = \"mongodb://localhost:27017\"\nDB = \"cifar10\"\nCOLLECTION_TRAIN = \"train\"\nCOLLECTION_TEST = \"test\"\n\nclient = MongoClient(CONNECTION_STRING)\ncoll_train = client[DB][COLLECTION_TRAIN]\ncoll_test = client[DB][COLLECTION_TEST]\n\n\n@jit\ndef create_img(arr):\n red = arr[:1024]\n green = arr[1024:2048]\n blue = arr[2048:]\n img_mat = np.zeros((32, 32, 3), np.uint8)\n for col in range(0, 32):\n for row in range(0, 32):\n pos = 32*col + row\n img_mat[col][row][0] = blue[pos]\n img_mat[col][row][1] = green[pos]\n img_mat[col][row][2] = red[pos]\n return img_mat\n\n\ndef get_labels(base_dir):\n with open(base_dir + \"batches.meta\", 'rb') as file:\n meta_data = pickle.load(file, encoding='bytes')\n return_val = []\n for name in meta_data[b'label_names']:\n return_val.append(name.decode(\"utf-8\"))\n return return_val\n\n\ndef upload_data(collection, file_path, data_labels):\n with open(file_path, 'rb') as fo:\n data = pickle.load(fo, encoding='bytes')\n np_arr = data[b\"data\"]\n\n for x, label_int in enumerate(data[b\"labels\"]):\n label_str = data_labels[label_int]\n\n img_raw = np_arr[x]\n img = create_img(img_raw)\n\n png_img_str = cv2.imencode(\".png\", img)[1].tostring()\n\n collection.insert_one({\n 'label': label_int,\n 'label_name': label_str,\n 'img': png_img_str,\n 'content_type': \"image/png\"\n })\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Upload Comma AI speed challenge')\n parser.add_argument('--path_data', required=True, type=str, help=\"Path to cifar-10 data\")\n args = parser.parse_args()\n\n labels = get_labels(args.path_data)\n\n # upload train batches in single train collection\n for i in range(1, 6):\n print(\"Uploading Batch \" + str(i))\n file_name = args.path_data + \"data_batch_\" + str(i)\n upload_data(coll_train, file_name, labels)\n\n # upload test batches in test collection\n print(\"Uploading Test Batch\")\n upload_data(coll_test, args.path_data + \"test_batch\", labels)\n\n print(\"Uploading done\")\n","sub_path":"cifar10/mongodb/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"532432535","text":"import os\nclass HarshadNumber:\n\tdef isHarshad(self,n):\n\t\tcopy = n\n\t\tsum = 0\n\t\twhile (copy > 0):\n\t\t\tremainder = copy % 10\n\t\t\tsum += remainder\n\t\t\tcopy = copy // 10\n\t\tif (n % sum == 0):\n\t\t\tprint(n,\"is Harshad.\")\n\t\telse:\n\t\t\tprint(n,\"is not Harshad.\")\nx = HarshadNumber()\nnumber = int(input(\"Number to check if Harshad: \"))\nx.isHarshad(number)\nos.system(\"pause\")","sub_path":"How to Code Together using Python/CLASS PYTHON/harshad.py","file_name":"harshad.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"207114896","text":"import config\nimport discord\nimport datetime\n\nimport util.utils as utils\nimport util.exceptions as exceptions\n\nfrom bs4 import BeautifulSoup, SoupStrainer\nfrom discord.ext import commands\n\n\nclass Legislature(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(name='submit')\n @commands.cooldown(1, config.getCooldown(), commands.BucketType.user)\n @commands.has_any_role(\"Legislator\", \"Legislature\")\n @utils.is_democraciv_guild()\n async def submit(self, ctx, google_docs_url: str):\n \"\"\"Submit a new bill directly to the current Speaker of the Legislature.\n\n Usage:\n -----\n -submit [Google Docs Link of Bil]\n \"\"\"\n speaker_role = discord.utils.get(self.bot.democraciv_guild_object.roles, name=\"Speaker of the Legislature\")\n valid_google_docs_url_strings = ['https://docs.google.com/', 'https://drive.google.com/']\n\n if len(google_docs_url) < 15 or not google_docs_url:\n await ctx.send(\":x: You have to give me a valid Google Docs URL of the bill you want to submit!\")\n return\n\n if not any(string in google_docs_url for string in valid_google_docs_url_strings):\n await ctx.send(\":x: That doesn't look like a Google Docs URL.\")\n return\n\n if speaker_role is None:\n raise exceptions.RoleNotFoundError(\"Speaker of the Legislature\")\n\n if len(speaker_role.members) == 0:\n raise exceptions.NoOneHasRoleError(\"Speaker of the Legislature\")\n\n speaker_person = speaker_role.members[0] # Assuming there's only 1 speaker ever\n\n try:\n async with ctx.typing():\n async with self.bot.session.get(google_docs_url) as response:\n text = await response.read()\n\n strainer = SoupStrainer(property=\"og:title\") # Only parse the title property HTMl to save time\n soup = BeautifulSoup(text, \"lxml\", parse_only=strainer) # Use lxml parser to speed things up\n\n bill_title = soup.find(\"meta\")['content'] # Get title of Google Docs website\n\n if bill_title.endswith(' - Google Docs'):\n bill_title = bill_title[:-14]\n\n soup.decompose() # Garbage collection\n\n except Exception:\n await ctx.send(\":x: Could not connect to Google Docs.\")\n return\n\n embed = self.bot.embeds.embed_builder(title=\"New Bill Submitted\", description=\"\", time_stamp=True)\n embed.add_field(name=\"Title\", value=bill_title, inline=False)\n embed.add_field(name=\"Author\", value=ctx.message.author.name)\n embed.add_field(name=\"Time of Submission (UTC)\", value=datetime.datetime.utcnow())\n embed.add_field(name=\"URL\", value=google_docs_url, inline=False)\n\n try:\n await speaker_person.create_dm()\n await speaker_person.dm_channel.send(embed=embed)\n await ctx.send(\n f\":white_check_mark: Successfully submitted '{bill_title}' to the Speaker of the Legislature!\")\n except Exception:\n await ctx.send(\":x: Unexpected error occurred during DMing the Speaker!\"\n \" Your bill was not submitted, please try again!\")\n return\n\n\ndef setup(bot):\n bot.add_cog(Legislature(bot))\n","sub_path":"module/legislature.py","file_name":"legislature.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"376040912","text":"#!/usr/bin/python3\n#\n# template for console programs and modules.\n#\nprint(\"type integers, each followed by , or just to finish\")\n#\ntotal = 0\ncount = 0\n#\nwhile True:\n line = input(\"Enter an integer: \")\n if line:\n try:\n number = int(line)\n except ValueError as err:\n print(err)\n continue\n total += number\n count += 1\n else:\n break\nif count:\n print(\"count = \", count, \", total = \", total, \", mean = \", total/count)\n#\nexit(0);\n\n","sub_path":"books/programming_in_python_3/mine/ch1/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"80091143","text":"#Kyla Ryan \r\n#9/18\r\n#Get Name Function\r\n\r\n#Import math functions\r\nimport math\r\n#define function to ask user for name input\r\ndef get_name():\r\n name=input(\"What is your name? \")\r\n\r\n\r\n#display name\r\n print(\"The name you entered was\", name)\r\n\r\n\r\n\r\n\r\n\r\nprint(\"This is our function\")\r\n#get_name()\r\n\r\n\r\n#define function for area of a circle. Assign variables to functions for calculations.\r\ndef areaOfCircle(radius1):\r\n PI = 3.14159263\r\n#1 Get a radius\r\n radius = radius1\r\n \r\n \r\n#2 compute an area. Area is r^2*Pi\r\n radius = float(radius)\r\n area = radius*radius*PI\r\n#3 Display informaiton back\r\n print(\"The area of the circle is: \",area)\r\ninputx(\"What is radius? \")\r\nareaOfCircle(radiusx)\r\n\r\n#Assign function for pythagorean theorum\r\ndef pythagorean_theorum_1():\r\n #a^2+b^2=c^2\r\n #Ask for the sides of the triangle to compute\r\n a=float(input(\"what is side a of the triangle?\"))\r\n b=float(input(\"what is side b of the triangle?\"))\r\n c=a*a+b*b #Assign c as the first side squared, plus, the second side squared. \r\n \r\n print(\"The third side is\",c)\r\n#Present the calculation to the user and call the function. \r\npythagorean_theorum_1()\r\n\r\n#Assign function again, but give parameters.\r\ndef pythagorean_theorum(ax,bx):\r\n #a^2+b^2=c^2\r\n a=float(ax)\r\n b=float(bx)\r\n c=a*a+b*b\r\n #Assign a mathematic equation to the c value to calculate the side of the hypoteneus squared.\r\n #Then take the square root by calling the math.sqrt function of c to find the side. \r\n c=math.sqrt(c)\r\n \r\n print(\"The third side is\",c)\r\n#Assign variables to the user's inputs for the trangle sides.\r\nax=input(\"what is side a of the triangle?\")\r\nbx=input(\"what is side b of the triangle?\")\r\npythagorean_theorum(ax,bx)\r\n\r\n#Define the function to add two numbers together\r\n#Ask for inputs from the user.\r\n#Create a function to add the two assigned variables together.\r\n#Assign a variable to the equation to simplify the function for better output.\r\n#Call the function by the variable.\r\n\r\ndef add_numbers():\r\n num1=input(\"enter a number\")\r\n num2=input(\"enter a second number\")\r\n num3=int(num1)+int(num2)\r\n return num3\r\nnum4=add_numbers() #num4=num3\r\nprint(\"the sum of your numbers is: \",num4)\r\n\r\nprint(num4)\r\nadd_numbers()\r\n#Do the same function as the Add Numbers, but assign variables to the input numbers.\r\ndef add_numbers(X,Y):\r\n num1=X\r\n num2=Y\r\n num3=int(num1)+int(num2)\r\n print(\"this is num1\")\r\n print(\"this is num2\")\r\n return num3\r\nX=input(\"enter a number\")\r\nY=input(\"enter a second number\")\r\nnum4=add_numbers(X,Y) #num4=num3\r\nprint(\"the sum of your numbers is: \",num4)\r\n\r\nprint(num4)\r\n\r\n#Define the function for the user's name. \r\ndef get_name(name_input):\r\n \r\n\r\n\r\n#display name\r\n name=name_input\r\n name.lower()\r\n name=name.title()\r\n print(\"the name you entered was\",name)\r\n print(\"is this correct? yes or no\")\r\n\r\n\r\n\r\nprint(\"This is our function\")\r\nname=input(\"what is your name\")\r\nget_name(name)\r\n\r\n\r\n","sub_path":"Get_Name.py","file_name":"Get_Name.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"577811049","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n wfluo 2016-07-12\n app.cmdb.rdbms.views\n ~~~~~~~~~~~~~~~~~~~~~~\n 配置管理模块中的关系数据库,与前端交互层\n\"\"\"\nfrom flask_restful import (Resource, reqparse)\nfrom app.cmdb.rdbms.services import (DatabaseService, InstanceService, ClusterService, SchemaService)\nfrom app.configs.code import ResponseCode\nfrom app.response import res, res_list_page, res_details\nfrom app.utils.parser import common_parser\n\n# 参数解析对象生成\nparser = reqparse.RequestParser()\n\n# 添加通用参数解析\ncommon_parser(parser)\nparser.add_argument(\"id\", type=int)\n\n\nclass DatabaseApi(Resource):\n \"\"\"\n 数据库添加、删除、修改、单条记录详查操作\n \"\"\"\n @staticmethod\n def post():\n # 添加记录 Songgy 2016-08-16\n parser.add_argument(\"name\", type=str)\n parser.add_argument(\"status\", type=str)\n parser.add_argument(\"sdid\", type=int)\n parser.add_argument(\"cluster_role\", type=str)\n parser.add_argument(\"product\", type=str)\n parser.add_argument(\"version\", type=str)\n parser.add_argument(\"characterset\", type=str)\n parser.add_argument(\"arch\", type=str)\n parser.add_argument(\"usage\", type=str)\n parser.add_argument(\"scenario\", type=str)\n parser.add_argument(\"descript\", type=str)\n parser.add_argument(\"max_sessions\", type=int)\n parser.add_argument(\"cluster_id\", type=int)\n parser.add_argument(\"coss_id\", type=int)\n parser.add_argument(\"service_level\", type=str)\n args = parser.parse_args()\n db_ = DatabaseService.insert_database(args)\n return res(ResponseCode.SUCCEED, db_)\n\n @staticmethod\n def put():\n # 修改记录 Songgy 2016-08-17\n parser.add_argument(\"name\", type=str)\n parser.add_argument(\"status\", type=str)\n parser.add_argument(\"sdid\", type=int)\n parser.add_argument(\"cluster_role\", type=str)\n parser.add_argument(\"product\", type=str)\n parser.add_argument(\"version\", type=str)\n parser.add_argument(\"characterset\", type=str)\n parser.add_argument(\"arch\", type=str)\n parser.add_argument(\"usage\", type=str)\n parser.add_argument(\"scenario\", type=str)\n parser.add_argument(\"descript\", type=str)\n parser.add_argument(\"max_sessions\", type=int)\n parser.add_argument(\"cluster_id\", type=int)\n parser.add_argument(\"coss_id\", type=int)\n parser.add_argument(\"service_level\", type=str)\n args = parser.parse_args()\n DatabaseService.update_database(args)\n return res(ResponseCode.SUCCEED, 'SUCCESS', None, None)\n\n @staticmethod\n def delete():\n # 删除记录 Songgy 2016-08-16\n args = parser.parse_args()\n id_ = args['id']\n DatabaseService.delete_database(id_)\n return res(ResponseCode.SUCCEED, 'SUCCESS', None, None)\n\n @staticmethod\n def get():\n # 通过ID查找相关修改 Songgy 2016-08-17\n args = parser.parse_args()\n id_ = args['id']\n db_ = DatabaseService.get_database(id_)\n return res(ResponseCode.SUCCEED, 'SUCCESS', None, db_)\n\n\nclass DatabaseListApi(Resource):\n \"\"\"数据库 列表 API\"\"\"\n @staticmethod\n def post():\n args = parser.parse_args()\n page = args['page']\n db = DatabaseService.get_database_list(page)\n count = DatabaseService.get_database_count()\n return res_list_page(ResponseCode.SUCCEED, \"SUCCESS \", None, db, count, page)\n\n\nclass DatabaseDetailApi(Resource):\n \"\"\"数据库详情API\"\"\"\n @staticmethod\n def post():\n args = parser.parse_args()\n id_ = args['id']\n ret = DatabaseService.get_database_detail(id_)\n return res_details(ResponseCode.SUCCEED, \"SUCCESS \", None, ret)\n\n\nclass InstanceApi(Resource):\n \"\"\"\n 数据库添加、删除、修改、单条记录详查操作\n \"\"\"\n @staticmethod\n def post():\n # 添加记录 Songgy 2016-08-18\n parser.add_argument('name', type=str)\n parser.add_argument('status', type=str)\n parser.add_argument('install_user', type=str)\n parser.add_argument('listener_port', type=int)\n parser.add_argument('database_id', type=int)\n parser.add_argument('sdid', type=int)\n parser.add_argument('coss_id', type=int)\n args = parser.parse_args()\n instance_ = InstanceService.insert_instance(args)\n return res(ResponseCode.SUCCEED, instance_)\n\n @staticmethod\n def put():\n # 修改记录 Songgy 2016-08-18\n # 对coss_id的处理是不予修改\n parser.add_argument('name', type=str)\n parser.add_argument('status', type=str)\n parser.add_argument('install_user', type=str)\n parser.add_argument('listener_port', type=int)\n parser.add_argument('database_id', type=int)\n parser.add_argument('sdid', type=int)\n # parser.add_argument('coss_id', type=int)\n args = parser.parse_args()\n instance_ = InstanceService.update_instance(args)\n return res(ResponseCode.SUCCEED, instance_)\n\n @staticmethod\n def delete():\n # 删除记录 Songgy 2016-08-18\n args = parser.parse_args()\n delete_info = InstanceService.delete_instance(args)\n return res(ResponseCode.SUCCEED, delete_info)\n\n @staticmethod\n def get():\n # 通过ID或Name查找相关修改 Songgy 2016-08-17\n args = parser.parse_args()\n id_ = args['id']\n instance_ = InstanceService.get_instance_by_id(id_)\n return res(ResponseCode.SUCCEED, 'SUCCESS', None, instance_)\n\n\nclass InstanceListApi(Resource):\n \"\"\"数据库 实例列表 API\"\"\"\n @staticmethod\n def post():\n args = parser.parse_args()\n page = args['page']\n inst = InstanceService.get_instance_list(page)\n count = InstanceService.get_instance_count()\n return res_list_page(ResponseCode.SUCCEED, \"SUCCESS \", None, inst, count, page)\n\n\nclass InstanceDetailApi(Resource):\n \"\"\"数据库实例详情API\"\"\"\n\n @staticmethod\n def post():\n args = parser.parse_args()\n id_ = args['id']\n inst_detail = InstanceService.get_instance_detail(id_)\n return res_details(ResponseCode.SUCCEED, \"SUCCESS \", None, inst_detail)\n\n\nclass ClusterApi(Resource):\n \"\"\"\n 数据库添加、删除、修改、单条记录详查操作\n \"\"\"\n\n def post(self):\n # 添加记录\n pass\n\n def put(self):\n # 修改记录\n pass\n\n def delete(self):\n # 删除记录\n pass\n\n def get(self):\n # 通过ID或Name查找相关修改\n pass\n\n\nclass ClusterListApi(Resource):\n \"\"\"数据库 集群列表 API\"\"\"\n @staticmethod\n def post():\n args = parser.parse_args()\n page = args['page']\n cluster = ClusterService.get_cluster_list(page)\n count = ClusterService.get_cluster_count()\n return res_list_page(ResponseCode.SUCCEED, \"SUCCESS \", None, cluster, count, page)\n\n\nclass ClusterDetailApi(Resource):\n \"\"\"数据库集群详情API\"\"\"\n\n @staticmethod\n def post():\n args = parser.parse_args()\n id_ = args['id']\n cluster_detail = ClusterService.get_cluster_detail(id_)\n return res_details(ResponseCode.SUCCEED, \"SUCCESS \", None, cluster_detail)\n\n\nclass SchemaApi(Resource):\n \"\"\"\n 数据库添加、删除、修改、单条记录详查操作\n \"\"\"\n\n def post(self):\n # 添加记录\n pass\n\n def put(self):\n # 修改记录\n pass\n\n def delete(self):\n # 删除记录\n pass\n\n def get(self):\n # 通过ID或Name查找相关修改\n pass\n\n\nclass SchemaListApi(Resource):\n \"\"\"数据库 模式列表 API\"\"\"\n @staticmethod\n def post():\n args = parser.parse_args()\n page = args['page']\n schema = SchemaService.get_schema_list(page)\n count = SchemaService.get_schema_count()\n return res_list_page(ResponseCode.SUCCEED, \"SUCCESS \", None, schema, count, page)\n\n\nclass SchemaDetailApi(Resource):\n \"\"\"数据库 模式 API\"\"\"\n @staticmethod\n def post():\n args = parser.parse_args()\n id_ = args['id']\n schema_detail = SchemaService.get_schema_detail(id_)\n return res_details(ResponseCode.SUCCEED, \"SUCCESS \", None, schema_detail)\n","sub_path":"app/cmdb/rdbms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"298931453","text":"import random\r\n\r\nn = int(input('Input the number items of list:\\n>'))\r\nmy_list = []\r\nfor i in range(n):\r\n my_list.append(random.randint(1, 100))\r\nprint('Source list:', *my_list)\r\ncounter = 0\r\nfor i in range(n - 1):\r\n if my_list[i] > my_list[i + 1]:\r\n counter += 1\r\n i += 1\r\nprint('There is(are) {} inversion(s) in your list'.format(counter))\r\n\r\n\r\n\r\n\r\n","sub_path":"inversions_count.py","file_name":"inversions_count.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"68708760","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/rpmspectool/version.py\n# Compiled at: 2019-12-10 09:36:36\n# Size of source mod 2**32: 153 bytes\nimport pkg_resources\ntry:\n version = pkg_resources.require('rpmspectool')[0].version\nexcept pkg_resources.DistributionNotFound:\n version = 'git'","sub_path":"pycfiles/rpmspectool-1.99.7-py3.7/version.cpython-37.py","file_name":"version.cpython-37.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"162988212","text":"import numpy\n#import curses\nfrom os import system\n\nFIELDSIZE = (50, 80)\nSPEED = 1\nINIT_SIZE = 4\nINIT_HEADPOS = (int(FIELDSIZE[0]), int(FIELDSIZE[1]))\n\n#stdscr = curses.initscr()\n\nFIELD = []\n\ndef create_box():\n for i in range(FIELDSIZE[0]):\n FIELD.append([])\n for j in range(FIELDSIZE[1]):\n if (i == 0) or (i == FIELDSIZE[1] - 1) or (j == 0) or (j == FIELDSIZE[0] - 1):\n FIELD[i].append(-1)\n else:\n FIELD[i].append(0)\n\nprint(FIELD)\n","sub_path":"Python/Snake/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"451522538","text":"seconds = float (input('How may seconds do you want to convert? '))\r\n\r\nif seconds >= 60 : \r\n minutes = seconds//60\r\n remhours = seconds %60 \r\n print('That is',format(minutes, '.0f'), ' minute and', format(remhours, '.3f'),'seconds')\r\nelif seconds >= 3600 :\r\n hours = seconds // 3600 \r\n minutes = (seconds//60)%60 \r\n seconds = seconds %60\r\n print('That is ', hours, 'hours', minutes, 'minutes and', seconds, 'seconds!!')\r\nelse: \r\n print('Not valid input!!!!!')\r\n\r\n ","sub_path":"CSC308 Examples/Examples/Exam 1 Review/TimeCalculator.py","file_name":"TimeCalculator.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"591565354","text":"# This script takes a string and returns the longest palindromic substring.\n# Time complexity: O(n^2)\n# Space complexity: O(1) (use three pointers, see below)\n\n# First, define a helper function that returns the largest palindromic substring\n# starting from a left and right index (by gradually moving them outwards if matching characters are found).\ndef largest_palindrome_at_index(s, left, right):\n \n left_index = 0\n right_index = 0\n \n while left >= 0 and right < len(s):\n if s[left] == s[right]:\n left_index = left\n right_index = right\n else:\n break\n left -= 1\n right += 1\n \n return s[left_index : right_index + 1]\n\n# Main function: traverse through the list using the helper function from above\ndef longest_palindrome(s):\n \n result = \"\" \n for i in range(len(s)):\n palindrome_odd = largest_palindrome_at_index(s, i, i)\n palindrome_even = largest_palindrome_at_index(s, i, i + 1)\n larger_palindrome = palindrome_odd if len(palindrome_odd) > len(palindrome_even) else palindrome_even\n result = result if len(result) >= len(larger_palindrome) else larger_palindrome\n \n return result","sub_path":"largest_palindromic_substring.py","file_name":"largest_palindromic_substring.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"51335616","text":"## SI 364 - Fall 2017\r\n## HW 4 \r\n##worked with Avery Wein \r\n\r\n## Import statements\r\nimport os\r\nfrom flask import Flask, render_template, session, redirect, url_for, flash\r\nfrom flask_script import Manager, Shell\r\nfrom flask_wtf import FlaskForm\r\nfrom wtforms import StringField, SubmitField\r\nfrom wtforms.validators import Required\r\nfrom flask_sqlalchemy import SQLAlchemy\r\n\r\n\r\n# import json\r\n# from psycopg2 import connect\r\n# username = 'alliwanHW4'\r\n# conn = connect(dbname=username, user=username)\r\n# cur = conn.cursor()\r\n# conn = psycopg2.connect(database=\"alliwanHW4\", user=\"postgres\", password=\"secret\")\r\n\r\n\r\n\r\n# Configure base directory of app\r\nbasedir = os.path.abspath(os.path.dirname(__file__))\r\n\r\n# Application configurations\r\napp = Flask(__name__)\r\napp.debug = True\r\napp.config['SECRET_KEY'] = 'hardtoguessstringfromsi364thisisnotsupersecure'\r\n## TODO SI364: Create a database in postgresql in the code line below, and fill in your app's database URI. It should be of the format: postgresql://localhost/YOUR_DATABASE_NAME\r\n\r\n## Your Postgres database should be your uniqname, plus HW4, e.g. \"jczettaHW4\" or \"maupandeHW4\"\r\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://localhost/alliwanHW4\"\r\napp.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True\r\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\r\n\r\n# Set up Flask debug stuff\r\nmanager = Manager(app)\r\ndb = SQLAlchemy(app) # For database use\r\n\r\n## Set up Shell context so it's easy to use the shell to debug\r\ndef make_shell_context():\r\n return dict(app=app, db=db, Tweet=Tweet, User=User, Hashtag=Hashtag) ## TODO SI364: Add your models to this shell context function so you can use them in the shell C\r\n # TODO SI364: Submit a screenshot of yourself using the shell to make a query for all the Tweets in the database.\r\n # Filling this in will make that easier!\r\n\r\n ###SET UP FLASK SHELL FOR MY APPLICATION! \r\n ##type in flask shell and write in t = tweet.query.all BUT DO THIS ONCE I HAVE TWEETS\r\n\r\n# Add function use to manager\r\nmanager.add_command(\"shell\", Shell(make_context=make_shell_context))\r\n\r\n\r\n#########\r\n######### Everything above this line is important/useful setup, not problem-solving.\r\n#########\r\n\r\n##### Set up Models #####\r\n\r\n## TODO SI364: Set up the following Model classes, with the respective fields (data types).\r\n\r\n## The following relationships should exist between them:\r\n# Tweet:User - Many:One\r\n# Tweet:Hashtag - Many:Many\r\n\r\n# - Tweet\r\n## -- id (Primary Key)\r\n## -- text (String, up to 285 chars)\r\n## -- user_id (Integer, ID of user posted)\r\n\r\n# - User\r\n## -- id (Primary Key)\r\n## -- twitter_username (String, up to 64 chars) (Unique=True)\r\n\r\n# - Hashtag\r\n## -- id (Primary Key)\r\n## -- text (Unique=True)\r\n\r\n# Association Table: Tweet_Hashtag\r\n# -- tweet_id\r\n# -- hashtag_id\r\n\r\n## NOTE: You'll have to set up database relationship code in either the Tweet table or the Hashtag table so that the association table for that many-many relationship will work properly!\r\n\r\n\r\ntwitterhashtags =db.Table('tweets_hashtags',db.Column ('tweet_id',db.Integer, db.ForeignKey ('Tweets.id')),db.Column('hashtag_id',db.Integer, db.ForeignKey('Hashtags.id')))\r\n\r\nclass Tweet(db.Model):\r\n __tablename__ = \"Tweets\"\r\n id = db.Column(db.Integer, primary_key=True)\r\n text = db.Column(db.String(285))\r\n user_id = db.Column(db.Integer)\r\n\r\n def __repr__(self):\r\n return \"{} tweeted: {}\".format(self.id,self.text)\r\n\r\n\r\nclass User(db.Model):\r\n __tablename__ = \"Users\"\r\n id = db.Column(db.Integer, primary_key = True)\r\n twitter_username = db.Column(db.String(64), unique=True)\r\n\r\n\r\nclass Hashtag(db.Model):\r\n __tablename__ = \"Hashtags\"\r\n id = db.Column(db.Integer, primary_key=True)\r\n text = db.Column(db.String(), unique=True)\r\n\r\n def __repr__(self):\r\n return \"{} by {}\".format(self.id,self.text)\r\n\r\n\r\ndef get_or_create_tweet(db_session, text, user_name, hashtags):\r\n user = get_or_create_user(db_session, user_name)\r\n tweet = db_session.query(Tweet).filter_by(text=text, user_id=user.id).first()\r\n for hashtag in hashtags:\r\n get_or_create_hashtag(db_session, hashtag)\r\n if tweet:\r\n return tweet\r\n else: \r\n tweet = Tweet(text=text, user_id=user.id)\r\n db_session.add(tweet)\r\n db_session.commit()\r\n return tweet\r\n\r\n## HINT: Your get_or_create_tweet function should invoke your get_or_create_user function AND your get_or_create_hashtag function. You'll have seen an example similar to this in class!\r\n\r\n\r\ndef get_or_create_user(db_session, twitter_username):\r\n user = db_session.query(User).filter_by(twitter_username=twitter_username).first()\r\n if user:\r\n return user\r\n else: \r\n user = User(twitter_username=twitter_username)\r\n db_session.add(user)\r\n db_session.commit()\r\n return user\r\n\r\ndef get_or_create_hashtag(db_session, text):\r\n hashtag = db_session.query(Hashtag).filter_by(text=text).first()\r\n if hashtag:\r\n return hashtag\r\n else: \r\n hashtag = Hashtag(text=text)\r\n db_session.add(hashtag)\r\n db_session.commit()\r\n return hashtag\r\n\r\n##### Set up Forms #####\r\n\r\n# TODO SI364: Fill in the rest of this Form class so that someone running this web app will be able to fill in information about tweets they wish existed to save in the database:\r\n\r\n## -- tweet text\r\n## -- the twitter username who should post it\r\n## -- a list of comma-separated hashtags it should have\r\n\r\nclass TweetForm(FlaskForm):\r\n submit = SubmitField('Submit')\r\n text = StringField(\"Enter Tweet here\")\r\n hashtag = StringField(\"Enter a list of comma-separated hashtags\")\r\n username = StringField(\"Enter username here\")\r\n\r\n\r\n##### Helper functions\r\n\r\n### For database additions / get_or_create functions\r\n\r\n## TODO SI364: Write get_or_create functions for each model -- Tweets, Hashtags, and Users.\r\n## -- Tweets should be identified by their text and user id,(e.g. if there's already a tweet with that text, by that user, then return it; otherwise, create it)\r\n## -- Users should be identified by their username (e.g. if there's already a user with that username, return it, otherwise; create it)\r\n## -- Hashtags should be identified by their text (e.g. if there's already a hashtag with that text, return it; otherwise, create it)\r\n\r\n## HINT: Your get_or_create_tweet function should invoke your get_or_create_user function AND your get_or_create_hashtag function. You'll have seen an example similar to this in class!\r\n\r\n## NOTE: If you choose to organize your code differently so it has the same effect of not encounting duplicates / identity errors, that is OK. But writing separate functions that may invoke one another is our primary suggestion.\r\n\r\n\r\n\r\n\r\n\r\n##### Set up Controllers (view functions) #####\r\n\r\n## Error handling routes - PROVIDED\r\n@app.errorhandler(404)\r\ndef page_not_found(e):\r\n return render_template('404.html'), 404\r\n\r\n\r\n@app.errorhandler(500)\r\ndef internal_server_error(e):\r\n return render_template('500.html'), 500\r\n\r\n## Main route\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef index():\r\n formform = TweetForm()\r\n if formform.validate_on_submit():\r\n oneUser = get_or_create_user(db.session, formform.username.data)\r\n if db.session.query(Tweet).filter_by(text=formform.text.data, user_id=oneUser.id).first():\r\n flash(\"That's already been tweeted! You can think of someothing new :)\")\r\n return redirect(url_for(\"see_all_tweets\"))\r\n get_or_create_tweet(db.session,formform.text.data, formform.username.data, formform.hashtag.data.split(\",\"))\r\n list_tweets = Tweet.query.all()\r\n return render_template('index.html', form=formform, num_tweets=len(list_tweets))\r\n\r\n ## TODO SI364: Fill in the index route as described.\r\n # A template index.html has been created and provided to render what this route needs to show -- YOU just need to fill in this view function so it will work.\r\n ## HINT: Check out the index.html template to make sure you're sending it the data it needs.\r\n\r\n\r\n # The index route should:\r\n # - Show the Tweet form.\r\n # - If you enter a tweet with identical text and username to an existing tweet, it should redirect you to the list of all the tweets and a message that you've already saved a tweet like that.\r\n\r\n ## ^ HINT: Invoke your get_or_create_tweet function\r\n ## ^ HINT: Check out the get_flashed_messages setup in the songs app you saw in class\r\n\r\n # This main page should ALSO show links to pages in the app (see routes below) that:\r\n # -- allow you to see all of the tweets posted\r\n # -- see all of the twitter users you've saved tweets for, along with how many tweets they have in your database\r\n\r\n@app.route('/all_tweets')\r\ndef see_all_tweets():\r\n list_of_tweets = Tweet.query.all()\r\n tweet_tuples = [(tweet.text, db.session.query(User).filter_by(id=tweet.user_id).first().twitter_username) for tweet in list_of_tweets]\r\n return render_template('all_tweets.html', all_tweets=tweet_tuples)\r\n\r\n # TODO SI364: Fill in this view function so that it can successfully render the template all_tweets.html, which is provided.\r\n ## HINT: Check out the all_songs and all_artists routes in the songs app you saw in class.\r\n\r\n\r\n@app.route('/all_users')\r\ndef see_all_users():\r\n list_users = User.query.all()\r\n user_tuples = [(user.twitter_username, len(db.session.query(Tweet).filter_by(user_id=user.id).all())) for user in list_users]\r\n return render_template('all_users.html', usernames=user_tuples) \r\n\r\n # TODO SI364: Fill in this view function so it can successfully render the template all_users.html, which is provided. (See instructions for more detail.)\r\n ## HINT: Check out the all_songs and all_artists routes in the songs app you saw in class.\r\n\r\n\r\nif __name__ == '__main__':\r\n db.create_all()\r\n manager.run() # Run with this: python main_app.py runserver\r\n # Also provides more tools for debugging\r\n","sub_path":"APWHW4/APWSI364_hw4.py","file_name":"APWSI364_hw4.py","file_ext":"py","file_size_in_byte":9953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"542606814","text":"import logging\nimport sys\nfrom PyQt5 import QtCore, QtWidgets\nfrom PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QPushButton, QPlainTextEdit\nfrom PyQt5.QtCore import QSize, pyqtSlot\n\n\nclass HelloWindow(QMainWindow):\n def __init__(self):\n QMainWindow.__init__(self)\n self.setMinimumSize(QSize(640, 480))\n self.setWindowTitle(\"Hello world\") \n \n centralWidget = QWidget(self)\n self.setCentralWidget(centralWidget) \n gridLayout = QGridLayout() \n centralWidget.setLayout(gridLayout)\n title = QLabel(\"Hello World from PyQt\", self)\n title.setAlignment(QtCore.Qt.AlignCenter)\n gridLayout.addWidget(title, 0, 0, 1, 2)\n\n logging_text_edit = QPlainTextEdit()\n gridLayout.addWidget(logging_text_edit, 2, 0, 1, 2)\n\n button = QPushButton(self)\n button.setText(\"Print!\")\n gridLayout.addWidget(button, 3, 0, QtCore.Qt.AlignHCenter)\n button.pressed.connect(self.add_logging)\n\n button = QPushButton(self)\n button.setText(\"Clear\")\n gridLayout.addWidget(button, 3, 1, QtCore.Qt.AlignHCenter)\n button.pressed.connect(logging_text_edit.clear)\n\n class QLogHandler(logging.Handler):\n def __init__(self):\n logging.Handler.__init__(self)\n\n def emit(self, record):\n record = self.format(record)\n logging_text_edit.appendPlainText(record)\n\n q_log_handler = QLogHandler()\n q_log_handler.setLevel(logging.DEBUG)\n q_log_handler.setFormatter(logging.Formatter('%(asctime)s\\n%(name)s\\n%(levelname)s:%(message)s\\n'))\n logging.basicConfig(level=logging.DEBUG)\n logging.getLogger('').addHandler(q_log_handler)\n\n @pyqtSlot()\n def add_logging(self):\n logging.info('you pressed the button')\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n mainWin = HelloWindow()\n mainWin.show()\n sys.exit( app.exec_() )","sub_path":"ex03-signal-slot/log-to-ui.py","file_name":"log-to-ui.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"338199706","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport soundfile as sf\nimport time\n\ndef dft(x):\n N = len(x)\n Y = []\n for i in range(N):\n y = 0j\n for n in range(N):\n y += x[n] * np.exp(-1j * 2 * np.pi * i * n / N)\n Y.append(y)\n\n return Y\n\nif __name__ == \"__main__\":\n # 音声信号の読み込み\n fname = \"wave/a_1.wav\"\n data, fs = sf.read(fname)\n\n t = np.arange(0, len(data)/fs , 1/fs)\n\n # 適当な長さで音声を切り取る\n center = len(data) // 2\n cuttime = 0.04\n x = data[int(center - cuttime/2 * fs):int(center + cuttime/2 * fs)]\n\n # ハミング窓をかける\n hamming = np.hamming(len(x)) \n x = x * hamming\n\n # 振幅スペクトルを求める\n t1 = time.time()\n N = 2048\n pad_x = np.hstack((x, np.zeros(N - len(x))))\n spec = np.abs(dft(pad_x))[:N//2]\n fscale = [k * fs / N for k in range(N)][:N//2]\n t2 = time.time()\n\n# print('実行時間: ', t2 - t1)\n\n plt.plot(fscale, spec)\n plt.xlabel(\"frequency [Hz]\")\n plt.ylabel(\"amplitude spetrum\")\n plt.show()\n","sub_path":"grad_resarch/grad_resarch/mfcc/source/dft.py","file_name":"dft.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"132626690","text":"def __bootstrap__():\n global __bootstrap__, __loader__, __file__\n import sys, pkg_resources, imp, atexit\n __file__ = pkg_resources.resource_filename(\n __name__,\n 'wrapped.cpython-36m-x86_64-linux-gnu.so',\n )\n __loader__ = None\n del __bootstrap__, __loader__\n imp.load_dynamic(__name__, __file__)\n\n__bootstrap__()\n","sub_path":"protopy/wrapped.py","file_name":"wrapped.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"124924467","text":"from django.forms import ModelForm\nfrom hr.models import Staff\nfrom datetime import date\nfrom django.core.exceptions import ValidationError\n\n\ndef calculate_age(born):\n today = date.today()\n return today.year - born.year - \\\n ((today.month, today.day) < (born.month, born.day))\n\n\nclass StaffForm(ModelForm):\n \"\"\"Класс для форм создания и измения объектов класса Staff.\"\"\"\n\n class Meta:\n model = Staff\n fields = ['department', 'fname', 'lname', 'bdate', 'email', 'photo']\n\n def clean_bdate(self):\n \"\"\" Возраст должен быть от 18 лет\"\"\"\n\n required_age = 18\n bdate = self.cleaned_data['bdate']\n if calculate_age(bdate) < required_age:\n raise ValidationError('Too young...')\n return bdate\n","sub_path":"tk/hr/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"183255628","text":"# -*- coding: utf-8 -*-\r\n##############################################################################\r\n#\r\n# OpenERP, Open Source Management Solution\r\n# Copyright (C) 2004-2010, 2014 Tiny SPRL ().\r\n#\r\n# This program is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU Affero General Public License as\r\n# published by the Free Software Foundation, either version 3 of the\r\n# License, or (at your option) any later version.\r\n#\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU Affero General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU Affero General Public License\r\n# along with this program. If not, see .\r\n#\r\n##############################################################################\r\nfrom openerp import models, fields, api, _\r\nfrom openerp.exceptions import ValidationError\r\nfrom dateutil.relativedelta import relativedelta\r\n\r\n\r\nclass ProductTemplate(models.Model):\r\n _inherit = 'product.template'\r\n\r\n min_stock = fields.Float(\r\n string=\"Min Stock\")\r\n max_stock = fields.Float(\r\n string=\"Max Stock\")\r\n\r\n @api.one\r\n @api.constrains('min_stock', 'max_stock')\r\n def _check_min_max_stock(self):\r\n if self.max_stock < self.min_stock:\r\n msg_error = \"The max stock could be more than min stock.\"\r\n raise ValidationError(_(msg_error))\r\n\r\n\r\nclass ProductProduct(models.Model):\r\n _inherit = 'product.product'\r\n\r\n @api.model\r\n def _cron_automatic_purchase(self):\r\n product_list = []\r\n for prod in self.search([]):\r\n if prod.virtual_available <= prod.min_stock and \\\r\n prod.min_stock != 0:\r\n product_list.append(prod)\r\n purchase = self.env['purchase.order']\r\n user = self.env['res.users'].browse(self.env.uid)\r\n if user.company_id.parent_id:\r\n company_id = user.company_id.parent_id\r\n else:\r\n company_id = user.company_id\r\n order_line = []\r\n pricelist_id = company_id.partner_id.property_product_pricelist_purchase\r\n journal_obj = self.env['account.journal']\r\n journal_id = journal_obj.search([('type', '=', 'purchase'),\r\n ('company_id', '=', company_id.id)],\r\n limit=1)\r\n for each_prod in product_list:\r\n product_qty = each_prod.max_stock - \\\r\n (each_prod.virtual_available + each_prod.min_stock)\r\n if product_qty:\r\n date_planned = fields.datetime.now()\r\n for supplier in each_prod.seller_ids:\r\n if company_id.partner_id.id and \\\r\n (supplier.name.id == company_id.partner_id.id):\r\n supplier_delay = int(supplier.delay)\r\n date_planned += relativedelta(days=supplier_delay)\r\n break\r\n if pricelist_id:\r\n price_unit = pricelist_id.price_get(each_prod.id,\r\n product_qty,\r\n company_id.partner_id.id)[pricelist_id.id]\r\n else:\r\n price_unit = each_prod.standard_price\r\n dummy, name = each_prod.name_get()[0]\r\n if each_prod.description_purchase:\r\n name += '\\n' + each_prod.description_purchase\r\n order_line.append((0, 0, {'name': name,\r\n 'product_id': each_prod.id,\r\n 'product_qty': product_qty,\r\n 'price_unit': price_unit,\r\n 'date_planned': date_planned}))\r\n location_id = self.env['stock.location'].search([('company_id', '=',\r\n company_id.id),\r\n ('usage', '=',\r\n 'internal')],\r\n limit=1)\r\n if order_line:\r\n vals = {'partner_id': company_id.partner_id.id,\r\n 'location_id': location_id.id,\r\n 'pricelist_id': pricelist_id.id,\r\n 'currency_id': company_id.currency_id.id,\r\n 'journal_id': journal_id.id,\r\n 'order_line': order_line}\r\n purchase.create(vals)\r\n","sub_path":"stock_product_purchase/models/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"105658910","text":"import flask\nfrom flask import Flask, jsonify, request\nimport json\napp = Flask(__name__)\n@app.route('/predict', methods=['GET'])\ndef predict():\n response = json.dumps({'response': 'yahhhh!'})\n return response, 200\nif __name__ == '__main__':\n application.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"540347046","text":"from Helper.Terminal import execute, execute_with_result\nfrom Database.Db import Db\nfrom Model.systemConfiguration import systemConfiguration\nfrom Cache.GlobalVariables import GlobalVariables\nimport datetime\nfrom HcServices.Mqtt import Mqtt\nfrom HcServices.Http import Http\nfrom Contracts.ITransport import ITransport\nfrom sqlalchemy import and_, or_\nfrom HcServices.Http import Http\nimport aiohttp\nimport asyncio\nimport Constant.constant as const\nimport http\nimport json\nimport logging\n\n\ndef time_split(time: datetime.datetime):\n m = str(time.month)\n if int(m) < 10:\n m = \"0\" + m\n\n d = str(time.day)\n if int(d) < 10:\n d = \"0\" + d\n\n update_day = int(str(time.year) + m + d)\n update_time = 60 * time.hour + time.minute\n return update_day, update_time\n\n\ndef ping_google():\n rel = execute_with_result(\"ping -c3 www.google.com|grep packet\")[1]\n try:\n rel2 = rel.split(\", \")\n rel3 = rel2[2].split(\" \")\n r = rel3[0] == \"0%\"\n except:\n r = False\n return r\n\n\ndef eliminate_current_progress():\n s = execute_with_result(f'ps | grep python3')\n dt = s[1].split(\" \")\n current_progress_port = \"\"\n for i in range(len(dt)):\n if dt[i] != \"\":\n current_progress_port = dt[i]\n break\n execute(f'kill -9 {current_progress_port}')\n\n\ndef check_and_kill_all_repeat_progress():\n s = execute_with_result(f'ps|grep python3')\n current_self_repeat_process_list_info = s[1].split(\"\\n\")\n current_self_repeat_process_list_port = []\n for i in range(len(current_self_repeat_process_list_info)):\n p = current_self_repeat_process_list_info[i].split(\" \")\n if p[len(p) - 1] != \"RDhcPy/main.py\":\n continue\n current_self_repeat_process_list_port.append(p[1])\n\n if len(current_self_repeat_process_list_port) > 1:\n kill_all_cmd = \"kill -9\"\n for i in range(len(current_self_repeat_process_list_port)):\n kill_all_cmd = kill_all_cmd + \" \" + current_self_repeat_process_list_port[i]\n execute(kill_all_cmd)\n\n\nclass System:\n __db = Db()\n __globalVariables = GlobalVariables()\n __logger = logging.Logger\n\n def __init__(self, logger: logging.Logger):\n self.__logger = logger\n\n def get_gateway_mac(self):\n mac_len = 17\n s = execute_with_result('ifconfig')\n dt = s[1].split(\"\\n\")\n for i in dt:\n if str(i).find(\"eth0\") != -1:\n last_mac_character = len(i) -2\n self.__globalVariables.GatewayMac = i[last_mac_character-mac_len:last_mac_character]\n break\n return\n\n async def send_http_request_to_gw_online_status_url(self, h: Http):\n token = await self.__get_token(h)\n cookie = f\"Token={token}\"\n heartbeat_url = const.SERVER_HOST + const.SIGNALR_GW_HEARTBEAT_URL\n header = h.create_new_http_header(cookie=cookie, domitory_id=self.__globalVariables.DormitoryId)\n gw_report_body_data = {\n \"macAddress\": self.__globalVariables.GatewayMac\n }\n req = h.create_new_http_request(url=heartbeat_url, header=header, body_data=gw_report_body_data)\n session = aiohttp.ClientSession()\n res = await h.post(session, req)\n try:\n data = await res.json()\n self.__logger.info(f\"ping hc status: {data}\")\n except: \n self.__logger.debug(f\"fail to ping hc\")\n await session.close()\n\n async def __check_and_reconnect_signalr_when_change_wifi(self, signalr: ITransport):\n while not ping_google():\n await asyncio.sleep(2)\n while not self.__globalVariables.PingCloudSuccessFlag:\n await asyncio.sleep(2)\n try:\n signalr.disconnect()\n except:\n eliminate_current_progress()\n\n def update_current_wifi_name(self):\n s = execute_with_result('iwinfo')\n dt = s[1].split(\"\\n\")\n if str(dt[0]).find(\"RD_HC\") == -1:\n wifi_name_started_point = str(dt[0]).find('\"') + 1\n wifi_name_ended_point = str(dt[0]).find('\"', wifi_name_started_point) - 1\n self.__globalVariables.CurrentWifiName = str(dt[0])[wifi_name_started_point:wifi_name_ended_point+1]\n\n async def check_wifi_change(self, signalr: ITransport):\n s = execute_with_result('iwinfo')\n dt = s[1].split(\"\\n\")\n wifi_name = \"\"\n if str(dt[0]).find(\"RD_HC\") == -1:\n wifi_name_started_point = str(dt[0]).find('\"') + 1\n wifi_name_ended_point = str(dt[0]).find('\"', wifi_name_started_point) - 1\n wifi_name = str(dt[0])[wifi_name_started_point:wifi_name_ended_point + 1]\n if wifi_name != \"\" and wifi_name != self.__globalVariables.CurrentWifiName:\n self.__logger.info(f\"current wifi name change from {self.__globalVariables.CurrentWifiName} to {wifi_name}\")\n print(f\"current wifi name change from {self.__globalVariables.CurrentWifiName} to {wifi_name}\")\n await self.__check_and_reconnect_signalr_when_change_wifi(signalr)\n\n async def update_reconnect_status_to_db(self, reconnect_time: datetime.datetime):\n rel = self.__db.Services.SystemConfigurationServices.FindSysConfigurationById(id=1)\n r = rel.fetchone()\n s = systemConfiguration(IsConnect=True, DisconnectTime=r['DisconnectTime'], ReconnectTime=reconnect_time,\n IsSync=r['IsSync'])\n self.__db.Services.SystemConfigurationServices.UpdateSysConfigurationById(id=1, sysConfig=s)\n await self.__push_data_to_cloud(r['DisconnectTime'], s)\n\n def update_disconnect_status_to_db(self, disconnect_time: datetime.datetime):\n s = systemConfiguration(IsConnect=False, DisconnectTime=disconnect_time, ReconnectTime=None, IsSync=False)\n if disconnect_time is None:\n s.DisconnectTime = datetime.datetime.now()\n rel = self.__db.Services.SystemConfigurationServices.FindSysConfigurationById(id=1)\n r = rel.fetchone()\n if r is None:\n self.__db.Services.SystemConfigurationServices.AddNewSysConfiguration(s)\n if r is not None and r[\"IsSync\"] != \"False\":\n self.__db.Services.SystemConfigurationServices.UpdateSysConfigurationById(id=1, sysConfig=s)\n\n async def recheck_reconnect_status_of_last_activation(self):\n if not self.__globalVariables.RecheckConnectionStatusInDbFlag:\n rel = self.__db.Services.SystemConfigurationServices.FindSysConfigurationById(id=1)\n r = rel.fetchone()\n\n if r is None:\n s = systemConfiguration(IsConnect=True, DisconnectTime=datetime.datetime.now(),\n ReconnectTime=datetime.datetime.now(), IsSync=True)\n self.__db.Services.SystemConfigurationServices.AddNewSysConfiguration(s)\n self.__globalVariables.RecheckConnectionStatusInDbFlag = True\n return\n\n s = systemConfiguration(IsConnect=r[\"IsConnect\"], DisconnectTime=r['DisconnectTime'],\n ReconnectTime=r['ReconnectTime'], IsSync=r['IsSync'])\n\n if r[\"ReconnectTime\"] is None:\n reconnectTime = datetime.datetime.now()\n await self.update_reconnect_status_to_db(reconnectTime)\n s.ReconnectTime = reconnectTime\n s.IsConnect = True\n ok = await self.__push_data_to_cloud(r[\"DisconnectTime\"], s)\n if ok:\n self.__globalVariables.RecheckConnectionStatusInDbFlag = True\n return\n\n if r[\"ReconnectTime\"] is not None and r[\"IsSync\"] == \"False\":\n s.IsConnect = True\n ok = await self.__push_data_to_cloud(r[\"DisconnectTime\"], s)\n if ok:\n self.__globalVariables.RecheckConnectionStatusInDbFlag = True\n return\n self.__globalVariables.RecheckConnectionStatusInDbFlag = True\n return\n\n async def send_http_request_to_heartbeat_url(self, h: Http):\n heartbeat_url = const.SERVER_HOST + const.SIGNSLR_HEARDBEAT_URL\n header = h.create_new_http_header(cookie='', domitory_id=self.__globalVariables.DormitoryId)\n req = h.create_new_http_request(url=heartbeat_url, header=header)\n session = aiohttp.ClientSession()\n res = await h.post(session, req)\n await session.close()\n try:\n if res.status == http.HTTPStatus.OK:\n return True\n except:\n return False\n\n async def __get_token(self, http: Http):\n refresh_token = self.__globalVariables.RefreshToken\n if refresh_token == \"\":\n return \"\"\n token_url = const.SERVER_HOST + const.TOKEN_URL\n cookie = f\"RefreshToken={refresh_token}\"\n header = http.create_new_http_header(cookie=cookie, domitory_id=self.__globalVariables.DormitoryId)\n req = http.create_new_http_request(url=token_url, header=header)\n session = aiohttp.ClientSession()\n res = await http.post(session, req)\n token = \"\"\n if res != \"\":\n try:\n data = await res.json()\n token = data['token']\n except:\n return \"\"\n await session.close()\n return token\n\n async def __push_data_to_cloud(self, reference_time: datetime.datetime, dt: systemConfiguration):\n t = time_split(time=reference_time)\n update_day = t[0]\n update_time = t[1]\n print(f\"updateDay: {update_day}, updateTime: {update_time}\")\n\n rel = self.__db.Services.DeviceAttributeValueServices.FindDeviceAttributeValueWithCondition(\n or_(and_(self.__db.Table.DeviceAttributeValueTable.c.UpdateDay == update_day,\n self.__db.Table.DeviceAttributeValueTable.c.UpdateTime >= update_time),\n self.__db.Table.DeviceAttributeValueTable.c.UpdateDay > update_day))\n data = []\n for r in rel:\n if r['DeviceId'] == \"\" or r['DeviceAttributeId'] is None or r['Value'] is None:\n continue\n d = {\n \"deviceId\": r['DeviceId'],\n \"deviceAttributeId\": r['DeviceAttributeId'],\n \"value\": r['Value']\n }\n data.append(d)\n if not data:\n print(\"have no data to push\")\n self.__logger.info(\"have no data to push\")\n self.__update_sync_data_status_success_to_db(dt)\n return True\n\n data_send_to_cloud = json.dumps(data)\n print(f\"data push to cloud: {data_send_to_cloud}\")\n self.__logger.info(f\"data push to cloud: {data_send_to_cloud}\")\n res = await self.__send_http_request_to_push_url(data=data_send_to_cloud)\n print(f\"push data response: {res}\")\n self.__logger.info(f\"pull data response: {res}\")\n if res == \"\":\n print(\"Push data failure\")\n self.__logger.info(\"Push data failure\")\n self.__update_sync_data_status_fail_to_db(dt)\n return False\n\n if (res != \"\") and (res.status == http.HTTPStatus.OK):\n self.__update_sync_data_status_success_to_db(dt)\n print(\"Push data successfully\")\n self.__logger.info(\"Push data successfully\")\n return True\n\n print(\"Push data failure\")\n self.__logger.info(\"Push data failure\")\n self.__update_sync_data_status_fail_to_db(dt)\n return False\n\n async def __send_http_request_to_push_url(self, data: str):\n h = Http()\n token = await self.__get_token(h)\n cookie = f\"Token={token}\"\n pull_data_url = const.SERVER_HOST + const.CLOUD_PUSH_DATA_URL\n header = h.create_new_http_header(cookie=cookie, domitory_id=self.__globalVariables.DormitoryId)\n req = h.create_new_http_request(url=pull_data_url, body_data=json.loads(data), header=header)\n session = aiohttp.ClientSession()\n res = await h.post(session, req)\n await session.close()\n return res\n\n def __update_sync_data_status_success_to_db(self, s: systemConfiguration):\n s.IsSync = True\n self.__db.Services.SystemConfigurationServices.UpdateSysConfigurationById(id=1, sysConfig=s)\n\n def __update_sync_data_status_fail_to_db(self, s: systemConfiguration):\n s.IsSync = False\n self.__db.Services.SystemConfigurationServices.UpdateSysConfigurationById(id=1, sysConfig=s)\n","sub_path":"Helper/System.py","file_name":"System.py","file_ext":"py","file_size_in_byte":12434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"190195934","text":"# -*- coding:utf-8 -*-\n# @version: 1.0\n# @author: wuxikun\n# @date: '2020/10/18 10:22 AM'\n\n\nimport numpy as np\nimport tensorflow as tf\n\ndata = np.random.randn(10, 28, 28, 1)\n\nx = tf.constant(data)\nsame_conv = tf.layers.conv2d(x, 32, 5, padding=\"SAME\")\nvalid_conv = tf.layers.conv2d(x, 32, 5, padding=\"VALID\")\n\nrandom_initializer = tf.random_normal_initializer(0.0, 0.001)\nfilter = tf.get_variable(\"filter\", shape=[6, 6, 1, 32], initializer=random_initializer)\nhis_conv2d = tf.nn.conv2d(tf.cast(x, tf.float32), filter, strides=[1, 1, 1, 1], padding=\"VALID\")\n\nfilter2 = tf.get_variable(\"filter2\", shape=[6, 6, 32, 64], initializer=random_initializer)\nhis_conv2d_2 = tf.nn.conv2d(tf.cast(his_conv2d, tf.float32), filter2, strides=[1, 1, 1, 1], padding=\"VALID\")\n\ninit = tf.global_variables_initializer()\nwith tf.Session() as sess:\n sess.run(init)\n\n print(same_conv.shape)\n print(valid_conv.shape)\n\n print(his_conv2d.shape)\n print(his_conv2d_2.shape)\n","sub_path":"conv_lr.py","file_name":"conv_lr.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"238803033","text":"class Bank:\n\n def __init__(self):\n self.name = \" \"\n self.age = \" \"\n self.address = \" \"\n self.phone = \" \"\n self.branch = \" \"\n\n self.result = 0\n self.balance = 0\n\n def details(self):\n\n self.name = input(\"Name \\n\")\n self.age = int(input(\"Age\\n\"))\n self.address = input(\"Address\\n\")\n self.phone = int(input(\" phone\\n\"))\n self.branch = input(\"Branch\")\n\n def deposit(self):\n amount = float(input(\"Deposit \"))\n self.balance += amount\n print(\" \\n Amount Deposited:\", amount)\n\n def withdraw(self):\n\n amount = float(input(\"Enter amount to be Withdrawn: \"))\n if self.balance >= amount:\n self.balance -= amount\n print(\" \\n You Withdraw:\", amount)\n else:\n print(\" \\n Insufficient balance\")\n\n def display(self):\n\n print(\" \\n Net Available Balance=\", self.balance)\n\n def bankdata(Bank):\n self.branchname = \" \"\n self.branchcode = \" \"\n self.IFSCcode=\" \"\n self.address = \" \"\n self.phone = \" \"\n\n\n def details(self):\n\n self.name = input(\"Name \\n\")\n self.branchcode = int(input(\"branchcode\\n\"))\n self.address = input(\"Address\\n\")\n self.phone = int(input(\" phone\\n\"))\n self.branch = input(\"Branch\")\n\n","sub_path":"dinesh/bank1.py","file_name":"bank1.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"234635130","text":"# Copyright 2018-2020 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport re\nimport unittest\nfrom unittest.mock import patch, MagicMock\nfrom git.exc import InvalidGitRepositoryError\n\nfrom streamlit.git_util import GITHUB_HTTP_URL, GITHUB_SSH_URL, GitRepo\n\n\nclass GitUtilTest(unittest.TestCase):\n def test_https_url_check(self):\n # standard https url\n self.assertTrue(\n re.search(GITHUB_HTTP_URL, \"https://github.com/username/repo.git\")\n )\n\n # with www\n self.assertTrue(\n re.search(GITHUB_HTTP_URL, \"https://www.github.com/username/repo.git\")\n )\n\n # not http\n self.assertFalse(\n re.search(GITHUB_HTTP_URL, \"http://www.github.com/username/repo.git\")\n )\n\n # no .git\n self.assertFalse(\n re.search(GITHUB_HTTP_URL, \"http://www.github.com/username/repo\")\n )\n\n def test_ssh_url_check(self):\n # standard ssh url\n self.assertTrue(re.search(GITHUB_SSH_URL, \"git@github.com:username/repo.git\"))\n\n # no .git\n self.assertFalse(re.search(GITHUB_SSH_URL, \"git@github.com:username/repo\"))\n\n def test_git_repo_invalid(self):\n with patch(\"git.Repo\") as mock:\n mock.side_effect = InvalidGitRepositoryError(\"Not a git repo\")\n repo = GitRepo(\".\")\n self.assertFalse(repo.is_valid())\n\n def test_git_repo_valid(self):\n with patch(\"git.Repo\") as mock, patch(\"os.path\"):\n mock.git.return_value = MagicMock()\n repo = GitRepo(\".\")\n self.assertTrue(repo.is_valid())\n","sub_path":"lib/tests/streamlit/git_util_test.py","file_name":"git_util_test.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"277824579","text":"from konlpy import tag\nimport pandas as pd\n\n\ndef file_open(DATA_DIR):\n title_list = None\n try:\n data = pd.read_excel(DATA_DIR, sheet_name='Sheet1')\n title_list = data['text']\n except:\n print(\"엑셀 파일 열기 실패. 파일을 확인해 주세요.\")\n return title_list\n\n\n\ndef test(titles):\n test_title_list = titles[:20]\n okt = tag.Okt()\n for title in test_title_list:\n print(okt.pos(title))\n\n\ndef decompose(titles):\n okt = tag.Okt()\n for title in titles:\n print(okt.morphs(title))\n\nif __name__ == \"__main__\":\n test()\n","sub_path":"Data_Preprocess/Tokenize/korean_decompose.py","file_name":"korean_decompose.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"399892822","text":"import tflearn\nimport tensorflow as tf\nimport numpy as np\nfrom tflearn.data_utils import image_preloader\nfrom tflearn.layers.core import input_data, dropout, fully_connected, flatten\nfrom tflearn.layers.conv import conv_2d, max_pool_2d\nfrom tflearn.layers.normalization import local_response_normalization\nfrom tflearn.layers.estimator import regression\n\ntest = 'test'\ntrain = 'training'\n\ndef getXY():\n X, Y = image_preloader(train, image_shape=(80, 80), mode='folder', categorical_labels='True', normalize=True)\n return X, Y\n\nnetwork = tflearn.input_data(shape=[None, 120, 80, 80, 3], name='input')\nnetwork = tflearn.conv_3d(network, 32, (3, 3, 3), activation='relu')\nnetwork = tflearn.max_pool_3d(network, (1, 2, 2), strides=(1, 2, 2))\nnetwork = tflearn.conv_3d(network, 64, (3, 3, 3), activation='relu')\nnetwork = tflearn.max_pool_3d(network, (1, 2, 2), strides=(1, 2, 2))\nnetwork = tflearn.conv_3d(network, 128, (3, 3, 3), activation='relu')\nnetwork = tflearn.conv_3d(network, 128, (3, 3, 3), activation='relu')\nnetwork = tflearn.max_pool_3d(network, (1, 2, 2), strides=(1, 2, 2))\nnetwork = tflearn.conv_3d(network, 256, (2, 2, 2), activation='relu')\nnetwork =tflearn.conv_3d(network, 256, (2, 2, 2), activation='relu')\nnetwork = tflearn.max_pool_3d(network, (1, 2, 2), strides=(1, 2, 2))\n\n\n\nnetwork = tflearn.conv_2d(network, 64, 4, activation='relu', regularizer=\"L2\")\nnetwork = tflearn.max_pool_2d(network, 2)\nnetwork = tflearn.local_response_normalization(network)\nnetwork = fully_connected(network, 128, activation='tanh')\nnetwork = dropout(network, 0.8)\nnetwork = fully_connected(network, 256, activation='tanh')\nnetwork = dropout(network, 0.8)\nnetwork = tflearn.reshape(network, [-1, 1, 256])\n\nnetwork = tflearn.lstm(network, 128, return_seq=True)\nnetwork = tflearn.lstm(network, 128)\nnetwork = tflearn.fully_connected(network, 4, activation='softmax')\nnetwork = tflearn.regression(network, optimizer='adam', loss='categorical_crossentropy',\n name='target')\n\nmodel = tflearn.DNN(network, tensorboard_verbose=0)\nX, Y = getXY()\nmodel.fit(X, Y, n_epoch=1, validation_set=0.1, show_metric=True, snapshot_step=100)","sub_path":"architecture.py","file_name":"architecture.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"59519236","text":"import numpy as np\n\n\ndef get_grid_possibilities_with_next_word(grid_state, word_array, remaining_grid_possibilities):\n \"\"\"Computes possible grids for a given original grid state and word\n\n Args:\n grid_state (char array): Defines the initial content of the grid\n word_array (char array): The word to add in the grid\n remaining_grid_possibilities (dict): A dictionary of free word positions in the grid\n\n Returns:\n next_step_options ([char array, dict]): A list containing couples of new grid state with the word\n in it and remaining free word position for the given grid\n \"\"\"\n\n next_step_options = []\n # Length of current word to fit\n word_len = len(word_array)\n # Filter of possible ways to write word in grid, based on size only\n good_len_pos = remaining_grid_possibilities[word_len]\n\n # Loop through all word possibilities\n for current_key in good_len_pos.keys():\n for possible_pos in good_len_pos[current_key]:\n # Does the word fit?\n grid_state_at_chosen_position = grid_state[possible_pos]\n test_word_fit = word_can_fit_check(grid_state_at_chosen_position, word_array)\n # If word fit, return grid with updated word and updated list of grid remaining possibilities\n if test_word_fit:\n # update grid\n grid_state_with_word = grid_state.copy()\n grid_state_with_word[possible_pos] = word_array\n # update possible positions\n remaining_grid_possition_good_len = good_len_pos.copy()\n remaining_grid_possibilities_with_word = remaining_grid_possibilities.copy()\n del remaining_grid_possition_good_len[current_key]\n remaining_grid_possibilities_with_word[word_len] = remaining_grid_possition_good_len\n # Add the possibility to the next step option\n next_step_options.append([grid_state_with_word, remaining_grid_possibilities_with_word])\n return next_step_options\n\n\ndef word_can_fit_check(local_grid_state, word_array):\n \"\"\"Checks if a word fits at a given grid position\n\n Args:\n local_grid_state (char array): Value of the grid at the position the word is being checked\n word_array (char array): The word to add in the grid\n\n Returns:\n test_global (bool): Can the word fit? True for success, False otherwise.\n \"\"\"\n\n # For each letter, it is compatible with the grid if the same letter is already in the grid\n # or if the grid is empty '#' at this position.\n test_by_char = (local_grid_state == '#') | (local_grid_state == word_array)\n test_global = np.all(test_by_char)\n return test_global\n\n\ndef solve_grid(grid_state, words_to_place, dict_grid_possibilities, word_id):\n \"\"\"Recursive function called to solve the grid\n\n Args:\n grid_state (char array): Initial content of the grid\n words_to_place (string array): List of words to be placed in the grid\n dict_grid_possibilities (dict): Available free position in the current grid state\n word_id (int): Index number of the current word to be placed\n\n Returns:\n None\n \"\"\"\n\n # Get all feasible grid configurations with the current word being placed\n all_current_pos = get_grid_possibilities_with_next_word(grid_state,\n list(words_to_place[word_id]),\n dict_grid_possibilities)\n # If no feasible configurations exist, return 0\n if len(all_current_pos) == 0:\n return 0\n # If possible configurations exist, then:\n else:\n # If the word is the last word to place. Print the completed grid. Display a happy message.\n if word_id == (len(words_to_place)-1):\n print('VICTORY')\n print(all_current_pos[0][0])\n return 0\n # If the word is not the last one to place; for all possibilities to place it, make a recursive call\n # to the solve_grid function.\n else:\n for checked_pos in all_current_pos:\n # This print allows rough estimation of the solving speed\n if word_id == 0:\n print('TIC')\n solve_grid(checked_pos[0], words_to_place, checked_pos[1], word_id+1)\n\n\nif __name__ == '__main__':\n # Initializes the grid as empty\n defGrid = np.array(list('#'*(9*13)))\n # Defines words positions in the grid\n grid_configuration = {4: {0: [[0, 1, 2, 3], [3, 2, 1, 0]],\n 1: [[27, 28, 29, 30], [30, 29, 28, 27]],\n 2: [[45, 46, 47, 48], [48, 47, 46, 45]],\n 3: [[68, 69, 70, 71], [71, 70, 69, 68]],\n 4: [[86, 87, 88, 89], [89, 88, 87, 86]],\n 5: [[113, 114, 115, 116], [116, 115, 114, 113]],\n 6: [[0, 9, 18, 27], [27, 18, 9, 0]],\n 7: [[45, 54, 63, 72], [72, 63, 54, 45]],\n 8: [[29, 38, 47, 56], [56, 47, 38, 29]],\n 9: [[3, 12, 21, 30], [30, 21, 12, 3]],\n 10: [[86, 95, 104, 113], [113, 104, 95, 86]],\n 11: [[60, 69, 78, 87], [87, 78, 69, 60]],\n 12: [[44, 53, 62, 71], [71, 62, 53, 44]],\n 13: [[89, 98, 107, 116], [116, 107, 98, 89]]\n },\n 5: {14: [[12, 13, 14, 15, 16], [16, 15, 14, 13, 12]],\n 15: [[40, 41, 42, 43, 44], [44, 43, 42, 41, 40]],\n 16: [[56, 57, 58, 59, 60], [60, 59, 58, 57, 56]],\n 17: [[72, 73, 74, 75, 76], [76, 75, 74, 73, 72]],\n 18: [[100, 101, 102, 103, 104], [104, 103, 102, 101, 100]],\n 19: [[73, 82, 91, 100, 109], [109, 100, 91, 82, 73]],\n 20: [[48, 57, 66, 75, 84], [84, 75, 66, 57, 48]],\n 21: [[32, 41, 50, 59, 68], [68, 59, 50, 41, 32]],\n 22: [[7, 16, 25, 34, 43], [43, 34, 25, 16, 7]]\n }\n }\n # Defines words to place in the grid\n word_list = ['ABLE', 'AXIS', 'CALF', 'EVEN', 'LAWN', 'PAIR', 'PILL', 'TIDY', 'TUBA', 'TURF', 'ZEST', 'ZINC',\n 'BHAJI', 'CIVIL', 'EQUAL', 'IRISH', 'MANIC', 'QUICK', 'SITAR', 'YACHT']\n\n # Solve for the grid\n solve_grid(defGrid, word_list, grid_configuration, 0)\n","sub_path":"ep2_crossword/crosswd.py","file_name":"crosswd.py","file_ext":"py","file_size_in_byte":6751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"190882621","text":"## this script splits the asap_aes dataset and normalizes the scores\n\nimport csv\nimport math\n\n## read all lines\nheader_list = None;\ndata_list = [];\nwith open(\"source/asap_aes.csv\", \"rb\") as f:\n reader = csv.reader(f)\n for i, line in enumerate(reader):\n if(i == 0): \n header_list = line;\n else:\n data_list.append(line);\n\n #if(i>10): break;\n if(i % 1000 == 0): print(\"reading line \" + str(i))\n \n\n## group by essay set\nessay_set_index = header_list.index(\"essay_set\");\nessay_sets = dict();\nfor i, line in enumerate(data_list):\n this_set_index = line[essay_set_index];\n if(this_set_index not in essay_sets): essay_sets[this_set_index] = [];\n essay_sets[this_set_index].append(line);\n if(i % 1000 == 0): print(\"grouping line \" + str(i))\n \n\n## find max score for each dataset\ndef find_max_score_in_set(essay_set):\n score_index = header_list.index(\"domain1_score\");\n max_score = 0;\n for i, line in enumerate(essay_set):\n this_score = (line[score_index]);\n if(this_score == \"\"): continue;\n this_score = int(this_score);\n print(this_score);\n if(this_score > max_score): max_score = this_score;\n return max_score;\nmax_scores = dict();\nfor essay_set_key in essay_sets.keys():\n print(\"finding max score for \" + essay_set_key);\n max_scores[essay_set_key] = find_max_score_in_set(essay_sets[essay_set_key]);\nprint(\"max_scores:\");\nprint(max_scores);\n\n## Normalize score of each dataset out of max score and strip irrelevant information (lines 3+)\ndef normalize_scores_in_set(essay_set, max_score):\n score_index = header_list.index(\"domain1_score\");\n normalized_essay_set = [];\n for i, line in enumerate(essay_set):\n normalized_line = line[:3];\n this_score = line[score_index];\n if(this_score == \"\"): continue;\n normalized_score = int(this_score)/float(max_score);\n normalized_score = math.ceil(normalized_score * 100.0) / 100.0;\n normalized_line.append(normalized_score);\n normalized_line[2], normalized_line[3] = normalized_line[3], normalized_line[2] # puts score value before essay text\n print(normalized_score);\n normalized_essay_set.append(normalized_line);\n \n return normalized_essay_set;\nnormalized_essay_sets = dict();\nfor essay_set_key in essay_sets.keys():\n print(\"normalizing \" + essay_set_key);\n normalized_essay_sets[essay_set_key] = normalize_scores_in_set(essay_sets[essay_set_key], max_scores[essay_set_key]);\n#print(normalized_essay_sets);\n\n## save essay sets in distinct files and save one with all\ndef save_this_normalized_essay_set(essay_set, set_key):\n with open(\"essay_sets/essay_set_\"+str(set_key)+\".csv\", \"w+\") as file:\n writer = csv.writer(file);\n for line in essay_set:\n writer.writerow(line); \nall_sets = [];\nfor essay_set_key in normalized_essay_sets.keys():\n print(\"recording \" + essay_set_key);\n this_essay_set = normalized_essay_sets[essay_set_key];\n save_this_normalized_essay_set(this_essay_set, essay_set_key);\n all_sets.extend(this_essay_set);\nprint(\"recording \" + \"all\");\nsave_this_normalized_essay_set(all_sets, \"all\");","sub_path":"feature_engineering/preprocess_input/asap_aes/split_and_normalize.py","file_name":"split_and_normalize.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"298798743","text":"# Visualizer for LIDAR output from robot.\nimport threading\nfrom networktables import NetworkTables\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport time\nimport matplotlib\nfrom matplotlib.patches import Polygon\nfrom matplotlib.collections import PatchCollection\nimport matplotlib.animation as animation\n\n# Configure the ip address below and then run. Make sure you\n# have matplotlib, numpy, and networktables installed.\n# This program requires that enableDashboardOutput() is set\n# to true in the lidar class in robot code.\nroborio_ip = '169.254.250.49'\n\n\n\n\ncond = threading.Condition()\nnotified = [False]\n\ndef connectionListener(connected, info):\n print(info, '; Connected=%s' % connected)\n with cond:\n notified[0] = True\n cond.notify()\n\nNetworkTables.initialize(server=roborio_ip)\nNetworkTables.addConnectionListener(connectionListener, immediateNotify=True)\n\nwith cond:\n print(\"Waiting\")\n if not notified[0]:\n cond.wait()\n\n# Insert your processing code here\nprint(\"Connected!\")\ntable = NetworkTables.getTable('SmartDashboard')\nfig = plt.figure()\n\nax1 = fig.add_subplot(1,1,1)\nt = None\ndef animate(j):\n global t\n angles = table.getNumberArray(\"Angles\", [])\n distances = table.getNumberArray(\"Distances\", [])\n objx = table.getNumberArray(\"objx\", [])\n objy = table.getNumberArray(\"objy\", [])\n polarpts = []\n points = (int) (table.getNumber(\"Points\", 0))\n for i in range(0,min(points,len(angles),len(distances))):\n polarpts.append([angles[i],distances[i]])\n polarpts.sort()\n pts = []\n for i in range(0,len(polarpts)):\n x = polarpts[i][1] * np.cos(polarpts[i][0] * 0.0174533)\n y = polarpts[i][1] * np.sin(polarpts[i][0] * 0.0174533)\n pts.append([x,y])\n pt = np.array(pts)\n if t is not None:\n t.remove()\n t = Polygon(pt,color='cyan', zorder=1)\n ax1.clear()\n ax1.add_patch(t)\n ax1.scatter([c[0] for c in pts],[c[1] for c in pts], c='red', zorder=10, alpha=0.7)\n ax1.scatter(objx,objy, c='yellow', zorder=10, alpha=0.5,s=700)\n ax1.scatter([0],[0], c='green', zorder=11)\n ax1.text(-250, 250, points, fontsize=12)\n ax1.set_xlim([-300,300])\n ax1.set_ylim([-300,300])\n\nani = animation.FuncAnimation(fig, animate, interval=100)\nplt.show()","sub_path":"lidar_visualizer.py","file_name":"lidar_visualizer.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"337765493","text":"import itertools\nimport json\nfrom typing import Optional, List\nimport requests\n\nNLU_URL = \"http://localhost:5001/model/parse\"\n\n\nclass architecture:\n def __init__(self, name: str, requirements: List[str]):\n self.name = name\n self.requirements = requirements\n\n def get_name(self):\n return self.name\n\n def get_requirements(self):\n return self.requirements\n\n\nclass architecture_finder:\n def __init__(self, requirements=None):\n self.found_architectures = {}\n self.user_requirements = requirements if requirements else []\n\n def add_requirement(self, requirement: str):\n self.user_requirements.append(requirement)\n\n def find_architecture(self) -> Optional[str]:\n found_arch_name = \"\"\n found_arch_reqs = []\n arch_confidence = 0\n if len(self.user_requirements) > 2:\n for r in range(3, len(self.user_requirements) + 1):\n for reqs_combination in list(itertools.combinations(self.user_requirements, r)):\n text = \"\"\n for req in reqs_combination:\n text += req + \", \"\n response = requests.post(NLU_URL, data=json.dumps({\"text\": text})).json()\n if response[\"intent\"][\"confidence\"] > arch_confidence or \\\n (response[\"intent\"][\"confidence\"] == arch_confidence and\n len(found_arch_reqs) < len(reqs_combination)):\n found_arch_name = response[\"intent\"][\"name\"]\n found_arch_reqs = reqs_combination\n arch_confidence = response[\"intent\"][\"confidence\"]\n\n else:\n return None\n self.found_architectures[len(self.found_architectures.keys()) + 1] = {\"name\": found_arch_name,\n \"requirements\": list(found_arch_reqs)}\n for req in found_arch_reqs:\n self.user_requirements.remove(req)\n return found_arch_name\n\n def clear_requirements(self):\n self.user_requirements.clear()\n self.found_architectures.clear()\n\n def get_last_architecture(self) -> Optional[str]:\n return self.found_architectures[len(self.found_architectures.keys())][\"name\"] if len(self.found_architectures.keys()) > 0 else None\n\n","sub_path":"tour/arch_designer.py","file_name":"arch_designer.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"291345524","text":"# This file is part of Tryton. The COPYRIGHT file at the top level of\n# this repository contains the full copyright notices and license terms.\nfrom sql.functions import CurrentTimestamp\n\nfrom trytond.model import ModelView, Workflow, fields\nfrom trytond.pool import PoolMeta\nfrom trytond.transaction import Transaction\n\n\nclass Invoice(metaclass=PoolMeta):\n __name__ = 'account.invoice'\n numbered_at = fields.Timestamp(\"Numbered At\")\n\n @classmethod\n def __register__(cls, module_name):\n super().__register__(module_name)\n table_h = cls.__table_handler__(module_name)\n table = cls.__table__()\n cursor = Transaction().connection.cursor()\n\n # Migration from 5.2: rename open_date into numbered_at\n if table_h.column_exist('open_date'):\n cursor.execute(\n *table.update(\n [table.numbered_at],\n [table.open_date]))\n table_h.drop_column('open_date')\n\n @classmethod\n def __setup__(cls):\n super(Invoice, cls).__setup__()\n cls._check_modify_exclude.append('numbered_at')\n cls.party.datetime_field = 'numbered_at'\n if 'numbered_at' not in cls.party.depends:\n cls.party.depends.append('numbered_at')\n cls.invoice_address.datetime_field = 'numbered_at'\n if 'numbered_at' not in cls.invoice_address.depends:\n cls.invoice_address.depends.append('numbered_at')\n cls.payment_term.datetime_field = 'numbered_at'\n if 'numbered_at' not in cls.payment_term.depends:\n cls.payment_term.depends.append('numbered_at')\n\n @classmethod\n def set_number(cls, invoices):\n numbered = [i for i in invoices if not i.number or not i.numbered_at]\n super(Invoice, cls).set_number(invoices)\n if numbered:\n cls.write(numbered, {\n 'numbered_at': CurrentTimestamp(),\n })\n\n @classmethod\n @ModelView.button\n @Workflow.transition('draft')\n def draft(cls, invoices):\n super(Invoice, cls).draft(invoices)\n cls.write(invoices, {\n 'numbered_at': None,\n })\n\n @classmethod\n def copy(cls, invoices, default=None):\n if default is None:\n default = {}\n else:\n default = default.copy()\n default.setdefault('numbered_at', None)\n return super(Invoice, cls).copy(invoices, default=default)\n","sub_path":"account_invoice_history/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"48701160","text":"import json\nimport os\n\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS\n\nfrom mongoengine import *\n\nimport tsunami_potential\n\nfrom dotenv import load_dotenv\nload_dotenv()\n\nclass Earthquake(Document):\n name = StringField(db_field='name', required=True)\n usgs_id = StringField(db_field='usgsId')\n usgs_name = StringField(db_field='usgsName')\n origin_time = DateTimeField(db_field='originTime')\n usgs_origin_time = DateTimeField(db_field='usgsOriginTime')\n iris_origin_time = DateTimeField(db_field='irisOriginTime')\n noaa_location = StringField(db_field='noaaLocation')\n novianty_rupture_duration = FloatField(db_field='noviantyRuptureDuration')\n novianty_p_wave_dominant_period = FloatField(db_field='noviantyPWaveDominantPeriod')\n novianty_t0xtd = FloatField(db_field='noviantyT0xtd')\n novianty_mw = FloatField(db_field='noviantyMw')\n mw = FloatField(db_field='mw')\n usgs_mw = FloatField(db_field='usgsMw')\n iris_mw = FloatField(db_field='irisMw')\n noaa_tsunami = BooleanField(db_field='noaaTsunami')\n noaa_tsunami_id = IntField(db_field='noaaTsunamiId')\n unknown1 = IntField(db_field='unknown1')\n usgs_depth = FloatField(db_field='usgsDepth')\n collection_name = StringField(db_field='collectionName')\n collection_pos = IntField(db_field='collectionPos')\n epicenter = PointField(db_field='epicenter')\n usgs_epicenter = PointField(db_field='usgsEpicenter')\n\n meta = {\n 'collection': 'earthquake'\n }\n\n\nclass TsunamiEvent(Document):\n _id = IntField(db_field='_id')\n year = IntField(db_field='YEAR')\n month = IntField(db_field='MONTH')\n day = IntField(db_field='DAY')\n hour = IntField(db_field='HOUR')\n minute = IntField(db_field='MINUTE')\n second = IntField(db_field='SECOND')\n focalDepth = FloatField(db_field='FOCAL_DEPTH')\n primaryMagnitude = FloatField(db_field='PRIMARY_MAGNITUDE')\n country = StringField(db_field='COUNTRY')\n state = StringField(db_field='STATE')\n locationName = StringField(db_field='LOCATION_NAME')\n latitude = FloatField(db_field='LATITUDE')\n longitude = FloatField(db_field='LONGITUDE')\n maximumWaterHeight = FloatField(db_field='MAXIMUM_WATER_HEIGHT')\n # origin_time = DateTimeField(db_field='originTime')\n # usgs_origin_time = DateTimeField(db_field='usgsOriginTime')\n # iris_origin_time = DateTimeField(db_field='irisOriginTime')\n # noaa_location = StringField(db_field='noaaLocation')\n # novianty_rupture_duration = FloatField(db_field='noviantyRuptureDuration')\n # novianty_p_wave_dominant_period = FloatField(db_field='noviantyPWaveDominantPeriod')\n # novianty_t0xtd = FloatField(db_field='noviantyT0xtd')\n # novianty_mw = FloatField(db_field='noviantyMw')\n # mw = FloatField(db_field='mw')\n # usgs_mw = FloatField(db_field='usgsMw')\n # iris_mw = FloatField(db_field='irisMw')\n # noaa_tsunami = BooleanField(db_field='noaaTsunami')\n # noaa_tsunami_id = IntField(db_field='noaaTsunamiId')\n # unknown1 = IntField(db_field='unknown1')\n # usgs_depth = FloatField(db_field='usgsDepth')\n # collection_name = StringField(db_field='collectionName')\n # collection_pos = IntField(db_field='collectionPos')\n # epicenter = PointField(db_field='epicenter')\n # usgs_epicenter = PointField(db_field='usgsEpicenter')\n\n meta = {\n 'collection': 'tsevents',\n 'strict': False # temporary\n }\n\n\napp = Flask(__name__)\nCORS(app)\n\nconnect('ecn', host=os.getenv('MONGODB_URI', 'mongodb://localhost/ecn'))\n\n\n# t1 = Earthquake(name='Just testing', usgs_depth=5.2)\n# t1.save()\n\ndef earthquake_to_json(earthquake: Earthquake):\n json_obj = json.loads(earthquake.to_json())\n json_obj['id'] = str(earthquake.id)\n json_obj['originTime'] = earthquake.origin_time.strftime('%Y-%m-%dT%H:%M:%SZ')\n json_obj['irisOriginTime'] = earthquake.iris_origin_time.strftime(\n '%Y-%m-%dT%H:%M:%SZ') if earthquake.iris_origin_time else None\n json_obj['usgsOriginTime'] = earthquake.usgs_origin_time.strftime(\n '%Y-%m-%dT%H:%M:%SZ') if earthquake.usgs_origin_time else None\n return json_obj\n\n\ndef tsunami_event_to_json(tsunami_event: TsunamiEvent):\n json_obj = json.loads(tsunami_event.to_json())\n json_obj['id'] = tsunami_event._id\n # json_obj['originTime'] = earthquake.origin_time.strftime('%Y-%m-%dT%H:%M:%SZ')\n # json_obj['irisOriginTime'] = earthquake.iris_origin_time.strftime(\n # '%Y-%m-%dT%H:%M:%SZ') if earthquake.iris_origin_time else None\n # json_obj['usgsOriginTime'] = earthquake.usgs_origin_time.strftime(\n # '%Y-%m-%dT%H:%M:%SZ') if earthquake.usgs_origin_time else None\n return json_obj\n\n\n@app.route('/', methods=['GET'])\ndef hello():\n return jsonify({'message': 'Check /earthquakes'})\n\n\n@app.route('/earthquakes', methods=['GET'])\ndef earthquakes_list():\n earthquakes = Earthquake.objects()\n earthquakes_json = [earthquake_to_json(doc) for doc in earthquakes]\n return jsonify({'_embedded': {'earthquakes': earthquakes_json}})\n\n\n@app.route('/earthquakes/', methods=['GET'])\ndef earthquakes_detail(earthquake_id: str):\n earthquake = Earthquake.objects(id=earthquake_id).first()\n earthquake_json = earthquake_to_json(earthquake)\n return jsonify(earthquake_json)\n\n\n@app.route('/tsunamiPotential/predict', methods=['POST'])\ndef tsunami_potential_predict():\n \"\"\"\n Predict tsunami potential.\n\n Request body is JSON with {t0, td, mw}\n\n :param t0: Unnormalized rupture duration variable\n :param td: Unnormalized P-wave dominant period variable\n :param mw: Unnormalized moment magnitude (M_w)\n \"\"\"\n content = request.get_json()\n t0: float = content['t0']\n td: float = content['td']\n mw: float = content['mw']\n potential = tsunami_potential.predict(t0, td, mw)\n print('Potential: %s' % (potential,))\n return jsonify(potential)\n\n\n@app.route('/tsunamiEvents', methods=['GET'])\ndef tsunami_event_list():\n tsunami_events = TsunamiEvent.objects.order_by('-year') [:100]\n tsunami_events_json = [tsunami_event_to_json(doc) for doc in tsunami_events]\n return jsonify({'_embedded': {'tsunamiEvents': tsunami_events_json}})\n","sub_path":"ecn-svc-legacy/ecnsvc.py","file_name":"ecnsvc.py","file_ext":"py","file_size_in_byte":6172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"147950442","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#Francisco Carrillo Pérez\n#All wrongs reserved\n#Github: https://github.com/pacocp\ndef main():\n llave = input('Insertar llave: ')\n nombre_f = input('Nombre del fichero: ')\n f= open(nombre_f,'r')\n ctexto= f.read().split(\"0x\")\n texto_plano=\"\"\n size=len(llave)\n ctexto.remove('')\n for index,val in enumerate(ctexto):\n c = int(\"0x\"+val,16) ^ ord(llave[index % size])\n texto_plano += str(chr(c))\n f.close()\n print(\"Texto desencriptado: \")\n print(texto_plano)\n\nmain()\n","sub_path":"descrifrar.py","file_name":"descrifrar.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"647846699","text":"'''A level-order traversal, also known as a breadth-first search, visits each level of a tree's nodes from left to right, top to bottom. You are given a pointer, root, pointing to the root of a binary search tree. Complete the levelOrder function provided in your editor so that it prints the level-order traversal of the binary search tree.\r\n\r\nHint: You'll find a queue helpful in completing this challenge.\r\n\r\nFunction Description\r\n\r\nComplete the levelOrder function in the editor below.\r\n\r\nlevelOrder has the following parameter:\r\n- Node pointer root: a reference to the root of the tree\r\n\r\nPrints\r\n- Print node.data items as space-separated line of integers. No return value is expected.\r\n\r\nSample Input\r\n\r\n6\r\n3\r\n5\r\n4\r\n7\r\n2\r\n1\r\nSample Output\r\n\r\n3 2 5 1 4 7 '''\r\n\r\nimport sys\r\n\r\nclass Node:\r\n def __init__(self,data):\r\n self.right=self.left=None\r\n self.data = data\r\nclass Solution:\r\n def insert(self,root,data):\r\n if root==None:\r\n return Node(data)\r\n else:\r\n if data<=root.data:\r\n cur=self.insert(root.left,data)\r\n root.left=cur\r\n else:\r\n cur=self.insert(root.right,data)\r\n root.right=cur\r\n return root\r\n\r\n def levelOrder(self,root):\r\n #Write your code here\r\n \r\n if root is None:\r\n return \r\n \r\n qu = []\r\n qu.append(root)\r\n\r\n while len(qu) !=0:\r\n p = qu.pop(0)\r\n print(p.data, end=' ')\r\n if p.left is not None:\r\n qu.append(p.left)\r\n if p.right is not None:\r\n qu.append(p.right)\r\n\r\nT=int(input())\r\nmyTree=Solution()\r\nroot=None\r\nfor i in range(T):\r\n data=int(input())\r\n root=myTree.insert(root,data)\r\nmyTree.levelOrder(root)\r\n\r\n","sub_path":"23_BSt-lvl-ord-traversal.py","file_name":"23_BSt-lvl-ord-traversal.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"155601933","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 16 07:38:29 2017\n\n@name: queueing_simluation.py\n@author: Jared Bauman\n@description: Simulates the process of arrivals into and departures from a \n charging station using an inhomogeneous (arrival rate varying) Poisson \n process, writing key metrics to file\n\"\"\"\n\nimport sys\nimport math\nimport random\nimport queue as q\nimport pandas as pd\nimport datetime as dt\nimport multiprocessing as mp\nfrom datetime import datetime\n\n# import test_queueing_simulation as test\n\n################################################################################\n# Description: Object used to store queueing events such as station arrivals and \n# station departures\n# Attributes:\n# timestamp : float, the arrival or departure time of the customer\n# cust_type : string, the type of customer\n# is_charging : boolean, is the customer charging their car (so the next event\n# will be a station departure)?\n# char_type : string, the type of charger the customer is using, if any\n################################################################################\n\n\nclass Event(object):\n _timestamp = 0\n _cust_type = \"\"\n _is_charging = False\n _char_type = \"\"\n\n # Event(timestamp, cust_type, is_charging, char_type)\n # Event( t, 'Individual 50 kW', True/False, '150 kW charger')\n # if its not at a charger its and empty string\n # if it is true then it is charging\n # if it is false it has not be placed in a charger\n #simulate_arrival\n # it starts in the pq (priority queue) as false\n # # pq is made by taking calculating total sessions in a day and uses poisson prob to space out the arrival over the week\n # # sims an arrival and determines if that arrival is actually real based on the arrival distribution, if it is real then it goess into pq\n #process_arrival\n # # looping through the timestamps, if a charger is available then the arrival is turn to a depature:\n # # # False goes to True\n # # # timestamp is updated with how long itll be at that charger which is based on cust_typ and char_typ\n # # # elec_used is moved up when an arrival is processed, moved down when the charge is complete\n # # # elec_used is then appended to the load curve which is a dic where the key is the timestamp and the value is the elec_used\n \n \n def __init__(self, timestamp, cust_type, is_charging, char_type):\n self.timestamp = float(timestamp)\n self.cust_type = cust_type\n self.is_charging = is_charging\n self.char_type = char_type\n \n def get_time(self):\n return self.timestamp\n \n def get_charge_status(self):\n return self.is_charging\n \n def get_cust_type(self):\n return self.cust_type\n \n def get_char_type(self):\n return self.char_type\n \n def __eq__(self, other):\n return (self.timestamp == other.timestamp)\n\n def __ne__(self, other):\n return (self.timestamp != other.timestamp)\n\n def __lt__(self, other):\n return (self.timestamp < other.timestamp)\n\n def __le__(self, other):\n return (self.timestamp <= other.timestamp)\n\n def __gt__(self, other):\n return (self.timestamp > other.timestamp)\n\n def __ge__(self, other):\n return (self.timestamp >= other.timestamp)\n \n def __str__(self):\n return (str(self.timestamp) + \" | \" + self.cust_type + \" | \" + str(self.is_charging) + \" | \" + str(self.char_type))\n \n################################################################################\n# Description: Takes in a float representing the number of minutes since \n# midnight on the first day and return a formatted string representing the\n# date/time\n# Input: \n# t : float, time in minutes\n# Output:\n# string, in format 'Day X - HH:MM'\n################################################################################\n\n\ndef format_time(t):\n day = t // (24 * 60) + 1\n t %= (24 * 60)\n hour = int(t // 60)\n minute = int(t % 60)\n return 'Day {} - {:02d}:{:02d}'.format(day, hour, minute)\n\n################################################################################\n# Description: Takes in a float representing the number of minutes since \n# midnight on the first day and returns a integer representing the number of\n# hours since simulation start\n# Input: \n# t : float, time in minutes\n# Output:\n# int, the hour number\n################################################################################\n\n\ndef discretize(t):\n return int(t / (60))\n \n################################################################################\n# Description: Generate a random time with exponential distribution with mean \n# scale_param by inverting the cdf unif(0,1) = 1 - e^(-t/scale_param)\n# Input:\n# scale_param : float, the mean of the exponential distribution\n# Output:\n# float, an exponential random variable\n################################################################################\n\n\ndef expon(scale_param):\n return -math.log(1.0-random.random()) * scale_param\n\n################################################################################\n# Description: Take in a list of the available chargers and a customer type and\n# and assign a charger to the customer, in order of preference\n# Input: \n# char_avail : dictionary indexed by charger type (string) storing the number \n# of chargers of each type available (int)\n# cust_type : string, the customer type\n# Output:\n# string, the name of the assigned charger type\n################################################################################\n\n\ndef assign_char(char_avail, cust_type):\n \n # By default, try to assign a matching charger\n if cust_type[-6:] == ' 50 kW':\n if char_avail['50 kW charger'] >= 1:\n return '50 kW charger'\n if cust_type[-6:] == '150 kW':\n if char_avail['150 kW charger'] >= 1:\n return '150 kW charger'\n if cust_type[-6:] == '350 kW':\n if char_avail['350 kW charger'] >= 1:\n return '350 kW charger'\n \n # 50 kW customers go for lowest power chargers first (but avoid 7.2 char)\n if cust_type[-6:] == ' 50 kW':\n if char_avail['150 kW charger'] >= 1:\n return '150 kW charger'\n elif char_avail['350 kW charger'] >= 1:\n return '350 kW charger'\n else: \n return 'L2 charger'\n \n # All other customers go for the highest power chargers first\n else: \n if char_avail['350 kW charger'] >= 1:\n return '350 kW charger'\n elif char_avail['150 kW charger'] >= 1:\n return '150 kW charger'\n elif char_avail['50 kW charger'] >= 1:\n return '50 kW charger'\n else: \n return 'L2 charger'\n \n################################################################################\n# Description: Return the number of kWs used when a customer of type cust_types \n# charges ona charger of type char_type \n# Input:\n# cust_type : string, the type of customer\n# char_type : string, the type of charger\n# Output:\n# float, the number of kWs used\n################################################################################\n\n\ndef kw_used(cust_type, char_type):\n if char_type == 'L2 charger':\n return 7.2\n elif (cust_type[-6:] == ' 50 kW') or (char_type == '50 kW charger'):\n return 50\n elif (cust_type[-6:] == '150 kW') or (char_type == '150 kW charger'):\n return 150\n elif (cust_type[-6:] == '350 kW') and (char_type == '350 kW charger'):\n return 350\n else:\n print(\"ERROR: Issue in kw_used. This line should not be reached\")\n return\n \n################################################################################\n# Description: Simulate exponential arrivals from an inhomogeneous Poisson \n# process using the rejection sampling method. Simulates a superprocess of \n# length TIMEOUT using the maximum instantaneous arrival rate max_rate. After \n# each arrival from the superprocess is simulated, keep an arrival at time T \n# with probability accept(T). Kept arrivals are placed in the priority queue \n# pq and customer type typ is recorded\n# Input:\n# pq : PriorityQueue, stores station Event objects (such as arrivals)\n# typ : string, the customer type\n# max_rate : float, the maximum arrival rate acheived by the inhomogeneous\n# Poisson process\n# accept_rate : dictionary indexed by hour of the simulation (int), stores the\n# likelihood of the superprocess event being generated by the \n# inhomogeneous Poisson process (float)\n# TIMEOUT : float, the number of minutes in the simulation\n# Output:\n# pq : PriorityQueue, storing station Event objects\n# arrivals : float, the count of arrivals generated by the superprocess\n# accepts : float, the number of arrivals accepted and added to the priority\n# queue\n################################################################################\n\ndef simulate_arrivals(pq, typ, max_rate, accept_rate, TIMEOUT):\n \n # Initialize first potential arrival (could be rejected)\n t = expon(max_rate)\n\n arrivals = accepts = 0\n\n # while arrivals != abs_session_num:\n\n while t < TIMEOUT:\n\n arrivals += 1\n # Rejection sampling for inhomogeneous poisson processes\n if random.random() < accept_rate[discretize(t)]:\n # List: Cust type, arrival time, is_charging, charger type\n pq.put(Event(t, typ, False, \"\"))\n accepts += 1\n\n t += expon(max_rate)\n \n return (pq, arrivals, accepts)\n \n################################################################################\n# Description: Take priority queue pre-loaded with arrivals as an input and \n# simulate queueing behavior. Return descriptive statistics about the process\n# Input:\n# pq : PriorityQueue, stores station Event objects (such as arrivals)\n# wait : PriorityQueue, used to store customers waiting for a charger\n# num_char : dictionary indexed by charger type (string) storing the number \n# of chargers of each type at each station (int)\n# charge_rate : dictionary of dictionaries indexed first by customer type \n# (string) and then by charger type (string) storing the time a customer\n# will spend at the given charger (float)\n# TIMEOUT : float, the number of minutes in the simulation\n# TEST : boolean, indicates if detailed tests should be run\n# VERBOSE : boolean, indicates if detailed testing output should be printed\n# Output:\n# load_curve : dictionary indexed by time (float) storing forward-looking\n# power usage (float)\n# num_type_visits : dictionary indexed by cutomer type (string) storing the \n# number of arrivals by customers of that type\n# tot_elec : float, total electricity used in kilowatt-minutes\n# max_power : float, maximum instantaneous power used\n# uptime : float, total time chargers spend active\n################################################################################\n\ndef process_arrivals(pq, wait, num_char, charge_rate, TIMEOUT, TEST, VERBOSE=False):\n \n EPSILON = 0.00000001\n\n porsche_queue = 0\n porsche_not350 = 0\n char_avail = num_char.copy()\n \n # Define metrics to track\n num_visits = 0\n elec_in_use = 0.0\n uptime = 0.0\n tot_elec = 0.0\n max_power = 0\n load_curve = {}\n num_type_visits = {}\n \n # Process arrivals and compute output metrics\n\n\n t = 0\n while (not pq.empty() or not wait.empty()):\n \n #######################\n ## Charger available ##\n #######################\n \n # If a charger is available, process the wait queue. If the \n # wait queue is empty, then process the arrival queue\n if char_avail[max(char_avail, key=char_avail.get)] > 0:\n event = None\n if not wait.empty():\n event = wait.get()\n \n if t - event.get_time() > (30 + expon(10)): ################################# TE: leave waiting queue after 40 mins of waiting\n continue\n \n # Throw error if a charging term was put into the wait queue\n if TEST and event.get_charge_status():\n print(\"ERROR: Charging session placed in wait queue\")\n \n # Increment time by epsilon when drawing from the wait queue\n # and check simulation termination condition\n t += EPSILON\n if t >= TIMEOUT:\n wait.put(event)\n break\n \n else:\n event = pq.get()\n t = event.get_time() # Update simulation clock\n \n # Check simulation termination condition\n if t >= TIMEOUT:\n pq.put(event)\n break\n \n # If the event is a charging termination, handle\n if event.get_charge_status():\n \n # Update tracking metrics\n char_avail[event.get_char_type()] += 1\n elec_in_use -= kw_used(event.get_cust_type(), event.get_char_type())\n load_curve[t] = elec_in_use\n continue\n \n # Get customer type\n cust_type = event.get_cust_type()\n \n # Update number of visits\n num_visits += 1\n if cust_type not in num_type_visits: \n num_type_visits[cust_type] = 1\n else:\n num_type_visits[cust_type] += 1\n \n # Get charger type and decrement the number of available chargers\n char_type = assign_char(char_avail, cust_type)\n char_avail[char_type] -= 1\n if cust_type[-6:] == '350 kW' and char_type != '350 kW charger':\n porsche_not350 += 1\n\n # Get kw used in charging session\n kw = kw_used(cust_type, char_type)\n \n # Update tracking metrics\n elec_in_use += kw\n uptime += min(charge_rate[cust_type][char_type], TIMEOUT - t)\n max_power = max(max_power, elec_in_use)\n tot_elec += kw * min(charge_rate[cust_type][char_type], TIMEOUT - t)\n load_curve[t] = elec_in_use\n\n # ASSERT\n if TEST:\n for typ in char_avail:\n if char_avail[typ] < 0:\n print(\"There are fewer than zero available chargers\")\n \n # Calculate time customer will finish charging\n t_finish = t + charge_rate[cust_type][char_type]\n\n # Add customer back to wait queue\n pq.put(Event(t_finish, cust_type, True, char_type))\n\n ##########################\n ## No charger available ##\n ##########################\n \n # If there are no chargers available, process the next draw from \n # the event queue. If it's an arrival, move the customer to the \n # wait queue. If it's a departure, increment the number of available\n # chargers\n else:\n \n event = pq.get()\n if event.get_charge_status():\n\n # Update simulation time and check simulation termination\n # condition. Update avail counters\n t = event.get_time()\n if t >= TIMEOUT:\n pq.put(event)\n break\n \n char_avail[event.get_char_type()] += 1\n \n # Update tracking metrics\n elec_in_use -= kw_used(event.get_cust_type(), event.get_char_type())\n load_curve[t] = elec_in_use\n\n else:\n cust_type = event.get_cust_type()\n if cust_type[-6:] == '350 kW':\n porsche_queue += 1\n\n wait.put(event)\n\n cust_types = ['Individuals - 50 kW', 'Individuals - 150 kW', 'Individuals - 350 kW']\n\n for cust_type in cust_types:\n if cust_type not in num_type_visits:\n num_type_visits[cust_type] = 0\n\n \n # Ensure termination criteria are satisfied\n if VERBOSE:\n if pq.empty():\n print(\"End event queue size: \" + str(pq.qsize()))\n if not wait.empty():\n print(\"End wait queue size: \" + str(wait.qsize()))\n if t < TIMEOUT:\n print(\"Sim terminated after \" + str(100*t/TIMEOUT) + \"% time used\")\n \n # if TEST:\n # test.runtime_test(pq, wait, num_char.keys(), num_type_visits.keys(), num_char, load_curve, num_visits, tot_elec, max_power, uptime, TIMEOUT, EPSILON, VERBOSE)\n \n return (load_curve, num_type_visits, tot_elec, max_power, uptime, porsche_queue, porsche_not350)\n \n \n################################################################################\n# Description : Take in detailed load curve information and create a set of \n# dictionaries storing discretized load curve information--the max power in an \n# interval, the average power in an interval, and the average power in a \n# double length interval\n# Input:\n# load_curve : dictionary indexed by time (float) storing forward-looking\n# power usage (float)\n# max_kw_inst : float, maximum instantaneous power used\n# kwh : float, total electricity used in kWH\n# MIN_PER_HOUR : float, the number of minutes per hour\n# TIMEOUT : float, the number of minutes in the simulation\n# MIN_PER_INTERVAL : float, the length of the discrete interval\n# TEST : boolean, indicates if detailed tests should be run\n# Output:\n# max_power : dictionary indexed by interval number (int) storing the max\n# power used during that interval (float)\n# avg_power : dictionary indexed by interval number (int) storing the average\n# power used during that interval (float)\n# avg_power_dblen : dictionary indexed by double-length interval number (int) \n# storing the average power used during that interval (float)\n################################################################################\n\ndef discretize_load_curve(load_curve, max_kw_inst, kwh, MIN_PER_HOUR, TIMEOUT, MIN_PER_INTERVAL, TEST):\n\n # Discretize and agregate load curve\n MIN_PER_DBL_INT = 2 * MIN_PER_INTERVAL\n INTERVALS = int(TIMEOUT / MIN_PER_INTERVAL)\n DOUBLE_INTERVALS = int(TIMEOUT / (2 * MIN_PER_INTERVAL))\n \n # Define data structures\n max_power = {}\n avg_power = {}\n for i in range(0, INTERVALS):\n max_power[i] = 0\n avg_power[i] = 0\n avg_power_dblen = {}\n for i in range(0, DOUBLE_INTERVALS):\n avg_power_dblen[i] = 0\n \n # Parse load curve and calculate \n t_prev = 0\n power = 0\n for t in sorted(load_curve):\n \n ## Single length intervals ##\n \n # define range of affected intervals\n start = int(t_prev / MIN_PER_INTERVAL)\n end = int(t / MIN_PER_INTERVAL)\n \n # Handle intial interval \n max_power[start] = max(max_power[start], power)\n seg_len = min(t, (start + 1)*MIN_PER_INTERVAL) - t_prev\n avg_power[start] += seg_len * power # energy used\n\n # Handle in between intervals, if any\n for k in range(start+1, end):\n max_power[k] = max(max_power[k], power)\n avg_power[k] = MIN_PER_INTERVAL * power # energy used\n \n # Handle final interval\n if start != end and end < int(TIMEOUT / MIN_PER_INTERVAL):\n max_power[end] = max(max_power[end], power)\n seg_len = t - end * MIN_PER_INTERVAL\n avg_power[end] += seg_len * power # energy used\n \n ## Double length intervals ##\n \n # define range of affected intervals\n start = int(t_prev / MIN_PER_DBL_INT)\n end = int(t / MIN_PER_DBL_INT)\n \n # Handle intial interval \n seg_len = min(t, (start + 1)*MIN_PER_DBL_INT) - t_prev\n avg_power_dblen[start] += seg_len * power # energy used\n\n # Handle in between intervals, if any\n for k in range(start+1, end):\n avg_power_dblen[k] = MIN_PER_DBL_INT * power # energy used\n \n # Handle final interval\n if start != end and end < int(TIMEOUT / MIN_PER_DBL_INT):\n seg_len = t - end * MIN_PER_DBL_INT\n avg_power_dblen[end] += seg_len * power # energy used\n \n t_prev = float(t)\n power = load_curve[t]\n\n ## Validate load curve results ##\n \n if TEST: \n EPSILON = 0.0001\n \n # Ensure max power sense checks\n if (abs(max_kw_inst - max_power[max(max_power, key=max_power.get)]) > EPSILON):\n print(\"Max inst power is \" + str(max_kw_inst) + \" but load curve \" + \"shows a max of \" + str(max_power[max(max_power, key=max_power.get)]))\n \n # Ensure total energy sense checks\n tot_eng_single = 0\n for i in avg_power:\n tot_eng_single += avg_power[i]\n tot_eng_double = 0\n for i in avg_power_dblen:\n tot_eng_double += avg_power_dblen[i]\n \n if (abs(tot_eng_single / MIN_PER_HOUR - kwh) > EPSILON):\n print(\"Total energy \" + str(kwh) + \" but single load curve \" + \"shows \" + str(tot_eng_single / MIN_PER_HOUR)) \n if (abs(tot_eng_double / MIN_PER_HOUR - kwh) > EPSILON):\n print(\"Total energy \" + str(kwh) + \" but double load curve \" + \"shows \" + str(tot_eng_double / MIN_PER_HOUR)) \n \n # Convert energy to power numbers\n for i in avg_power:\n avg_power[i] /= MIN_PER_INTERVAL\n for i in avg_power_dblen:\n avg_power_dblen[i] /= MIN_PER_DBL_INT \n \n return (max_power, avg_power, avg_power_dblen)\n\n################################################################################\n# Description: Simulate arrivals and queueing behavior for a single station\n# during a single quater, returning descriptive statistics\n# Input:\n# stat : int, the in number of the station\n# cust_types : list strings, the possible customer types\n# char_types : list string, the possible character types\n# num_char : dictionary indexed by charger type (string), storing the number\n# of available chargers of that type\n# num_cust : dictionary indexed by customer type (string), storing the number\n# of customers by type\n# arriv_rate : dictionary indexed by customer type (string), storing the \n# number of visits per customer expected during the simulation period\n# arriv_mods : dictionary indexed by simulation hour number (int), storing the \n# the relative rate of arrivals by hour (float) \n# charge_rate : dictionary of dictionaries indexed first by customer type \n# (string) and then by charger type (string) storing the time a customer\n# will spend at the given charger \n# MIN_PER_INTERVAL : float, the length of intervals to be used when \n# discretizing the load curve\n# TIMEOUT : float, the number of minutes in the simulation\n# TEST : boolean, indicates if detailed tests should be run\n# VERBOSE : boolean, indicates if detailed testing output should be printed\n# Output:\n# stat : int, the in number of the station\n# max_power : dictionary indexed by interval number (int) storing the max\n# power used during that interval (float)\n# avg_power : dictionary indexed by interval number (int) storing the average\n# power used during that interval (float)\n# avg_power_dblen : dictionary indexed by double-length interval number (int) \n# storing the average power used during that interval (float)\n# num_type_visits : dictionary indexed by cutomer type (string) storing the \n# number of arrivals by customers of that type (int)\n# kwh : float, total electricity used in kWH\n# max_kw_inst : float, maximum instantaneous power used\n# utilzation : float, the fraction of total available charger uptime used\n################################################################################\n\ndef simulate_station(args):\n (stat_id, cust_types, char_types, num_char, num_cust, arriv_rate, arriv_mods, charge_rate, TIMEOUT, MIN_PER_INTERVAL, TEST, VERBOSE) = args\n \n ################################\n ## Define key data structures ##\n ################################\n \n MIN_PER_HOUR = 60.0\n \n # Create main event queue and helper wait queue\n pq = q.PriorityQueue()\n wait = q.PriorityQueue()\n\n # Find maximum arrival rate and calculate arrival accept rate for\n # non-homogeneous poisson simulation\n max_mod = arriv_mods[max(arriv_mods, key=arriv_mods.get)]\n accept_rate = {}\n for i in arriv_mods:\n accept_rate[i] = arriv_mods[i] / max_mod\n\n #######################\n ## Simulate arrivals ##\n #######################\n \n # Simulate customer arrivals for each customer type and load them into the \n # event queue. Skip type if there are no customers of that type\n for typ in num_cust:\n if num_cust[typ] == 0:\n continue\n # Calculate arrival rate from sim inputs\n max_rate = MIN_PER_HOUR / (arriv_rate[typ] * num_cust[typ] * max_mod)\n \n # Prime queue with arrivals of the given type\n (pq, arrivals, accepts) = simulate_arrivals(pq, typ, max_rate, accept_rate, TIMEOUT)\n \n if VERBOSE:\n print(\"Computing: \" + str(typ))\n print(\"Arrive_rate: \" + str(arriv_rate[typ]))\n print(\"Num cust: \" + str(num_cust[typ]))\n print(\"Max rate: \" + str(max_rate))\n print(\"Custs placed in queue: \" + str(accepts))\n print(\"Deviation from expectation: \" + str(100*accepts/(arriv_rate[typ] * num_cust[typ])-100) +\"%\") \n \n if VERBOSE:\n print(\"Final arrival queue size is \" + str(pq.qsize()))\n \n ######################\n ## Process arrivals ##\n ######################\n \n (load_curve, num_type_visits, tot_elec, max_power, uptime, porsche_queue, porsche_not350) = process_arrivals(pq, wait, num_char, charge_rate, TIMEOUT, TEST)\n \n ###########################\n ## Calculate key metrics ##\n ###########################\n \n # Handle corner case where customer charging at midnight on the last day\n load_curve[TIMEOUT] = 0\n \n # Scan through load curve and calculate total energy, uptime, and max power \n # used\n kwh = 0\n max_kw_inst = 0\n prev = 0\n prev_key = 0\n for key in sorted(load_curve):\n max_kw_inst = max(max_kw_inst, load_curve[key])\n kwh += (float(key) - prev_key) * prev\n prev = load_curve[key]\n prev_key = float(key) \n # Normalize\n kwh /= MIN_PER_HOUR\n \n # Calculate utilization\n capacity = 0\n for typ in num_char:\n capacity += num_char[typ]\n \n utiliz = uptime / (capacity * TIMEOUT)\n \n ######################################\n ## Discretize continuous load curve ##\n ######################################\n \n# if TEST and stat_id == 100001:\n# for key in sorted(load_curve):\n# print(str(format_time(float(key))) + \" : \" + str(load_curve[key]))\n \n (max_power, avg_power, avg_power_dblen) = discretize_load_curve(load_curve, max_kw_inst, kwh, MIN_PER_HOUR, TIMEOUT, MIN_PER_INTERVAL, TEST)\n \n return stat_id, max_power, avg_power, avg_power_dblen, num_type_visits, kwh, max_kw_inst, utiliz, porsche_queue, porsche_not350\n \n \n\n\n################################################################################\n# Description:\n# Input:\n# x :\n# Output:\n# integer,\n################################################################################\n\ndef main(station_dict, cust_types, char_types, quarters, stations, num_char_dics, num_cust_dics, arriv_rate, arriv_mods, charge_rate, ncores, site_IDs_float, run_num, nmonths):\n\n\n # Set global parameters\n\n MIN_PER_INTERVAL = 15\n mlen = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n \n # Determine if descriptive warning and error messages should be printed\n TEST = True\n # Create child processes to simulate stations in parallel. Can't be executed\n # within a intepreter such as Sypder\n PARALLEL = True\n \n # Define metric dictionaries\n total_kwh = {}\n max_inst_power = {}\n max_interval_avg_power = {}\n utilization = {}\n porsche_queue = {}\n porsche_not350 = {}\n cust_visits = {}\n est_cust_count = {}\n \n for typ in cust_types:\n cust_visits[typ] = {}\n est_cust_count[typ] = {}\n\n month = 0\n\n # Sequentially calculate usage by quarter, parrellizing calculations by \n # station within each quarter\n\n for quarter in quarters:\n\n for mon in range(0, 3):\n\n yearx = int((month + 6) / 12)\n year = 2018 + yearx\n month_num = month + 7 - yearx * 12\n wkdaystart = datetime(year, month_num, 1).weekday()\n NUM_DAYS = mlen[month_num-1]\n TIMEOUT = NUM_DAYS * 24 * 60\n\n start = wkdaystart*24\n end = wkdaystart*24+mlen[month_num-1]*24\n\n arriv_mods_month = {}\n i = 0\n for num in range(start,end):\n arriv_mods_month[i] = arriv_mods[num]\n i += 1\n\n print(run_num + \"Generating Load Curves Before Batteries / Month : \" + str(month+1))\n sys.stdout.flush()\n\n # Create subdictionaries for each month\n total_kwh[month] = {}\n max_inst_power[month] = {}\n max_interval_avg_power[month] = {}\n utilization[month] = {}\n porsche_queue[month] = {}\n porsche_not350[month] = {}\n month_key = 'month ' + str(month+1)\n for typ in cust_types:\n cust_visits[typ][month] = {}\n est_cust_count[typ][month] = {}\n\n # Execute core code using multiple cores\n if PARALLEL:\n\n p = mp.Pool(ncores)\n\n # create a tuple with timeframe attached to station processing\n # code\n args = [(stat_id, cust_types, char_types, num_char_dics[stat_id], num_cust_dics[stat_id][quarter], arriv_rate, arriv_mods_month, charge_rate, TIMEOUT, MIN_PER_INTERVAL, TEST, False) for stat_id in site_IDs_float]\n\n # TEEEE if its not indexes by station_ID then it values are the same for all stations\n\n # Output args: station id, load_curve, cust_visit_dict,\n # total_energy, max_inst_power, utilization\n list_df = p.map(simulate_station, args)\n\n # (stat_id, max_power, avg_power, avg_power_dblen, num_type_visits, kwh, max_kw_inst, utiliz, porsche_queue, porsche_not350)\n # TEEE what kicks off the parallel processing\n\n p.close()\n p.join()\n\n # Place output into relevant dictionaries\n\n\n length = len(list_df)\n for i in range(0, length):\n\n site_id = list_df[i][0]\n\n # # parse max power curve\n # for j in sorted(list_df[i][1]):\n # key = month + \" - \" + format_time(j*MIN_PER_INTERVAL)\n # if key not in interval_max_power:\n # interval_max_power[key] = {}\n # interval_max_power[key][site_id] = list_df[i][1][j]\n\n # parse avg power curve, saving max power in interval\n # max_interval_avg_power[month][site_id] = 0\n load_curve = []\n for j in sorted(list_df[i][2]):\n # key = month + \" - \" + format_time(j*MIN_PER_INTERVAL)\n # if key not in interval_avg_power:\n # interval_avg_power[key] = {}\n # interval_avg_power[key][site_id] = list_df[i][2][j]\n load_curve.append(int(list_df[i][2][j]))\n # max_interval_avg_power[month][site_id] = max(max_interval_avg_power[month][site_id], list_df[i][2][j])\n\n station_dict[str(site_id)]['load curve before batteries'][month_key] = load_curve\n\n # parse dbl avg power curve\n # for j in sorted(list_df[i][3]):\n # key = month + \" - \" + format_time(j * 2 * MIN_PER_INTERVAL)\n # if key not in interval_avg_power_dblen:\n # interval_avg_power_dblen[key] = {}\n # interval_avg_power_dblen[key][site_id] = (list_df[i][3][j])\n\n # Get customer counts by type\n for typ in list_df[i][4]:\n cust_visits[typ][month][site_id] = list_df[i][4][typ]\n est_cust_count[typ][month][site_id] = (list_df[i][4][typ] / arriv_rate[typ])\n\n\n # Grab scalar metrics\n total_kwh[month][site_id] = list_df[i][5]\n max_inst_power[month][site_id] = list_df[i][6]\n utilization[month][site_id] = list_df[i][7]\n porsche_queue[month][site_id] = list_df[i][8]\n porsche_not350[month][site_id] = list_df[i][9]\n\n month += 1\n\n\n cust_types = ['Individuals - 50 kW', 'Individuals - 150 kW', 'Individuals - 350 kW']\n\n # utilization\n mnum = 1\n for mo in range(0, nmonths):\n month_key = 'month ' + str(mnum)\n for siteID in stations:\n station_dict[str(siteID)]['utilization'][month_key] = utilization[mo][int(siteID)]\n mnum += 1\n\n # cust_visits\n for cust_type in cust_types:\n mnum = 1\n for mo in range(0, nmonths):\n month_key = 'month ' + str(mnum)\n for siteID in stations:\n cust_key = cust_type + ' customers'\n station_dict[str(siteID)][cust_key][month_key] = cust_visits[cust_type][mo][int(siteID)]\n mnum += 1\n\n # est_cust_count\n for cust_type in cust_types:\n mnum = 1\n for mo in range(0, nmonths):\n month_key = 'month ' + str(mnum)\n for siteID in stations:\n cust_key = cust_type + ' customer count'\n station_dict[str(siteID)][cust_key][month_key] = est_cust_count[cust_type][mo][int(siteID)]\n mnum += 1\n\n\n return station_dict, quarters\n\n################################################################################\n################################################################################\n\n #################\n ## Main Method ##\n #################\n\n################################################################################\n################################################################################\n\nif __name__==\"__main__\":\n main(sys.argv[0], sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7], sys.argv[8], sys.argv[9], sys.argv[10], sys.argv[11], sys.argv[12], sys.argv[13])","sub_path":"model_UTIL_200.py","file_name":"model_UTIL_200.py","file_ext":"py","file_size_in_byte":35255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"271266660","text":"import asyncio\nimport functools\n\n\ndef hello_world(msg):\n print(str.format('Hello, {}!', msg))\n\n\ndef hello_app(name='Name', surname='Surname'):\n print(str.format(\n '{} {}', name, surname\n ))\n\n\ndef main():\n loop = asyncio.get_event_loop()\n\n # можно передать аргументы callback функции в call_soon после объекта\n # callback\n loop.call_soon(hello_world, 'Andrii')\n\n # можно передать аргументы при помощи функции functools.partial(), если\n # необходимо передать ключевые аргументы\n loop.call_soon(functools.partial(print, 'Hello, world!', flush=True))\n\n # так не получится: loop.call_soon(hello_app, name='Andrii')\n loop.call_soon(\n functools.partial(\n hello_app, name='Andrii', surname='Sapel'\n )\n )\n\n try:\n # запускаем событийный цикл на бесконечное выполнение двух\n # спланированных callback функций; порядок выполнения будет FIFO\n loop.run_forever()\n except KeyboardInterrupt:\n print('[x] Event loop interrupted by Ctrl + C')\n finally:\n loop.close()\n print('[x] Event loop is closed')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"spl/asyncio_module/asyncio_docs/event_loop/app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"625890948","text":"import csv\nimport json\nimport sys\nimport pandas as pd\nfrom inc.datastructures import WorkbenchData\n\n\n\"\"\"\n File for building EEGWorkbench json files from \n EEG data stored in CSV files\n \n Usage: lg-json_builder.py +