diff --git "a/417.jsonl" "b/417.jsonl" new file mode 100644--- /dev/null +++ "b/417.jsonl" @@ -0,0 +1,734 @@ +{"seq_id":"248253835","text":"import os\r\nimport numpy as np\r\nimport pandas as pd\r\nimport json\r\nimport re\r\nimport nltk\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem import SnowballStemmer\r\nfrom nltk.tokenize import WordPunctTokenizer\r\nfrom gensim import models\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.metrics import confusion_matrix, precision_recall_fscore_support \r\nimport dill\r\nimport pickle\r\nfrom sklearn.model_selection import cross_val_score\r\n\r\nclass classifier_logisticRegression:\r\n\tdef __init__(self, word2vec, json_file):\r\n\t\t# model = models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)\r\n\t\tself.word2vec=models.KeyedVectors.load_word2vec_format(word2vec,binary=True)\r\n\t\tself.data=pd.read_json(json_file, lines=True)\r\n\t# def preprocessing_data(self, data):\r\n\tdef get_w2v_word(self, word):\r\n\t\treturn (self.word2vec[word])\r\n\tdef get_data_column(self, columns):\r\n\t\treturn (self.data[columns])\r\n\tdef preprocessing(self):\r\n\t\tself.data['text']=[\"title \"+ str(i)+\" \" for i in range(0,len(self.data['short_description']))]+self.data.short_description\r\n\tdef clean_text(self):\r\n\t\tstemmer = SnowballStemmer('english')\r\n\t\twords = stopwords.words('english')\r\n\t\tself.data['cleaned_text'] = self.data['text'].apply(lambda x:\" \".join([stemmer.stem(i) for i in re.sub(\"[^a-zA-Z]\",\" \",x).split() if i not in words]))\r\n\t\treturn self.data['cleaned_text']\r\n\tdef compute_doc_vec_single(self, clean_text):\r\n\t\tvec = np.zeros((self.word2vec.vector_size,), dtype=np.float32)\r\n\t\tn = 0\r\n\t\ttokenized_clean_text=nltk.word_tokenize(clean_text)\r\n\t\tfor word in tokenized_clean_text:\r\n\t\t\tif word in self.word2vec:\r\n\t\t\t\tvec += self.word2vec[word]\r\n\t\t\t\tn += 1\r\n\t\tif(n==0):\r\n\t\t\treturn (self.word2vec[\"Hello\"]*0)\r\n\t\telse:\r\n\t\t\treturn (vec/n)\r\n\tdef compute_doc_vec(self, clean_text):\r\n\t\treturn np.row_stack([self.compute_doc_vec_single(x) for x in clean_text])\r\n\r\n\tdef get_target_y(self):\r\n\t\ty_encoder=LabelEncoder()\r\n\t\ty=y_encoder.fit_transform(self.data['category'])\r\n\t\treturn y,y_encoder\r\n\tdef get_train_test(self, x, y):\r\n\t\ttrain_idx, test_idx = train_test_split(range(len(y)), test_size=0.1, stratify=y)\r\n\t\ttrain_x=x[train_idx, :]\r\n\t\ttrain_y=y[train_idx]\r\n\t\ttest_x=x[test_idx, :]\r\n\t\ttest_y=y[test_idx]\r\n\t\treturn train_x, train_y, test_x, test_y,test_idx\r\n\tdef get_LR_model(self, train_x, train_y):\r\n\t\tmodel=LogisticRegression(multi_class='multinomial',solver='lbfgs',max_iter=3000, n_jobs=-1)\r\n\t\tmodel.fit(train_x, train_y)\r\n\t\treturn (model)\r\n\tdef save_model(self, model, y_encoder):\r\n\t\toutput_dir=u'LR_output'\r\n\t\tif not os.path.exists(output_dir):\r\n\t\t\tos.mkdir(output_dir)\r\n\t\tmodel_file=os.path.join(output_dir, u'model.pkl')\r\n\t\twith open(model_file, 'wb') as outfile:\r\n\t\t\tpickle.dump({'y_encoder': y_encoder, 'lr': model}, outfile)\r\n\t\treturn model_file\r\n\t\r\n\tdef CV_predict(self,x,y):\r\n\t\tprint(\"10-fold cross validation...\")\r\n\t\tscore=cross_val_score(LogisticRegression(multi_class='multinomial', solver='lbfgs',max_iter=3000,verbose=2, n_jobs=-1), x,y, cv=10)\r\n\t\tprint(np.mean(score))\r\n\t\r\n\r\n\r\n\tdef tradition_predict(self, lr_model_file,test_idx, truth):\r\n\t\tprint(\"Traditional predict method...\")\r\n\t\tclf=Predictor(self.word2vec,lr_model_file)\r\n\t\tnew_y_pred = clf.predict(self.data['cleaned_text'][test_idx])\r\n\t\tdf=pd.DataFrame({u'test': new_y_pred, u'truth': truth[test_idx]})\r\n\t\ttest=list(map(str,df['test']))\r\n\t\ttruth=list(map(str,df['truth']))\r\n\t\tcount=0\r\n\t\tfor i in range(0, len(test)):\r\n\t\t\tif test[i]==truth[i]:\r\n\t\t\t\tcount+=1\r\n\t\tprint(count/len(test))\r\n\t\r\n\tdef process(self):\r\n\t\tprint(\"Preprocessing...\")\r\n\t\tself.preprocessing()\r\n\t\tprint(\"Cleaning text...\")\r\n\t\ttemp_clean_text=self.clean_text()\r\n\t\tprint(\"Getting the article vector...\")\r\n\t\tx=self.compute_doc_vec(temp_clean_text)\r\n\t\tprint(\"Getting train data and test data...\")\r\n\t\ty, y_encoder=self.get_target_y()\r\n\t\ttrain_x, train_y, test_x, test_y, test_idx=self.get_train_test(x,y)\r\n\t\tprint(\"Getting model...\")\r\n\t\tmodel=self.get_LR_model(train_x, train_y)\r\n\t\tprint(\"Saving model...\")\r\n\t\tmodel_file=self.save_model(model, y_encoder)\r\n\t\treturn model_file, test_idx, x,y\r\n\r\n\r\nclass Predictor(object):\r\n\tdef __init__(self, loaded_w2v, lr_model_file):\r\n\t\tself.w2v = loaded_w2v\r\n\t\twith open(lr_model_file, 'rb') as infile:\r\n\t\t\tself.model = pickle.load(infile)\r\n \r\n\tdef predict(self, articles):\r\n\t\tx = self._compute_doc_vec(articles)\r\n\t\ty = self.model['lr'].predict(x)\r\n# y_label = self.model1['y_encoder'].inverse_transform(y)\r\n\t\treturn y\r\n \r\n\tdef _compute_doc_vec(self, clean_text):\r\n\t\treturn np.row_stack([self._compute_doc_vec_single(x) for x in clean_text])\r\n\r\n\tdef _compute_doc_vec_single(self, clean_text):\r\n\t\tvec = np.zeros((self.w2v.vector_size,), dtype=np.float32)\r\n\t\tn = 0\r\n\t\ttokenized_clean_text=nltk.word_tokenize(clean_text)\r\n\t\tfor word in tokenized_clean_text:\r\n\t\t\tif word in self.w2v:\r\n\t\t\t\tvec += self.w2v[word]\r\n\t\t\t\tn += 1\r\n\t\tif(n==0):\r\n\t\t\treturn (self.w2v[\"Hello\"]*0)\r\n\t\telse:\r\n\t\t\treturn (vec/n)\r\n\r\n\r\nif __name__==\"__main__\":\r\n\tprint(\"Loading the pre-trained word2vec file and the json file...\")\r\n\tLR_classifier=classifier_logisticRegression(\"GoogleNews-vectors-negative300.bin\", \"News_Category_Dataset_v2.json\")\r\n\tclf, test_idx, x,y=LR_classifier.process()\r\n\r\n\r\n\t#Two methods to get precision\r\n\t#Method1 tradition, the same as online test\r\n\t#**********************************************************\r\n\tLR_classifier.tradition_predict(clf, test_idx,y)\r\n\t#**********************************************************\r\n\t\r\n\t#Method2 10-fold cross validation\r\n\t#**********************************************************\r\n\t# LR_classifier.CV_predict(x,y)\r\n\t#**********************************************************\r\n\r\n\r\n","sub_path":"news_classifier/classifier_logisticRegression.py","file_name":"classifier_logisticRegression.py","file_ext":"py","file_size_in_byte":5716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"254607490","text":"#!/usr/bin/env python\n\nfrom itertools import permutations\n\nwith open(\"inputs/day2.txt\", \"r\") as f:\n nums = [list(map(int, l.split(\"\\t\"))) for l in f if l.strip() != \"\"]\n\nprint(sum(map(lambda r: max(r) - min(r), nums)))\nprint(sum([a // b for a, b in permutations(row, 2) if a % b == 0][0] for row in nums))\n\n","sub_path":"day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"105343063","text":"# Some utility classes to represent a PDB structure\nimport numpy as np\nfrom itertools import combinations as combo\nimport pickle\n\nclass Atom:\n \"\"\"\n A simple class for an amino acid residue\n \"\"\"\n\n def __init__(self, type):\n self.type = type\n self.coords = (0.0, 0.0, 0.0)\n\n # Overload the __repr__ operator to make printing simpler.\n def __repr__(self):\n return self.type\n\nclass Residue:\n \"\"\"\n A simple class for an amino acid residue\n \"\"\"\n\n def __init__(self, type, number):\n self.type = type\n self.number = number\n self.atoms = []\n\n # Overload the __repr__ operator to make printing simpler.\n def __repr__(self):\n return \"{0} {1}\".format(self.type, self.number)\n\nclass ActiveSite:\n \"\"\"\n A simple class for an active site\n \"\"\"\n\n def __init__(self, name):\n self.name = name\n self.residues = []\n self.metrics = [None,None,None]\n\n # Overload the __repr__ operator to make printing simpler.\n def __repr__(self):\n return self.name\n \n def get_raw_metrics(self):\n if self.metrics[0] is None:\n self._individual_metrics()\n return self.metrics[0] \n \n def get_norm_metrics(self,redo_mean_dev=False):\n if self.metrics[2] is None or redo_mean_dev:\n self._individual_metrics()\n self.metrics[1] = flatten_metrics(self.metrics[0])\n self._normalize_metrics(redo_mean_dev)\n return self.metrics[2]\n \n def _individual_metrics(self,printMe=None):\n \"\"\"\n Compute metrics of chemistry, morphology and homogeneity for an ActiveSite instance.\n\n Input: ActiveSite instance\n Output: a dictionary of metrics\n \n Metrics:\n - Mean and Variance of total charge/polarity of residues\n - Fraction of carbon / nitrogen / oxygen\n - Total number of atoms / residues\n - Mean distance between residue centers of mass\n \"\"\"\n\n chem_properties = {\n \"GLY\": \"nonpolar\",\n \"ALA\": \"nonpolar\",\n \"VAL\": \"nonpolar\",\n \"ILE\": \"nonpolar\",\n \"LEU\": \"nonpolar\",\n \"MET\": \"nonpolar\",\n \"PHE\": \"nonpolar\",\n \"TYR\": \"nonpolar\",\n \"TRP\": \"nonpolar\",\n \"PRO\": \"nonpolar\",\n \"CYS\": \"nonpolar\",\n \"SER\": \"polar\",\n \"THR\": \"polar\",\n \"ASN\": \"polar\",\n \"GLN\": \"polar\",\n \"ARG\": \"basic\",\n \"HIS\": \"basic\",\n \"LYS\": \"basic\",\n \"ASP\": \"acidic\",\n \"GLU\": \"acidic\",\n }\n \n charge = {\"nonpolar\": 0, \"polar\": 0, \"basic\": 1, \"acidic\": -1}\n polarity = {\"nonpolar\":0, \"polar\": 0.5, \"basic\": 1, \"acidic\": 1}\n res_type = {\"nonpolar\":0, \"polar\": 0, \"basic\": 0, \"acidic\": 0}\n \n atom_type = {\"C\":0,\"N\":0,\"O\":0}\n \n metric_names = ['meanChar','meanPol','elemFracC',\n 'numAtoms','numRes','meanResDist',\n 'nonpolarFrac','acidicFrac','basicFrac']\n \n metrics = dict.fromkeys(metric_names)\n \n #first calculate mean of total charges/polarity of residues\n residue_charge = np.ndarray(0)\n residue_polarity = np.ndarray(0)\n numRes = len(self.residues)\n \n for residue in self.residues:\n res_type[chem_properties[residue.type.strip()]] += 1\n residue_charge = np.append(residue_charge, charge[chem_properties[residue.type.strip()]])\n residue_polarity = np.append(residue_polarity, polarity[chem_properties[residue.type.strip()]])\n \n for key in res_type.keys():\n res_type[key] /= numRes\n \n self._update_dict(metrics,\n ('meanChar','meanPol','nonpolarFrac','acidicFrac','basicFrac'),\n (np.mean(residue_charge), np.mean(residue_polarity),res_type['nonpolar'],\n res_type['acidic'],res_type['basic'])\n )\n \n #now calculate the fraction of atoms of carbon in the active zone\n numAtoms = 0\n \n for residue in self.residues:\n for atom in residue.atoms:\n numAtoms += 1\n type = atom.type[0]\n if type.lower()=='c':\n atom_type['C'] += 1\n \n for key in atom_type.keys():\n atom_type[key] /= numAtoms\n \n self._update_dict(metrics,\n ('elemFracC','numAtoms','numRes'),\n (atom_type['C'],numAtoms,numRes)\n )\n \n #now calculate the \"center of mass\" for each residue.\n #then calculate the mean of the pairwise Euclidean distance between residue COMs. \n\n for residue in self.residues:\n numAtoms = 0\n centerOfMass = np.zeros(3)\n \n for atom in residue.atoms:\n numAtoms += 1\n centerOfMass += np.asarray(atom.coords)\n \n if not numAtoms==0:\n centerOfMass /= numAtoms\n \n residue.com = tuple(centerOfMass)\n \n residue_dist = []\n \n for pair in combo(self.residues,2):\n distance = np.linalg.norm(np.asarray(pair[0].com)-np.asarray(pair[1].com))\n residue_dist.append(distance) \n \n metrics['meanResDist'] = np.mean(residue_dist)\n \n if printMe: \n for metric in metrics.keys():\n print('{0}\\n\\t\\t{1}\\n'.format(metric,metrics[metric]))\n \n #store\n self.metrics[0] = metrics\n \n return self.metrics[0]\n \n \n def _normalize_metrics(self,redo_mean_dev=False):\n \"\"\"\n Normalizes metric arrays to saved (or custom) dataset\n \"\"\"\n \n #if you want to recalculate mean/devs\n if redo_mean_dev:\n io.gen_mean_dev_normalizations()\n \n means = load_pickle('means_arr')\n devs = load_pickle('devs_arr')\n \n #normalize\n \n self.metrics[2] = (self.metrics[1] - means)/devs\n\n return self.metrics[2]\n \n def _update_dict(self,dictionary,keys,values):\n \"\"\"\n Update dictionary given lists of keys and values\n \n Input: dictionary, keys, values\n Output: None (dictionary updated automatically)\n \"\"\"\n\n dictionary.update(dict(zip(keys,values)))\n \ndef save_pickle(obj, name):\n with open('obj/'+ name + '.pkl', 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\n\ndef load_pickle(name):\n with open('obj/' + name + '.pkl', 'rb') as f:\n return pickle.load(f)\n\ndef flatten_metrics(metrics_dict):\n \"\"\"\n Flattens metric dictionary into a numpy array\n \"\"\"\n\n #NOTE: When converting into array, follows the metric_names list\n #so that you can consistently compare numpy arrays element-wise\n\n metric_names = ['meanChar','meanPol','elemFracC',\n 'numAtoms','numRes','meanResDist',\n 'nonpolarFrac','acidicFrac','basicFrac']\n\n metric_arr = np.ndarray(0)\n\n for metric in metric_names:\n metric_arr = np.append(metric_arr,metrics_dict[metric])\n \n return metric_arr\n","sub_path":"clustering/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"378451947","text":"import os\nfrom code.general import folder_management\nfrom code.general import request_file\nfrom code.general import run_multiprocessing\n\ndef download_files(list_of_enzyme_commission_numbers, list_of_databases, cpus):\n \"\"\" Downloads a url into an HTML file\n Creates data/raw path if does not exist\n Creates a list of files to download, running multiprocessing for speed purposes\n Multiprocessing function runs using a list of tupples, number of cpus and a function\n \"\"\"\n data_path = \"data/raw\"\n folder_management.create_folder(data_path)\n list_of_downloads = []\n for enzyme in list_of_enzyme_commission_numbers:\n for database in list_of_databases:\n download_data = ((enzyme, database, data_path))\n list_of_downloads.append(download_data)\n run_multiprocessing.run_mp(list_of_downloads, cpus, download_manager)\n\ndef download_manager(enzyme, database, data_path):\n \"\"\" Function that is being multiprocessed\n Runs request_file script, who downloads the url into HTML file\n download_path: in our case, it is conserved always with the same scheme\n if the file that we are going to save does not exists, it makes the request\n \"\"\"\n download_path = \"https://www.genome.jp/dbget-bin/get_linkdb?-t+{}+ec:{}\".format(database, enzyme)\n name_of_the_file_path = \"{}/{}_{}_raw.txt\".format(data_path, enzyme, database)\n if not os.path.exists(name_of_the_file_path):\n print(\"Downloading {} enzyme information from {} database. Path: {}\".format(enzyme, database, download_path))\n request_file.download_file(download_path, name_of_the_file_path)\n","sub_path":"code/downloader/download_information.py","file_name":"download_information.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"527586701","text":"import random\n\nclass Fruit():\n\n def __init__(self,tile_x,tile_y):\n self._tile_x = tile_x\n self._tile_y = tile_y\n self._object = []\n \n def GetBody(self):\n return self._object()\n\n def SpawnFruit(self):\n x = random.randint(1,self._tile_x-1)\n y = random.randint(1,self._tile_y-1)\n if (x,y) in self._player_1.GetBody() or (x,y) in self._player_2.GetBody():\n self.SpawnFruit()\n else:\n self._fruit = [(x,y)]","sub_path":"fruit.py","file_name":"fruit.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"411918235","text":"import vk,json,time,random\n\nclass PostToGroupOperation:\n \"\"\"This class execute requests from users\n to spam group via static methods implemented below\"\"\"\n\n @staticmethod\n def get_vk_api(token):\n if None is not token:\n session = vk.Session(access_token=token)\n return vk.API(session=session)\n return None\n\n @staticmethod\n def send_message(vk_api):\n try:\n print(vk_api.messages.send(domain = \"krupenin_pavel\", message = \"Hello\"))\n except Exception as err:\n print(err)\n\n\n @staticmethod\n def getFriends(vk_api):\n print(vk_api.friends.get(fields = 'nickname'))\n\n @staticmethod\n def send_posts_to_groups(vk_api,list_of_posts,list_of_groups):\n try:\n for i in list_of_groups:\n print(vk_api.wall.post(owner_id = '-' + i,message = random.choice(list_of_posts)))\n time.sleep(5)\n except Exception as err:\n print(err)\n\n\n","sub_path":"Model/Logic/VkOperations/PostToGroup/PostToGroupOperation.py","file_name":"PostToGroupOperation.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"120111283","text":"# -*- coding: utf-8 -*-\n\"\"\"\nMétodo simple de infiltración de Green-Ampt\nde una capa. \n\nBasado en ecuaciones presentadas en \n\nChow, V.T., Maidment, D.R., Mays, L.W., 1988. Applied Hydrology, \n\tMcGraw-Hill series in water resources and environmental \n\tengineering. Tata McGraw-Hill Education.\n\nAutor: Alejandro Jaramillo\n\"\"\"\nimport numpy as np\nfrom scipy.optimize import fsolve\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\n\n### PARAMETROS INGRESADOS POR EL USUARIO ###\n\n#Porosidad(n=\\eta)\nn = 0.501\n#Porosidad efectiva (Qe=\\theta_e)\nQe = 0.486\n#Cabesa de succión del suelo en el frente mojado\n#(Psi=\\psi) en cm.\nPsi = 16.68 # cm\n#Conductividad hidráulica (K) en cm/hora \nK = 0.65 # cm/h\n#Saturación efectiva (Se)\nSe = 0.3 # cm\n# Horas de simulación\nSimT = 3 # Horas de similación\n### PARAMETROS INGRESADOS POR EL USUARIO ###\n\nDQ = (1.0-Se)*Qe\nt = np.linspace(0,SimT*60,SimT*60)\nt = t/60\nF = np.zeros(len(t))\n\n\n\ndef func(F,t):\n\tfun = F-(K*t)-(Psi*DQ*np.log(1.0+(F/(Psi*DQ))))\n\treturn fun\n\ni = 0\nfor tt in t:\n\tF[i] = fsolve(func,K*tt,args=tt)\n\ti += 1\n\nf = K*(((Psi*DQ)/F[1:])+1.0)\ntf = t[1:]\n\nFmax = F.max()\nfmax = f.max()\n\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 5))\nfig.suptitle('Modelo de Green-Ampt de 1 Capa \\n'+r'$\\eta=$'+str(n)+r'; $\\theta_e=$'+str(Qe)+r'; $\\psi=$'+str(Psi)+r'; $K=$'+str(K)+r'; $S_e=$'+str(Se))\nax1 = axes[0]\nax1.set_xlim([0, SimT])\nax1.set_ylim([0, Fmax])\nax1.set_xlabel('Tiempo [Horas]')\nax1.set_ylabel('F [cm]')\nax1.plot(t, F, lw=2,ls='-.',color='b')\nax2 = axes[1]\nax2.set_xlim([0, SimT])\nax2.set_ylim([0, fmax])\nax2.set_xlabel('Tiempo [Horas]')\nax2.set_ylabel('f [cm/Hora]')\nax2.plot(tf, f, lw=2,ls='-.',color='r')\nplt.savefig('Modelo_GreenAmpt.png',format='png')\n#plt.show()\nplt.close(1)\n\n\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 5))\nfig.suptitle('Modelo de Green-Ampt de 1 Capa \\n'+r'$\\eta=$'+str(n)+r'; $\\theta_e=$'+str(Qe)+r'; $\\psi=$'+str(Psi)+r'; $K=$'+str(K)+r'; $S_e=$'+str(Se))\nax1 = axes[0]\nax1.set_xlim([0, SimT])\nax1.set_ylim([0, Fmax])\nax1.set_xlabel('Tiempo [Horas]')\nax1.set_ylabel('F [cm]')\nlineF, = ax1.plot([], [], lw=2,ls='-.',color='b')\nax2 = axes[1]\nax2.set_xlim([0, SimT])\nax2.set_ylim([0, fmax])\nax2.set_xlabel('Tiempo [Horas]')\nax2.set_ylabel('f [cm/Hora]')\nlinef, = ax2.plot([], [], lw=2,ls='-.',color='r')\n\ndef init():\n\tlineF.set_data([], [])\n\tlinef.set_data([], [])\n\treturn lineF,linef,\n\ndef animate(i):\n\t#print \"Frame = \" + str(i) \n\tlineF.set_data(t[0:i], F[0:i])\n\tlinef.set_data(tf[0:i], f[0:i])\n\treturn lineF,linef,\n\nanim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=len(t)-2, interval=100, blit=True)\n\n# save the animation as an mp4. This requires ffmpeg or mencoder to be\n# installed. The extra_args ensure that the x264 codec is used, so that\n# the video can be embedded in html5. You may need to adjust this for\n# your system: for more information, see\n# http://matplotlib.sourceforge.net/api/animation_api.html\nanim.save('GreenAmpt.mp4', fps=100, extra_args=['-vcodec', 'libx264'])\n\nplt.show()\n","sub_path":"Hidrologia/GreenAmpt_1LModel/GreenAmpt_1LModelV2.0.py","file_name":"GreenAmpt_1LModelV2.0.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"618019871","text":"import unittest\n\nfrom pyalink.alink import *\n\n\nclass TestPinjiu(unittest.TestCase):\n\n def test_doc_hash_count_vectorizer_op(self):\n import numpy as np\n import pandas as pd\n data = np.array([\n [0, u'二手旧书:医学电磁成像'],\n [1, u'二手美国文学选读( 下册 )李宜燮南开大学出版社 9787310003969'],\n [2, u'二手正版图解象棋入门/谢恩思主编/华龄出版社'],\n [3, u'二手中国糖尿病文献索引'],\n [4, u'二手郁达夫文集( 国内版 )全十二册馆藏书']])\n df = pd.DataFrame({\"id\": data[:, 0], \"text\": data[:, 1]})\n inOp1 = BatchOperator.fromDataframe(df, schemaStr='id int, text string')\n inOp2 = StreamOperator.fromDataframe(df, schemaStr='id int, text string')\n\n segment = SegmentBatchOp().setSelectedCol(\"text\").linkFrom(inOp1)\n train = DocHashCountVectorizerTrainBatchOp().setSelectedCol(\"text\").linkFrom(segment)\n predictBatch = DocHashCountVectorizerPredictBatchOp().setSelectedCol(\"text\").linkFrom(train, segment)\n [model, predict] = collectToDataframes(train, predictBatch)\n print(model)\n print(predict)\n","sub_path":"python/src/main/python/pyalink/alink/tests/examples/operator/batch/test_doc_hash_count_vectorizer.py","file_name":"test_doc_hash_count_vectorizer.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"282351668","text":"from keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TerminateOnNaN, CSVLogger\nfrom keras import backend as K\nfrom keras.models import load_model\n\nfrom models.keras_ssd7 import build_model\nfrom keras_loss_function.keras_ssd_loss import SSDLoss\nfrom keras_layers.keras_layer_AnchorBoxes import AnchorBoxes\nfrom keras_layers.keras_layer_DecodeDetections import DecodeDetections\nfrom keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast\n\nfrom ssd_encoder_decoder.ssd_input_encoder import SSDInputEncoder\nfrom ssd_encoder_decoder.ssd_output_decoder import decode_detections, decode_detections_fast\n\nfrom data_generator.object_detection_2d_data_generator import DataGenerator\nfrom data_generator.object_detection_2d_misc_utils import apply_inverse_transforms\nfrom data_generator.data_augmentation_chain_variable_input_size import DataAugmentationVariableInputSize\nfrom data_generator.data_augmentation_chain_constant_input_size import DataAugmentationConstantInputSize\nfrom data_generator.data_augmentation_chain_original_ssd import SSDDataAugmentation\n\nimport os\nimport csv\nimport cv2\nfrom math import ceil\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimg_height = 300 # Height of the input images\nimg_width = 480 # Width of the input images\nimg_channels = 3 # Number of color channels of the input images\nintensity_mean = 127.5 # Set this to your preference (maybe `None`). The current settings transform the input pixel values to the interval `[-1,1]`.\nintensity_range = 127.5 # Set this to your preference (maybe `None`). The current settings transform the input pixel values to the interval `[-1,1]`.\nn_classes = 3 # Number of positive classes\nscales = [0.08, 0.16, 0.32, 0.64, 0.96] # An explicit list of anchor box scaling factors. If this is passed, it will override `min_scale` and `max_scale`.\naspect_ratios = [0.5, 1.0, 2.0] # The list of aspect ratios for the anchor boxes\ntwo_boxes_for_ar1 = True # Whether or not you want to generate two anchor boxes for aspect ratio 1\nsteps = None # In case you'd like to set the step sizes for the anchor box grids manually; not recommended\noffsets = None # In case you'd like to set the offsets for the anchor box grids manually; not recommended\nclip_boxes = False # Whether or not to clip the anchor boxes to lie entirely within the image boundaries\nvariances = [1.0, 1.0, 1.0, 1.0] # The list of variances by which the encoded target coordinates are scaled\nnormalize_coords = True # Whether or not the model is supposed to use coordinates relative to the image size\n\nbatch_size = 64\n\ndef loadModel(path_model):\n\tssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)\n\tmodel = load_model(path_model, custom_objects={'AnchorBoxes':AnchorBoxes,\n\t\t\t\t\t\t\t\t\t'compute_loss':ssd_loss.compute_loss})\n\treturn model\n\ndef buildModel(path_weights=None):\n\n\tmodel = build_model(image_size=(img_height, img_width, img_channels),\n\t\t\t\t\t\t\tn_classes=n_classes,\n\t\t\t\t\t\t\tmode='training',\n\t\t\t\t\t\t\tl2_regularization=0.0005,\n\t\t\t\t\t\t\tscales=scales,\n\t\t\t\t\t\t\taspect_ratios_global=aspect_ratios,\n\t\t\t\t\t\t\taspect_ratios_per_layer=None,\n\t\t\t\t\t\t\ttwo_boxes_for_ar1=two_boxes_for_ar1,\n\t\t\t\t\t\t\tsteps=steps,\n\t\t\t\t\t\t\toffsets=offsets,\n\t\t\t\t\t\t\tclip_boxes=clip_boxes,\n\t\t\t\t\t\t\tvariances=variances,\n\t\t\t\t\t\t\tnormalize_coords=normalize_coords,\n\t\t\t\t\t\t\tsubtract_mean=intensity_mean,\n\t\t\t\t\t\t\tdivide_by_stddev=intensity_range)\n\n\tif path_weights:\n\t\tmodel.load_weights(path_weights, by_name=True)\n\n\tadam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n\tssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)\n\tmodel.compile(optimizer=adam, loss=ssd_loss.compute_loss)\n\n\treturn model\n\ndef createModel(path_model=None, path_weights=None):\n\tif path_model:\n\t\tmodel = loadModel(path_model)\n\telse:\n\t\tmodel = buildModel(path_weights)\n\ndef createGenerator(dir_img, file_labels, file_h5=None, batch_size=64):\n\n\tdata_augmentation_chain = DataAugmentationConstantInputSize(\n\t\t\t\t\t\t\t\trandom_brightness=(-48, 48, 0.5),\n\t\t\t\t\t\t\t\trandom_contrast=(0.5, 1.8, 0.5),\n\t\t\t\t\t\t\t\trandom_saturation=(0.5, 1.8, 0.5),\n\t\t\t\t\t\t\t\trandom_hue=(18, 0.5),\n\t\t\t\t\t\t\t\trandom_flip=0.5,\n\t\t\t\t\t\t\t\trandom_translate=((0.03,0.5), (0.03,0.5), 0.5),\n\t\t\t\t\t\t\t\trandom_scale=(0.5, 2.0, 0.5),\n\t\t\t\t\t\t\t\tn_trials_max=3,\n\t\t\t\t\t\t\t\tclip_boxes=True,\n\t\t\t\t\t\t\t\toverlap_criterion='area',\n\t\t\t\t\t\t\t\tbounds_box_filter=(0.3, 1.0),\n\t\t\t\t\t\t\t\tbounds_validator=(0.5, 1.0),\n\t\t\t\t\t\t\t\tn_boxes_min=1,\n\t\t\t\t\t\t\t\tbackground=(0,0,0))\n\n\tpredictor_sizes = [model.get_layer('classes4').output_shape[1:3],\n\t\t\t\t\t\tmodel.get_layer('classes5').output_shape[1:3],\n\t\t\t\t\t\tmodel.get_layer('classes6').output_shape[1:3],\n\t\t\t\t\t\tmodel.get_layer('classes7').output_shape[1:3]]\n\n\tssd_input_encoder = SSDInputEncoder(img_height=img_height,\n\t\t\t\t\t\t\t\t\timg_width=img_width,\n\t\t\t\t\t\t\t\t\tn_classes=n_classes,\n\t\t\t\t\t\t\t\t\tpredictor_sizes=predictor_sizes,\n\t\t\t\t\t\t\t\t\tscales=scales,\n\t\t\t\t\t\t\t\t\taspect_ratios_global=aspect_ratios,\n\t\t\t\t\t\t\t\t\ttwo_boxes_for_ar1=two_boxes_for_ar1,\n\t\t\t\t\t\t\t\t\tsteps=steps,\n\t\t\t\t\t\t\t\t\toffsets=offsets,\n\t\t\t\t\t\t\t\t\tclip_boxes=clip_boxes,\n\t\t\t\t\t\t\t\t\tvariances=variances,\n\t\t\t\t\t\t\t\t\tmatching_type='multi',\n\t\t\t\t\t\t\t\t\tpos_iou_threshold=0.5,\n\t\t\t\t\t\t\t\t\tneg_iou_limit=0.3,\n\t\t\t\t\t\t\t\t\tnormalize_coords=normalize_coords)\n\n\n\n\tdatagen = DataGenerator(load_images_into_memory=False, hdf5_dataset_path=file_h5)\n\tdatagen.parse_csv(images_dir=dir_img,\n\t\t\t\t\t\t\tlabels_filename=file_labels,\n\t\t\t\t\t\t\tinput_format=['xmin', 'ymin', 'xmax', 'ymax', 'image_name','class_id'],\n\t\t\t\t\t\t\tinclude_classes='all')\n\n\tif not file_h5:\n\t\tdatagen.create_hdf5_dataset(file_path=file_h5,\n\t\t\t\t\t\t\t\t\tresize=False,\n\t\t\t\t\t\t\t\t\tvariable_image_size=False,\n\t\t\t\t\t\t\t\t\tverbose=True)\n\n\tprint('number of images: %d' %datagen.get_dataset_size())\n\n\tgenerator = datagen.generate(batch_size=batch_size,\n\t\t\t\t\t\t\t\t\tshuffle=True,\n\t\t\t\t\t\t\t\t\ttransformations=[data_augmentation_chain],\n\t\t\t\t\t\t\t\t\tlabel_encoder=ssd_input_encoder,\n\t\t\t\t\t\t\t\t\treturns={'processed_images',\n\t\t\t\t\t\t\t\t\t\t\t'encoded_labels'},\n\t\t\t\t\t\t\t\t\tkeep_images_without_gt=False)\n\n\treturn generator, datagen.get_dataset_size()\n\ndef createCallBacks(path_history):\n\tif not os.path.isdir(path_history):\n\t\tos.mkdir(path_history)\n\n\tfile_checkpoint = '{epoch:03d}_{loss:.4f}_{val_loss:.4f}.h5'\n\tfile_log = 'ssd7_training_log.csv'\n\n\tcheckpoint = ModelCheckpoint(filepath=os.path.join(path_history,file_checkpoint),\n\t\t\t\t\t\t\t\tmonitor='val_loss',\n\t\t\t\t\t\t\t\tverbose=1,\n\t\t\t\t\t\t\t\tsave_best_only=True,\n\t\t\t\t\t\t\t\tsave_weights_only=False,\n\t\t\t\t\t\t\t\tmode='auto',\n\t\t\t\t\t\t\t\tperiod=1)\n\n\tlogger = CSVLogger(filename=os.path.join(pathHistory,file_log),\n\t\t\t\t\t\t\tseparator=',',\n\t\t\t\t\t\t\tappend=True)\n\n\tearly_stopping = EarlyStopping(monitor='val_loss',\n\t\t\t\t\t\t\t\tmin_delta=0.0,\n\t\t\t\t\t\t\t\tpatience=10,\n\t\t\t\t\t\t\t\tverbose=1)\n\n\treduce_lr = ReduceLROnPlateau(monitor='val_loss',\n\t\t\t\t\t\t\t\t\t\tfactor=0.1,\n\t\t\t\t\t\t\t\t\t\tpatience=5,\n\t\t\t\t\t\t\t\t\t\tverbose=1,\n\t\t\t\t\t\t\t\t\t\tmin_delta=0.001,\n\t\t\t\t\t\t\t\t\t\tcooldown=0,\n\t\t\t\t\t\t\t\t\t\tmin_lr=0.00001)\n\n\tcallbacks = [checkpoint, logger, early_stopping, reduce_lr]\n\n\treturn callbacks\n\nif __name__ == \"__main__\":\n\tdir_img = '/DataSet/Crowdai300/' # image dir\n\tfile_labels_train = '/DataSet/train.csv' # file labels train\n\tfile_labels_val = '/DataSet/val.csv'\t# file labels val\n\tpath_history = '/DataSet/History'\t\t# dir contain results\n\t\n\tmodel = createModel()\n\n\tgenerator_train, nb_samples_train = createGenerator(dir_img, file_labels_train, batch_size=batch_size)\n\tgenerator_val, nb_samples_val = createGenerator(dir_img, file_labels_val, batch_size=batch_size)\n\n\tcallbacks = createCallBacks(path_history)\n\n\tini_epoch = 0\n\tnb_epochs = 200\n\tsteps = ceil(nb_samples_train/batch_size) \n\tsteps_val = ceil(nb_samples_val/batch_size) \n\n\tmodel.fit_generator(generator=generator_train,\n\t\t\t\t\t\tsteps_per_epoch=steps_per_epoch,\n\t\t\t\t\t\tepochs=nb_epochs,\n\t\t\t\t\t\tcallbacks=callbacks,\n\t\t\t\t\t\tvalidation_data=generator_val,\n\t\t\t\t\t\tvalidation_steps=steps_val,\n\t\t\t\t\t\tinitial_epoch=ini_epoch)\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"131058160","text":"from DibujoSvg import Dibujo\nfrom Punto import Punto\nfrom FibonacciHeap import FH\nfrom random import randint\nfrom time import sleep, time\nimport matplotlib.pyplot as plt\n\n\n# iniciadores\ndef CrearPuntos(ancho, alto, numPuntos=50): # Cambias el valor para decidir cuantos puntos habrá\n # Crea un número N de puntos aleatorios y su matriz de adyacencia\n dibujo = Dibujo(ancho, alto)\n l = [] # lista de puntos\n g = [] # matriz de adyacencia\n\n for i in range(0, numPuntos):\n l.append(Punto(randint(0, alto), randint(0, ancho), aleatorio=False)) # Se crea un punto aleatorio\n dibujo.EscribirLinea(l[-1].GetSvg()) # Se dibuja en SVG el punto creado\n # sleep(0.25)#Se espera\n for j in range(len(l)):\n g.append([0] * len(l)) # Se inicializan a 0 las distancias\n for i in range(0, len(l)):\n for j in range(0, len(l)):\n if i == j:\n g[i][j] = float(\n \"inf\") # La distancia de un punto a él mismo se pone infinita para que no sea factible nunca\n else:\n g[i][j] = l[i].CalcularDistancia(l[j]) # Se rellena la matriz con las distancias a todos los puntos\n g[j][i] = g[i][j]\n return l, g, dibujo\n\n\ndef CrearCuadrícula(ancho, alto, numPuntos, dibujo):\n l = [] # lista de puntos\n g = [] # matriz de adyacencia\n separación = 50\n for i in range(0, numPuntos):\n for j in range(0, numPuntos):\n l.append(Punto(10 + i * separación, 10 + j * separación)) # Se crea un punto aleatorio\n dibujo.EscribirLinea(l[-1].GetSvg()) # Se dibuja en SVG el punto creado\n # sleep(0.25)#Se espera\n for j in range(len(l)):\n g.append([0] * len(l))\n for i in range(0, len(l)):\n print(i)\n for j in range(0, len(l)):\n if i == j:\n g[i][j] = float(\"inf\")\n else:\n g[i][j] = l[i].CalcularDistancia(l[j]) # Se rellena la matriz con las distancias a todos los puntos\n g[j][i] = g[i][j]\n return l, g\n\n\n\ndef SacarAristas(g, elem, visitados, aristas=FH()): # Devuelve en una lista todas las aristas del elemento indicado\n for i in range(0, len(g[elem])):\n if not visitados[i] and g[elem][i]!=float(\"inf\"):\n aristas.añadir((elem, i, g[elem][i])) # Se devuelve i,j,distancia\n return aristas\n\ndef CrearLinea(p1, p2):\n # Crea una línea entre dos puntos, además, deja un espacio vacío para que quede bonito\n i1, j1 = p1.GetPuntos()\n r1 = p1.GetRadio()\n r2 = p2.GetRadio()\n i2, j2 = p2.GetPuntos()\n IncrementoJ1 = (j2 - j1)\n IncrementoJ2 = -IncrementoJ1\n IncrementoI1 = (i2 - i1)\n IncrementoI2 = -IncrementoI1\n\n h = (IncrementoI1 ** 2 + IncrementoJ1 ** 2) ** 0.5 # hipotenusa\n return ''\n\n\ndef Prim(g, l, dibujo):\n visitados = [False] * len(g)\n visitados[0] = True\n aristas = SacarAristas(g, 0, visitados)\n while not all(visitados) and not aristas.IsEmpty():\n linea = aristas.extractmin()\n if not visitados[linea[1]]:\n dibujo.EscribirLinea(CrearLinea(l[linea[0]], l[linea[1]]), True) # Se dibuja la linea que une los puntos\n #sleep(5)\n dibujo.Mostrar()\n visitados[linea[1]] = True\n SacarAristas(g, linea[1], visitados, aristas) # Se añaden las aristas del nuevo punto\n dibujo.Terminar()\n\n\n\ndef UnirTodo(g, l, dibujo):\n for i in range(0, len(g)):\n for j in range(0, len(g)):\n if not i == j:\n dibujo.EscribirLinea(CrearLinea(l[i], l[j]), True)\n else:\n break\n dibujo.Mostrar()\n\n\nancho = 1920\nalto = 1080\npuntos = 50\n\nsleep(1)\nl, g, d = CrearPuntos(ancho, alto, puntos)\n\"\"\"\np1=Punto(200,300)\np2=Punto(100,200)\nEscribirLinea(p1.GetSvg())\nEscribirLinea(p2.GetSvg())\nEscribirLinea(CrearLinea(p2,p1))\n\"\"\"\nd.Mostrar()\nPrim(g, l, d)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"353659998","text":"array=[5,7,9,0,3,1,6,2,4,8]\n\ndef quick_sort(array,start,end):\n if start>=end: # 원소가 1개인 경우 종료\n return\n pivot=start #피벗은 첫번째 원소\n left=start+1\n right =end\n while left<=right:\n while left <= end and array[left] <= array[pivot]:\n left +=1\n while right >start and array[right] >=array[pivot]:\n right -=1\n\n if left >right:\n array[right],array[pivot]=array[pivot],array[right]\n else:\n array[left],array[right]=array[right],array[left]\n quick_sort(array,start,right-1)\n quick_sort(array,right+1,end)\n\nquick_sort(array,0,len(array)-1)\nprint(array)\n","sub_path":"정렬/QuickSort.py","file_name":"QuickSort.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"600072868","text":"from inhere import myproject\nimport re\n\n\ninfo = {'Cid': '2019171064',\n 'Cname': '天津华电南疆热电环保信息化平台项目',\n 'Ccompany': '天津华电南疆热电有限公司',\n 'Caddress': '天津市塘沽区港塘路2657号 天津华电南疆热电有限公司 物资部',\n 'Cperson': '曾春',\n 'Cphone': '18874053395',\n }\n\n\n\npath = r\"C:\\Users\\gao\\Desktop\\环保\\projects\"\nname = \"2019173067广东华电韶关热电有限公司环保信息化平台合同\"\nfilename = \"深圳坪山\"\n\na1 = myproject(path)\na1.makepro('天津南疆')\na1.makefy(info)\n\n\n\n\nid = re.match(r\"\\d*\",name)\norg = re.match(r\"[^0-9]*\",name)\n\n\n\n\n","sub_path":"Xiangmu/ProjectXG.py","file_name":"ProjectXG.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"104707952","text":"#!/usr/bin/python\n\"\"\"\nTime series analysis of data\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pylab as ppl\n\nppl.close('all')\n\n# Load paramters\nimport ConfigDetailSingle\nreload(ConfigDetailSingle)\nfrom ConfigDetailSingle import *\n\nnT = 2 #Thermistor number\n\n# Chunks working best for 380-450 \nChunk1 = np.array([388, 404.5])\nChunk2 = np.array([408.5, 422.2])\n\n# For 290-350\n#Chunk1 = np.array([291.4, 306.5])\n#Chunk2 = np.array([312.1, 335.3])\n#Chunk2 = np.array([311.9, 315.2])\n#Chunk2 = np.array([307.4, 315.2])\n#Chunk2 = np.array([331.1, 341.5])\n\n#function to perform block averaging\nfrom BlockAverage import BlockAverage\n\nprint ('Load data...')\n\nfrom netCDF4 import Dataset as ncdf\nfile = ncdf(DetailDir+'Output_data.nc', mode='r', format='NETCDF4')\ntime = file.variables['Time'][:]\nT = file.variables['Temp'][nT-1,np.nonzero((time>=Start)&(time<=End))[0]]\nZ = file.variables['Depth'][nT-1]\nddt = file.SkipData\nfile.close()\ntime = time[np.nonzero((time>=Start)&(time<=End))]\n\nprint ('Data loaded')\n\n# Make block average of data if subsampling is requested\nT = BlockAverage(T, ddt, SubSamp)\ntime = BlockAverage(time, ddt, SubSamp)\n\n# Interpolate to regular time step\nintTime = np.arange(time[0], time[-1], SubSamp/86400.)\nData = np.interp(intTime, time, T, left=np.nan, right=np.nan)\ntime = intTime\n\n# For the FFT analysis\nfrom scipy.signal import detrend\nT1 = T[np.nonzero((time>Chunk1[0])&(time<=Chunk1[1]))]\nT1 = detrend(T1)\nT2 = T[np.nonzero((time>Chunk2[0])&(time<=Chunk2[1]))]\nT2 = detrend(T2)\ntime1 = time[np.nonzero((time>Chunk1[0])&(time<=Chunk1[1]))]\ntime2 = time[np.nonzero((time>Chunk2[0])&(time<=Chunk2[1]))]\n\nprint ('Fourier analysis')\n\n# Use Hanning window (see pag.445 Data Analysis Methods in Phys. Oc)\nfrom scipy.signal import hann\nT1w = T1*hann(T1.size)\nT2w = T2*hann(T2.size)\n# Use Kaiser window\n#from scipy.signal import kaiser\n#T1 *= kaiser(T1.size, 2)\n#T2 *= kaiser(T1.size, 2)\n\nprint ('Compute FFT')\n# Use matplotlib psd\n\nN1 = 2**int(np.log2(T1w.size)+1); N2 = 2**int(np.log2(T2w.size)+1)\n#N1 = 2**22; N2=2**22\n\n# 8/3 for hanning\n# N1/T1.size for compensate zero padding\nfft_pw1 = (N1/np.float(T1.size))*np.abs(((8./3.)**0.5)*np.fft.fft(T1w,N1)) ** 2 # FFT power spectrum\nfft_pw2 = (N2/np.float(T2.size))*np.abs(((8./3.)**0.5)*np.fft.fft(T2w,N2)) ** 2\nfreqs1 = np.fft.fftfreq(len(fft_pw1), SubSamp) # frequencies of FFT\nfreqs2 = np.fft.fftfreq(len(fft_pw2), SubSamp)\n\n# Normalization: Dt*abs(FFT)**2/N\n# this way Df*sum(power)/N = variance\nfft_power1 = SubSamp*fft_pw1[:fft_pw1.size/2]/N1\nfft_power1[1:] += SubSamp*fft_pw1[fft_pw1.size/2+1:]/N1\nfft_power2 = SubSamp*fft_pw2[:fft_pw2.size/2]/N2\nfft_power2[1:] += SubSamp*fft_pw2[fft_pw2.size/2+1:]/N2\nfreqs1 = freqs1[:freqs1.size/2]\nfreqs2 = freqs2[:freqs2.size/2]\n\nwin = 19 #width of smoothing window\nsm_fft_power1 = np.convolve(fft_power1,np.ones(win))\nsm_fft_power1 = sm_fft_power1[(win/2):-(win/2)]/np.float(win)\nsm_fft_power2 = np.convolve(fft_power2,np.ones(win))\nsm_fft_power2 = sm_fft_power2[(win/2):-(win/2)]/np.float(win)\n\n# significance levels for smoothed spectra (pag.454 Data Analysis Methods in Phys. Oc.)\nfrom scipy.stats import chi2\nslev = 0.05 # significance level\nnu1 = 2*win#T1.size/np.float(win) *8./3. # for a Hanning window!\nnu2 = 2*win#T2.size/np.float(win) *8./3.\nsig1 = np.diff([np.log10(nu1/chi2.ppf(1-slev/2,nu1)), np.log10(nu1/chi2.ppf(slev/2,nu1))])\nsig2 = np.diff([np.log10(nu2/chi2.ppf(1-slev/2,nu2)), np.log10(nu2/chi2.ppf(slev/2,nu2))])\n\nprint ('Wavelet analysis')\n\nfrom sys import path\n#Path to toolbox\npath.append('/home/cimatori/installed')\n\nimport wavelet\n\nstd = Data.std() # Standard deviation\nstd2 = std ** 2 # Variance\nvar = (Data - Data.mean()) / std # Calculating anomaly and normalizing\n#p = np.polyfit(time, Data, 1) # Linear fit of the data\n#var = (Data - p[0]*time - p[1]) / std # Calculating anomaly, normalizing and removing linear trend\n\nN = var.size # Number of measurements\n\nmother = wavelet.Morlet(6.) # Morlet mother wavelet with wavenumber=6\n#mother = wavelet.Mexican_hat() # Mexican hat wavelet, or DOG with m=2\n#mother = wavelet.Paul(4) # Paul wavelet with order m=4\n#mother = wavelet.DOG(6) # Derivative of the Gaussian, with m=6\n\n# perform the wavelet transform\nwave, scales, freqs, coi, fft, fftfreqs = wavelet.cwt(var, dt, dj, s0, J,\n mother)\n\npower = (np.abs(wave)) ** 2 # Normalized wavelet power spectrum\nfft_power = std2 * np.abs(fft) ** 2 # FFT power spectrum\nperiod = 1. / freqs\n\n# Calculates the global wavelet spectrum\nglbl_power = std2 * power.mean(axis=1)\n\n# Scale average between avg1 and avg2 periods and significance level\nsel = ppl.find((period >= avg1) & (period < avg2))\n#sel = np.ones(period.shape, dtype=int)\nCdelta = mother.cdelta\nscale_avg = (scales * np.ones((N, 1))).transpose()\n# As in Torrence and Compo (1998) equation 24\nscale_avg = power / scale_avg\nscale_avg = std2 * dj * dt / Cdelta * scale_avg[sel, :].sum(axis=0)\n\n# Compute time average of scale average in the chunks\nw_power1 = SubSamp*std2*\\\n np.mean(power[:,np.nonzero((time>Chunk1[0])&(time<=Chunk1[1]))[0]],\n axis=1)\nw_power2 = SubSamp*std2*\\\n np.mean(power[:,np.nonzero((time>Chunk2[0])&(time<=Chunk2[1]))[0]],\n axis=1)\n\nprint ('Done.\\n Plot data...')\n\n# The following routines plot the results in four different subplots containing\n# the original series anomaly, the wavelet power spectrum, the global wavelet\n# and Fourier spectra and finally the range averaged wavelet spectrum. In all\n# sub-plots the significance levels are either included as dotted lines or as\n# filled contour lines.\n#ppl.ion()\nfontsize = 'medium'\nparams = {'text.fontsize': fontsize,\n 'xtick.labelsize': fontsize,\n 'ytick.labelsize': fontsize,\n 'axes.titlesize': fontsize\n }\nppl.rcParams.update(params) # Plot parameters\n\n#\n# First plot, wavelet analysis\n#\n\nfigprops = dict(figsize=(11, 8))\nfig = ppl.figure(**figprops)\n\nunits='^{\\circ}C'\ntitle='Time series at depth {:.1f}m'.format(Z)\nlabel='Temp.'\n# First sub-plot, the original time series anomaly.\n\nax = fig.add_axes([0.1, 0.75, 0.65, 0.2])\nax.plot(time, Data, 'k', linewidth=1.5)\ntmin = Data.min()-Data.std(); tmax=Data.max()+Data.std()\nax.set_title('a) %s' % (title, ))\nif units != '':\n ax.set_ylabel(r'%s [$%s$]' % (label, units,))\nelse:\n ax.set_ylabel(r'%s' % (label, ))\nax.set_ylim(tmin,tmax)\n\n# Second sub-plot, the normalized wavelet power spectrum and significance level\n# contour lines and cone of influece hatched area.\nbx = fig.add_axes([0.1, 0.37, 0.65, 0.28], sharex=ax)\npmean = np.log2(power).mean(); pstd = np.log2(power).std()\nlevels = np.arange(int(pmean-2*pstd),int(pmean+2*pstd),1)\nbx.contourf(time, np.log2(period), np.log2(power), levels,\n extend='both')\n#bx.contour(time, np.log2(period), sig95, [-99, 1], colors='k',\n# linewidths=2.)\nbx.fill(np.concatenate([time[:1]-dt, time, time[-1:]+dt, time[-1:]+dt,\n time[:1]-dt, time[:1]-dt]), np.log2(np.concatenate([[1e-9], np.fmax(coi,1e-9),\n [1e-9], period[-1:], period[-1:], [1e-9]])), 'k', alpha='0.3',\n hatch='x')\nbx.plot([time[0],time[-1]], [np.log2(Tf/24.),np.log2(Tf/24.)], '--',\n color=[0.5,0.5,0.5], lw=2) # Inertial period\nbx.plot([time[0],time[-1]], [np.log2(avg1),np.log2(avg1)], 'w-') # Power averaging limits\nbx.plot([time[0],time[-1]], [np.log2(avg2),np.log2(avg2)], 'w-')\nbx.set_title('b) %s Wavelet Power Spectrum (%s)' % (label, mother.name))\nbx.set_ylabel('Period (hours)')\nYticks = 2 ** np.arange(np.ceil(np.log2(period.min())),\n np.ceil(np.log2(period.max())))\nbx.set_yticks(np.log2(Yticks))\nbx.set_yticklabels([\"%.3f\" % tick for tick in Yticks*24])\nbx.set_ylim(np.log2([period.min(), period.max()]))\nbx.invert_yaxis()\n\n# Third sub-plot, the global wavelet and Fourier power spectra and theoretical\n# noise spectra.\ncx = fig.add_axes([0.77, 0.37, 0.2, 0.28], sharey=bx)\n#cx.plot(np.log10(glbl_signif), np.log2(period), 'k--')\ncx.plot(np.log10(fft_power), np.log2(1./fftfreqs), '-', color=[0.7, 0.7, 0.7],\n linewidth=1.)\ncx.plot(np.log10(glbl_power), np.log2(period), 'k-', linewidth=1.5)\ncx.plot([-100,100], [np.log2(Tf/24.),np.log2(Tf/24.)], '--',\n color=[0.5,0.5,0.5], lw=2)\ncx.set_title('c) Global Wavelet Spectrum')\nif units != '':\n cx.set_xlabel(r'log(Power) [$%s^2$]' % (units, ))\nelse:\n cx.set_xlabel(r'log(Power)')\ncx.set_xlim([-9, np.log10(glbl_power.max())+0.9])\ncx.set_ylim(np.log2([period.min(), period.max()]))\ncx.set_yticks(np.log2(Yticks))\n#cx.set_yticklabels(Yticks)\nppl.setp(cx.get_yticklabels(), visible=False)\ncx.invert_yaxis()\n\n# Fourth sub-plot, the scale averaged wavelet spectrum as determined by the\n# avg1 and avg2 parameters\ndx = fig.add_axes([0.1, 0.07, 0.65, 0.2], sharex=ax)\n#dx.axhline(scale_avg_signif, color='k', linestyle='--', linewidth=1.)\ndx.plot(time, scale_avg, 'k-', linewidth=1.5)\ndx.set_title('d) ${}$-${}$ hour scale-averaged power' .format(24*avg1, 24*avg2))\ndx.set_xlabel('Time (yeardays)')\nif units != '':\n dx.set_ylabel(r'Average variance [$%s$]' % (units, ))\nelse:\n dx.set_ylabel(r'Average variance')\n#\nax.set_xlim([time.min(), time.max()])\n#\nppl.draw()\nppl.show()\nfig.savefig(OutDir+'WaveletAnalysis/'+\\\n 'Wavelet_analysis_nT_{}_day_{}_{}_SubSample_{}.png'.format(nT,Start,End,SubSamp))\n\n#\n# Second plot: comparison between fourier transform and wavelet power\n#\n\nfigprops = dict(figsize=(11, 6))\nfig = ppl.figure(**figprops)\nfig.subplots_adjust(wspace=0.5, hspace=0.5)\n\n#First subplot, time series\nax = ppl.subplot2grid((3,2), (0,0), colspan=3, rowspan=1)\nax.plot(time, Data, 'k', linewidth=1.5)\ntmin = Data.min()-Data.std(); tmax=Data.max()+Data.std()\nax.fill(np.hstack((Chunk1,Chunk1[::-1])), [tmin,tmin,tmax,tmax], 'b', alpha=0.5)\nax.fill(np.hstack((Chunk2,Chunk2[::-1])), [tmin,tmin,tmax,tmax], 'r', alpha=0.5)\nax.set_title('a) %s' % (title, ))\nif units != '':\n ax.set_ylabel(r'%s [$%s$]' % (label, units,))\nelse:\n ax.set_ylabel(r'%s' % (label, ))\nax.set_ylim(tmin,tmax)\n\n# First sub-plot, spectra of first chunk\nbx = ppl.subplot2grid((3,2), (1,0), colspan=1, rowspan=2)\n\n#Handy pointers for plotting spectra\nper1 = np.log10(1./freqs1)\nper2 = np.log10(1./freqs2)\ndata1 = np.log10(fft_power1) # data to be plotted\ndata2 = np.log10(fft_power2)\nsdata1 = np.log10(sm_fft_power1)\nsdata2 = np.log10(sm_fft_power2)\n\n#plot spectrum\nbx.plot(per1, data1, 'b-', linewidth=0.5, alpha=0.3)\nbx.plot(per1, sdata1, 'b-', linewidth=1.5, alpha=0.7)\nbx.plot(np.log10(period*86400), np.log10(w_power1), 'b-', linewidth=2)\nxsig = np.log10(60); ysig=1 #where to centre significance bar\nbx.errorbar(xsig,ysig, yerr=sig1, color='k', lw=2)\n\nbx.set_title('b) PS time interval: {}-{} days'.format(Chunk1[0],Chunk1[1]))\nbx.set_ylabel('$\\log_{10}$(Power) [$'+units+'^2 \\cdot Hz^{-1}$]')\n\n# Fifth sub-plot, spectra of second chunk\ncx = ppl.subplot2grid((3,2), (1,1), colspan=1, rowspan=2)\n\n#plot spectrum\ncx.plot(per2, data2, 'r-', linewidth=0.5, alpha=0.3)\ncx.plot(per2, sdata2, 'r-', linewidth=1.5, alpha=0.7)\ncx.plot(np.log10(period*86400), np.log10(w_power2), 'r-', linewidth=2)\ncx.errorbar(xsig,ysig, yerr=sig2, color='k', lw=2)\n\ncx.set_title('c) Time interval: {}-{} days'.format(Chunk2[0],Chunk2[1]))\n\n# Common settings for the spectra of the two chunks\n# plot reference lines\nxi = np.log10(np.array([86400, 3600])); xh = np.log10(np.array([2400, 180]))\nslopes = [3, 2, 5./3] # slopes to be plotted\nticks = np.array([60, 600, 3600, 86400]) #ticks to be used\nbx.plot(xi, xi-xi[0]+2, 'k-', lw=2)\nbx.text(xi[0], 2, '-1', fontsize='x-large')\n#cx.plot(xi, 2*(xi-xi[0])+3, 'k-', lw=2) # -2 slope\ncx.plot(xi, xi-xi[0]+2, 'k-', lw=2) # -1 slope\ncx.text(xi[0], 2, '-1', fontsize='x-large')\nfor axis in [bx,cx]:\n for slope in slopes:\n axis.plot(xh, slope*xh-slope*xh[1]-3, color='k', lw=2)\n # plot inertial frequency\n axis.plot(2*[np.log10(Tf*3600)], [-100, 100],\\\n '--', color=[0.5,0.5,0.5], lw=2)\n # settings common to spectra subplots\n axis.set_xlabel('Period [hours]')\n axis.set_xticks(np.log10(ticks))\n axis.set_xticklabels([\"%.3f\" % member for member in ticks/3600.])\n axis.set_xlim(np.log10(2.5*86400), np.log10(61))\nbx.set_ylim(sdata1.min(), sdata1.max()+1)\ncx.set_ylim(sdata2.min(), sdata2.max()+1)\n\nppl.draw()\nppl.show()\nfig.savefig(OutDir+'WaveletAnalysis/'+\\\n 'Wavelet_FFT_analysis_nT_{}_day_{}_{}_SubSample_{}.png'.format(nT,Start,End,SubSamp))\n\nprint ('Done.')\n","sub_path":"CanaryBasin/Wavelet_FFT_analysis.py","file_name":"Wavelet_FFT_analysis.py","file_ext":"py","file_size_in_byte":12627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"246681021","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom urllib.parse import unquote, unquote_plus\n\n\ndef main():\n url1 = \"http://localhost:8080/~hellmann/\"\n url2 = \"http%3A%2F%2Flocalhost%3A8080%2F%7Ehellmann%2F\"\n\n print(\"unquote() :\", unquote(url1))\n print(\"unquote_plus():\", unquote_plus(url2))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"standard/057.urllib.parse/encode_query_arguments/urllib_parse_unquote.py","file_name":"urllib_parse_unquote.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"211262621","text":"dnaResult = []\nfileContent = \"\"\nfileContent1 = \"\"\nfileContent2 = \"\"\nmutateFile = \"\"\nnormalFile = \"\"\n\n#this function takes the users DNA sequence input and slpits it on every third character in the sequence (the code in line 2) and then runs a for loop for each set of 3 characters to test which Amino Acid the 3 characters form and adds the Acids accronym to the empty list which is returned at the end of the function\ndef translate(fileContent):\n sequence = [fileContent[i:i+3] for i in range(0, len(fileContent), 3)]\n for item in sequence:\n if item == \"ATT\" or item == \"ATC\" or item == \"ATA\" : \n dnaResult.append(\" I \")\n elif item == \"CTT\" or item == \"CTC\" or item == \"CTA\" or item == \"CTG\" or item == \"TTA\" or item == \"TTG\" : \n dnaResult.append(\" L \")\n elif item == \"GTT\" or item == \"GTC\" or item == \"GTA\" or item == \"GTG\" :\n dnaResult.append(\" V \")\n elif item == \"TTT\" or item == \"TTC\" : \n dnaResult.append(\" F \")\n elif item == \"ATG\" : \n dnaResult.append(\" M \")\n else:\n dnaResult.append(\" X \")\n return dnaResult\n\n#i open the file and then read each line \nfile = open(\"DNA.txt\",\"r\" )\nfileContent = file.read()\nfile.close()\n\n#then i make a for loop to go over each letter which was read from the file, if the latter is ‘a’ it mutates it ‘T’ and fix’s it ‘A’ and adds it to variables mutateFile and normalFile, if the letter is not ‘a’ it just adds the letter exactly as is to the same variables\nfor letter in fileContent:\n if letter == \"a\":\n mutateFile = (mutateFile + \"T\")\n normalFile = (normalFile + \"A\")\n else :\n mutateFile = (mutateFile + letter)\n normalFile = (normalFile + letter)\n\n#next 2 functions open 2 new files and writes to each file one of the different variabls mutateFile and normalFile\nfile = open(\"mutatedDNA.txt\",\"w\")\nfile.write(mutateFile)\nfile.close()\n\nfile = open(\"normalDNA.txt\",\"w\")\nfile.write(normalFile)\nfile.close()\n\n#the next 2 functions read from each file that was created above and runs them through the function “translate” to find the amino acids in each DNA sequence, i think this is where my error comes in, its when you call these to functions\nfile = open(\"mutatedDNA.txt\",\"r\")\nfileContent1 = file.read()\nprint(\"These are the folowing Amino Acids found in the DNA sequence's found in the mutated DNA text file : '\" + str(translate(fileContent1)))\nfile.close()\n\ndnaResult.clear()\n\nfile = open(\"normalDNA.txt\",\"r\")\nfileContent2 = file.read()\nprint(\"These are the folowing Amino Acids found in the DNA sequence's found in the normal DNA text file : '\" + str(translate(fileContent2)))\nfile.close()\n\ndnaResult.clear()\n","sub_path":"DNA_readfile.py","file_name":"DNA_readfile.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"126576279","text":"# Copyright 2020 The Forte Authors. All Rights Reserved.\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\"\"\"\nTrain preprocessor helps doing data pre-processing during training.\n\"\"\"\nimport logging\nfrom typing import Optional, Dict, Type, Any, Union, Iterator, List\nfrom texar.torch.data import DataIterator, Batch\nimport torch\nfrom torch import device\n\nfrom forte.common.configuration import Config\nfrom forte.data.converter import Converter\nfrom forte.data.data_pack import DataPack\nfrom forte.data.data_pack_dataset import DataPackDataset, DataPackIterator\nfrom forte.data.base_extractor import BaseExtractor\nfrom forte.data.ontology.core import Entry\nfrom forte.data.ontology.core import EntryType\nfrom forte.utils import get_class\n\nlogger = logging.getLogger(__name__)\n\n__all__ = [\"TrainPreprocessor\"]\n\n\nclass TrainPreprocessor:\n r\"\"\"\n `TrainPreprocessor` provides the functionality of doing pre-processing work\n including building vocabulary, extracting the features, batching and\n padding (optional). The main functionality is provided by its method\n :meth:`get_train_batch_iterator` which will return an `iterator` over the\n batch of pre-processed data. Please refer to the documentation of\n that method for how the pre-processing is done.\n\n `TrainPreprocessor` will maintain a Config that stores all the configurable\n parameters for various components.\n\n `TrainPreprocessor` will also accept a user request. Internally it will\n parse this user request and store the parsed result.\n\n Args:\n pack_iterator (Iterator[DataPack]): An iterator of\n :class:`~forte.data.data_pack.DataPack`.\n request (Dict): A request that specifies how to do train pre-processing.\n Please refer to :meth:`request` for details.\n config: A `Dict` or :class:`~forte.common.configuration.Config` that\n configs this preprocessor. See :meth:`default_configs` for\n the defaults.\n\n\n .. note::\n For parameters `request`, user does not necessarily need to provide\n `converter`. If no `converter` is specified, a default converter of\n type :class:`~forte.data.converter.Converter` will be picked.\n \"\"\"\n\n DATA_INPUT = 0\n DATA_OUTPUT = 1\n\n def __init__(self, pack_iterator: Iterator[DataPack]):\n self._pack_iterator: Iterator[DataPack] = pack_iterator\n self._cached_packs: List[DataPack] = []\n\n self._user_request: Dict = {}\n self._request: Dict = {}\n self._request_ready: bool = False\n self._vocab_ready: bool = False\n\n def initialize(self, config: Optional[Union[Config, Dict]] = None):\n # pylint: disable=attribute-defined-outside-init,unused-argument\n self._config = Config(config, default_hparams=self.default_configs())\n self._user_request = self._config.request\n self._validate_config()\n self._parse_request(self._user_request)\n self._build_vocab()\n\n @staticmethod\n def default_configs():\n r\"\"\"Returns a dictionary of default hyper-parameters.\n\n .. code-block:: python\n\n {\n \"preprocess\": {\n \"device\": \"cpu\",\n },\n \"dataset\": DataPackDataset.default_hparams()\n }\n\n Here:\n\n `\"preprocessor.device\"`:\n The device of the produced batches. For GPU training,\n set to current CUDA device.\n\n `\"dataset\"`:\n This contains all the configurable options same as\n :class:`~forte.data.data_pack_dataset.DataPackDataset`.\n \"\"\"\n\n # Configs should be serializable\n return {\n \"preprocess\": {\n \"device\": \"cpu\",\n },\n \"dataset\": DataPackDataset.default_hparams(),\n \"request\": {\"scope\": None, \"feature_scheme\": None},\n }\n\n def _validate_config(self):\n # Placeholder\n pass\n\n def _parse_request(self, request: Dict):\n \"\"\"\n This method has two responsibilities:\n 1. parse the given data request and stored it internally\n 2. validate if the given data request is valid\n \"\"\"\n parsed_request: Dict[str, Any] = {}\n\n assert \"scope\" in request, \"Field not found for data request: `scope`\"\n assert (\n \"feature_scheme\" in request\n ), \"Field not found for data request: `schemes`\"\n\n parsed_request[\"scope\"] = get_class(request[\"scope\"])\n parsed_request[\"schemes\"] = {}\n\n # Used for check dependency between different extractors\n scheme_group: Dict[str, Dict] = {\"dependent\": {}, \"dependee\": {}}\n\n for tag, scheme in request[\"feature_scheme\"].items():\n assert (\n \"extractor\" in scheme\n ), \"Field not found for data request scheme: `extractor`\"\n parsed_request[\"schemes\"][tag] = {}\n\n assert (\n \"type\" in scheme\n ), \"Field not found for data request scheme: `type`\"\n assert scheme[\"type\"] in [\n \"data_input\",\n \"data_output\",\n ], \"Type field must be either data_input or data_output.\"\n if scheme[\"type\"] == \"data_input\":\n parsed_request[\"schemes\"][tag][\n \"type\"\n ] = TrainPreprocessor.DATA_INPUT\n if scheme[\"type\"] == \"data_output\":\n parsed_request[\"schemes\"][tag][\n \"type\"\n ] = TrainPreprocessor.DATA_OUTPUT\n\n extractor_class = scheme[\"extractor\"][\"class_name\"]\n if not isinstance(get_class(extractor_class)(), BaseExtractor):\n raise RuntimeError(\"Invalid extractor: \", scheme[\"extractor\"])\n\n extractor: BaseExtractor = get_class(extractor_class)()\n extractor.initialize(config=scheme[\"extractor\"][\"config\"])\n parsed_request[\"schemes\"][tag][\"extractor\"] = extractor\n\n # Track dependency\n if hasattr(extractor, \"based_on\"):\n if extractor.entry_type not in scheme_group[\"dependent\"]:\n scheme_group[\"dependent\"][extractor.entry_type] = set()\n scheme_group[\"dependent\"][extractor.entry_type].add(extractor)\n else:\n if extractor.entry_type not in scheme_group[\"dependee\"]:\n scheme_group[\"dependee\"][extractor.entry_type] = set()\n scheme_group[\"dependee\"][extractor.entry_type].add(extractor)\n\n # Create default converter if there is no given converter\n if \"converter\" not in scheme:\n converter: Converter = Converter({})\n parsed_request[\"schemes\"][tag][\"converter\"] = converter\n\n # Check dependency\n for _, dependent_extractors in scheme_group[\"dependent\"].items():\n for dependent_extractor in dependent_extractors:\n based_on: Entry = dependent_extractor.based_on\n if based_on not in scheme_group[\"dependee\"]:\n raise ValueError(\n \"Extractor {} needs the entry {} to do extraction \"\n \"processing but it is not extracted by any other \"\n \"extractors given in request\".format(\n based_on, dependent_extractor.tag\n )\n )\n\n self._request = parsed_request\n self._request_ready = True\n\n def _build_vocab(self):\n scope: EntryType = self._request[\"scope\"]\n schemes: Dict = self._request[\"schemes\"]\n\n # TODO: clear vocab?\n\n # Cached all data packs\n for data_pack in self._pack_iterator:\n self._cached_packs.append(data_pack)\n\n for _, scheme in schemes.items():\n extractor: BaseExtractor = scheme[\"extractor\"]\n if extractor.vocab_method != \"raw\":\n for data_pack in self._cached_packs:\n for instance in data_pack.get(scope):\n extractor.update_vocab(data_pack, instance)\n\n self._vocab_ready = True\n\n def _build_dataset_iterator(self) -> DataIterator:\n scope: Type[EntryType] = self._request[\"scope\"] # type: ignore\n schemes: Dict[str, Dict[str, Any]] = self._request[\"schemes\"]\n\n data_source = DataPackIterator(\n pack_iterator=iter(self._cached_packs),\n context_type=scope,\n request={scope: []},\n )\n\n dataset = DataPackDataset(\n data_source, schemes, self._config.dataset, self.device\n )\n iterator = DataIterator(dataset)\n\n return iterator\n\n @property\n def request(self) -> Dict:\n # pylint: disable=line-too-long\n r\"\"\"A `Dict` containing all the information needed for doing the\n pre-processing. This is obtained via parsing the input `request`\n\n An example `request` is:\n\n .. code-block:: python\n\n request = {\n \"scope\": ft.onto.Sentence\n \"schemes\": {\n \"text_tag\": {\n \"extractor\": forte.data.extractor.AttributeExtractor,\n \"converter\": forte.data.converter.Converter,\n \"type\": TrainPreprocessor.DATA_INPUT,\n },\n \"char_tag\" {\n \"extractor\": forte.data.extractor.CharExtractor,\n \"converter\": forte.data.converter.Converter,\n \"type\": TrainPreprocessor.DATA_INPUT,\n }\n \"ner_tag\": {\n \"extractor\":\n forte.data.extractor.BioSeqTaggingExtractor,\n \"converter\": forte.data.converter.Converter,\n \"type\": TrainPreprocessor.DATA_OUTPUT,\n }\n }\n }\n\n Here:\n\n `\"scope\"`: Entry\n A class of type :class:`~forte.data.ontology.core.Entry` The\n granularity to separate data into different examples. For example,\n if `scope` is :class:`~ft.onto.base_ontology.Sentence`, then each\n training example will represent the information of a sentence.\n\n `\"schemes\"`: `Dict`\n A `Dict` containing the information about doing the pre-processing.\n The `key` is the tags provided by input `request`. The `value` is a\n `Dict` containing the information for doing pre-processing for that\n feature.\n\n `\"schemes.tag.extractor\"`: Extractor\n An instance of type :class:`~forte.data.extractor.BaseExtractor`.\n\n `\"schemes.tag.converter\"`: Converter\n An instance of type :class:`~forte.data.converter.Converter`.\n\n `\"schemes.tag.type\"`: TrainPreprocessor.DATA_INPUT/DATA_OUTPUT\n Denoting whether this feature is the input or output feature.\n \"\"\"\n if not self._request:\n self._parse_request(self._request)\n return self._request\n\n @property\n def device(self) -> device:\n r\"\"\"The device of the produced batches. For GPU training,\n set to current CUDA device.\n \"\"\"\n return torch.device(self._config.preprocess.device)\n\n @property\n def config(self) -> Config:\n r\"\"\"A :class:`~forte.common.configuration.Config` maintaining all the\n configurable options for this `TrainPreprocessor`.\n \"\"\"\n return self._config\n\n def get_train_batch_iterator(self) -> Iterator[Batch]:\n r\"\"\"\n This method mainly has four steps:\n\n 1. Iterate over :class:`~forte.data.data_pack.DataPack`\n via pack iterator\n 2. Extract :class:`~forte.data.converter.feature.Feature` from\n :class:`~forte.data.data_pack.DataPack`\n 3. Batch :class:`~forte.data.converter.feature.Feature`\n 4. (optional) Pad a batch of\n :class:`~forte.data.converter.feature.Feature`\n\n It will return an `iterator` of a batch of pre-processed data.\n\n Returns:\n An `Iterator` of type :class:`~texar.torch.data.Batch`\n\n Please refer to :meth:`collate` in\n :class:`~forte.data.data_pack_dataset.DataPackDataset` for details\n about its structure.\n \"\"\"\n if not self._request:\n raise ValueError(\"Feature resource is not parsed\")\n\n if not self._vocab_ready:\n raise ValueError(\"Vocab is not built\")\n\n dataset_iter = self._build_dataset_iterator()\n\n return iter(dataset_iter)\n","sub_path":"forte/train_preprocessor.py","file_name":"train_preprocessor.py","file_ext":"py","file_size_in_byte":13243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"417672064","text":"import ModelCreators.GANs\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass GAN:\n def __init__(self, images, discriminator, generator, network_optimizer, trainer, noise_dim=100):\n _, size = images.data.shape\n if (images.image_width * images.image_height != size):\n raise ValueError('Invalid image dimensions.')\n self.images = images\n \n self.discriminator = discriminator\n self.discriminator.trainable = False\n self.discriminator_loss = []\n \n self.generator = generator\n self.generator_loss = []\n \n self.network = ModelCreators.GANs.create_gan(generator, discriminator, network_optimizer, noise_dim)\n \n self.trainer = trainer\n \n self.noise_dim = noise_dim\n \n def train(self, epochs=1, batch_size=100):\n self.trainer(self, epochs, batch_size)\n\n def generateImages(self, number_images=100, dim=(10, 10), figsize=(10,10), filename=None):\n noise_vector = np.random.normal(0, 1, size=[number_images, self.noise_dim])\n \n generated_images = self.generator.predict(noise_vector)\n generated_images = generated_images.reshape(number_images,\n self.images.image_width, self.images.image_height)\n \n plt.figure(figsize=figsize)\n \n for image in range(number_images):\n plt.subplot(dim[0], dim[1], image + 1)\n plt.imshow(generated_images[image], interpolation='nearest', cmap='gray_r')\n plt.axis('off')\n \n plt.tight_layout()\n \n if filename is not None:\n plt.savefig(filename)\n else:\n plt.show()","sub_path":"YAGAN/GAN.py","file_name":"GAN.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"645937047","text":"# coding=utf-8\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\nimport calendar\nimport sys\n\n\ndef add_months(dt,months):\n month = dt.month - 1 + months\n year = dt.year + int(month / 12)\n month = month % 12 + 1\n day = min(dt.day, calendar.monthrange(year, month)[1])\n return dt.replace(year=year, month=month, day=day)\n\ntoday = datetime.now().date()\ntoday=today.replace(year=2012,month=1,day=1)\n\nprint(today)\n\ntodaytime = datetime.now()\n# todaytime=todaytime.date(2014,1,1)\n# print (today.)\nprint(today.replace(2014).strftime('%Y%m'))\n\n# print(isinstance(demo, unicode))\n# with open('a.txt', 'w+', encoding=\"gb2312\") as f:\n# f.write(wpage)\n\n\n# print(ss.find_all('tr'))\n# pd.dataframe\n\n# https://www.aqistudy.cn/historydata/daydata.php?city=%E6%9D%AD%E5%B7%9E&month=2014-12\nwith open('ZhouShan.csv', 'w+', encoding='utf-8') as f:\n detail=today.strftime('%Y%m')\n while detail<='201902':\n \n response = requests.get(\n 'http://qq.ip138.com/weather/zhejiang/ZhouShan/'+detail+'.htm')\n wpage = response.text\n wpage = wpage.encode('iso-8859-1').decode('gb2312')\n soup = BeautifulSoup(wpage, 'html.parser')\n if (soup.find_all('table', id='weatherHistory')!=[]):\n ss = soup.find_all('table', id='weatherHistory')[0]\n else :\n ss = soup.find_all('table',class_='t12')[0]\n month_sum=[]\n for n, i in enumerate(ss):\n if n != 0:\n ii = i.find_all('td')\n s = []\n for item in ii:\n s.append(re.sub('[\\t\\n\\r]','',item.string))\n month_sum.append(s)\n month_sum=month_sum[::-1]\n for m in month_sum:\n f.writelines(','.join(m)+'\\n')\n \n today=add_months(today,1)\n detail=today.strftime('%Y%m')\n print(detail)\n\n","sub_path":"scrach.py","file_name":"scrach.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"546651406","text":"\"\"\"For parsing input/output files\"\"\"\nimport re\nimport os\nfrom copy import deepcopy\nfrom io import StringIO, IOBase\nfrom warnings import warn\n\nimport numpy as np\n\nfrom AaronTools.atoms import Atom\nfrom AaronTools.const import ELEMENTS, PHYSICAL, UNIT\n\nread_types = [\"xyz\", \"log\", \"com\", \"sd\"]\nwrite_types = [\"xyz\", \"com\"]\nfile_type_err = \"File type not yet implemented: {}\"\nfloat_num = re.compile(\"[-+]?\\d+\\.?\\d*\")\nNORM_FINISH = \"Normal termination\"\nERRORS = {\n \"Convergence failure -- run terminated.\": \"CONV\",\n \"Inaccurate quadrature in CalDSu\": \"CONV_CDS\",\n \"Error termination request processed by link 9999\": \"CONV_LINK\",\n \"FormBX had a problem\": \"FBX\",\n \"NtrErr Called from FileIO\": \"CHK\",\n \"Wrong number of Negative eigenvalues\": \"EIGEN\",\n \"Erroneous write\": \"QUOTA\",\n \"Atoms too close\": \"CLASH\",\n \"The combination of multiplicity\": \"CHARGEMULT\",\n \"Bend failed for angle\": \"REDUND\",\n \"Unknown message\": \"UNKNOWN\",\n}\n\n\ndef is_alpha(test):\n rv = re.search(\"^[a-zA-Z]+$\", test)\n return bool(rv)\n\n\ndef is_int(test):\n rv = re.search(\"^[+-]?\\d+$\", test)\n return bool(rv)\n\n\ndef is_num(test):\n rv = re.search(\"^[+-]?\\d+\\.?\\d*\", test)\n return bool(rv)\n\n\ndef step2str(step):\n if int(step) == step:\n return str(int(step))\n else:\n return str(step).replace(\".\", \"-\")\n\n\ndef str2step(step_str):\n if \"-\" in step_str:\n return float(step_str.replace(\"-\", \".\"))\n else:\n return float(step_str)\n\n\nclass FileWriter:\n @classmethod\n def write_file(cls, geom, style=\"xyz\", append=False, outfile=None, *args, **kwargs):\n \"\"\"\n Writes file from geometry in the specified style\n\n :geom: the Geometry to use\n :style: the file type style to generate\n Currently supported options: xyz, com\n :append: for *.xyz, append geometry to the same file\n :options: for *.com files, the computational options\n \"\"\"\n if style.lower() not in write_types:\n raise NotImplementedError(file_type_err.format(style))\n\n if style.lower() == \"xyz\":\n cls.write_xyz(geom, append, outfile)\n elif style.lower() == \"com\":\n if \"theory\" in kwargs and \"step\" in kwargs:\n step = kwargs[\"step\"]\n theory = kwargs[\"theory\"]\n del kwargs[\"step\"]\n del kwargs[\"theory\"]\n cls.write_com(geom, step, theory, outfile, **kwargs)\n else:\n raise TypeError(\n \"when writing com files, **kwargs must include: theory=Aaron.Theory(), step=int/float()\"\n )\n\n @classmethod\n def write_xyz(cls, geom, append, outfile=None):\n mode = \"a\" if append else \"w\"\n fmt = \"{:3s} {: 10.5f} {: 10.5f} {: 10.5f}\\n\"\n s = \"%i\\n\" % len(geom.atoms)\n s += \"%s\\n\" % geom.comment\n for atom in geom.atoms:\n s += fmt.format(atom.element, *atom.coords)\n\n if outfile is None:\n #if no output file is specified, use the name of the geometry\n with open(geom.name + \".xyz\", mode) as f:\n f.write(s)\n elif outfile is False:\n #if no output file is desired, just return the file contents\n return s.strip()\n else:\n #write output to the requested destination\n with open(outfile, mode) as f:\n f.write(s)\n\n return\n\n @classmethod\n def write_com(cls, geom, step, theory, outfile=None, **kwargs):\n has_frozen = False\n fmt = \"{:<3s}\" + \" {:> 12.6f}\" * 3 + \"\\n\"\n for atom in geom.atoms:\n if atom.flag:\n fmt = \"{:<3s} {:> 2d}\" + \" {:> 12.6f}\" * 3 + \"\\n\"\n has_frozen = True\n break\n\n s = theory.make_header(geom, step, **kwargs)\n for atom in geom.atoms:\n if has_frozen:\n s += fmt.format(a.element, -a.flag, *a.coords)\n else:\n s += fmt.format(a.element, *a.coords)\n\n s += theory.make_footer(geom, step)\n\n if outfile is None:\n #if outfile is not specified, name file in Aaron format\n fname = \"{}.{}.com\".format(geom.name, step2str(step))\n with open(fname, \"w\") as f:\n f.write(s)\n elif outfile is False:\n return s\n else:\n with open(outfile, 'w') as f:\n f.write(s)\n\n return\n\n\nclass FileReader:\n \"\"\"\n Attributes:\n name ''\n file_type ''\n comment ''\n atoms [Atom]\n other {}\n \"\"\"\n\n def __init__(self, fname, get_all=False, just_geom=True):\n \"\"\"\n :fname: either a string specifying the file name of the file to read\n or a tuple of (str(name), str(file_type), str(content))\n :get_all: if true, optimization steps are also saved in\n self.other['all_geom']; otherwise only saves last geometry\n :just_geom: if true, does not store other information, such as\n frequencies, only what is needed to construct a Geometry() obj\n \"\"\"\n # Initialization\n self.name = \"\"\n self.file_type = \"\"\n self.comment = \"\"\n self.atoms = []\n self.other = {}\n self.content = None\n self.all_geom = None\n\n # get file name and extention\n if isinstance(fname, str):\n fname = fname.rsplit(\".\", 1)\n self.name = fname[0]\n self.file_type = fname[1].lower()\n elif isinstance(fname, (tuple, list)):\n self.name = fname[0]\n self.file_type = fname[1]\n self.content = fname[2]\n if self.file_type not in read_types:\n raise NotImplementedError(file_type_err.format(self.file_type))\n\n # Fill in attributes with geometry information\n if self.content is None:\n self.read_file(get_all, just_geom)\n elif isinstance(self.content, str):\n f = StringIO(self.content)\n elif isinstance(self.content, IOBase):\n f = self.content\n\n if self.content is not None:\n if self.file_type == \"log\":\n self.read_log(f, get_all, just_geom)\n elif self.file_type == \"sd\":\n self.read_sd(f)\n elif self.file_type == \"xyz\":\n self.read_xyz(f)\n elif self.file_type == \"com\":\n self.read_com(f)\n\n def read_file(self, get_all=False, just_geom=True):\n \"\"\"\n Reads geometry information from fname.\n Parameters:\n get_all If false (default), only keep the last geom\n If true, self is last geom, but return list\n of all others encountered\n \"\"\"\n if os.path.isfile(self.name):\n f = open(self.name)\n else:\n fname = '.'.join([self.name, self.file_type])\n if os.path.isfile(fname):\n f = open(fname)\n else:\n raise FileNotFoundError(\"Error while looking for %s: could not find %s or %s in %s\" % \\\n (self.name, fname, self.name, os.getcwd()))\n\n if self.file_type == \"xyz\":\n self.read_xyz(f, get_all)\n elif self.file_type == \"log\":\n self.read_log(f, get_all, just_geom)\n elif self.file_type == \"com\":\n self.read_com(f)\n elif self.file_type == \"sd\":\n self.read_sd(f)\n\n f.close()\n\n return\n\n def skip_lines(self, f, n):\n for i in range(n):\n f.readline()\n return\n\n def read_xyz(self, f, get_all=False):\n self.all_geom = []\n # number of atoms\n f.readline()\n # comment\n self.comment = f.readline().strip()\n # atom info\n for line in f:\n line = line.strip()\n if line == \"\":\n continue\n try:\n int(line)\n if get_all:\n self.all_geom += [\n (deepcopy(self.comment), deepcopy(self.atoms))\n ]\n self.comment = f.readline().strip()\n self.atoms = []\n except ValueError:\n line = line.split()\n self.atoms += [Atom(element=line[0], coords=line[1:4])]\n for i, a in enumerate(self.atoms):\n a.name = str(i + 1)\n if get_all:\n self.all_geom += [(deepcopy(self.comment), deepcopy(self.atoms))]\n\n def read_sd(self, f, get_all=False):\n self.all_geom = []\n lines = f.readlines()\n self.comment = lines[0]\n counts = lines[3].split()\n natoms = int(counts[0])\n nbonds = int(counts[1])\n self.atoms = []\n for line in lines[4:4+natoms]:\n atom_info = line.split()\n self.atoms += [Atom(element=atom_info[3], coords = atom_info[0:3])]\n\n for i, a in enumerate(self.atoms):\n a.name = str(i + 1)\n\n def read_log(self, f, get_all=False, just_geom=True):\n def get_atoms(f, n):\n rv = []\n self.skip_lines(f, 4)\n line = f.readline()\n n += 5\n while \"--\" not in line:\n line = line.strip()\n line = line.split()\n for l in line:\n try:\n float(l)\n except ValueError:\n msg = \"Error detected with log file on line {}\"\n raise IOError(msg.format(n))\n elem = ELEMENTS[int(line[1])]\n flag = not bool(line[2])\n rv += [Atom(element=elem, flag=flag, coords=line[3:])]\n line = f.readline()\n n += 1\n return rv, n\n\n self.all_geom = []\n line = f.readline()\n self.other[\"archive\"] = \"\"\n found_archive = False\n n = 1\n while line != \"\":\n # archive entry\n if line.strip().startswith(\"1\\\\1\\\\\"):\n found_archive = True\n line = \"@\" + line.strip()[4:]\n if found_archive and line.strip().endswith(\"@\"):\n self.other[\"archive\"] = self.other[\"archive\"][:-2] + \"\\\\\\\\\"\n found_archive = False\n elif found_archive:\n self.other[\"archive\"] += line.strip()\n\n # geometry\n if re.search(\"(Standard|Input) orientation:\", line):\n if get_all and len(self.atoms) > 0:\n self.all_geom += [deepcopy(self.atoms)]\n self.atoms, n = get_atoms(f, n)\n if just_geom:\n line = f.readline()\n n += 1\n continue\n if \"Symbolic Z-matrix:\" in line:\n line = f.readline()\n n += 1\n match = re.search(\n \"Charge\\s*=\\s*(\\d+)\\s*Multiplicity\\s*=\\s*(\\d+)\", line\n )\n if match is not None:\n self.other[\"charge\"] = int(match.group(1))\n self.other[\"multiplicity\"] = int(match.group(2))\n\n # status\n if NORM_FINISH in line:\n self.other[\"finished\"] = True\n if \"SCF Done\" in line:\n self.other[\"energy\"] = float(line.split()[4])\n if \"Molecular mass:\" in line:\n self.other[\"mass\"] = float(float_num.search(line).group(0))\n self.other[\"mass\"] *= UNIT.AMU_TO_KG\n\n # Frequencies\n if \"hpmodes\" in line:\n self.other[\"hpmodes\"] = True\n if \"Harmonic frequencies\" in line:\n freq_str = line\n while line != \"\\n\":\n line = f.readline()\n n += 1\n freq_str += line\n if \"hpmodes\" not in self.other:\n self.other[\"hpmodes\"] = False\n self.other[\"frequency\"] = Frequency(\n freq_str, self.other[\"hpmodes\"]\n )\n\n # Thermo\n if \"Temperature\" in line:\n self.other[\"temperature\"] = float(\n float_num.search(line).group(0)\n )\n if \"Rotational constants (GHZ):\" in line:\n rot = float_num.findall(line)\n rot = [\n float(r) * PHYSICAL.PLANK * (10 ** 9) / PHYSICAL.KB\n for r in rot\n ]\n self.other[\"rotational_temperature\"] = rot\n if \"Sum of electronic and zero-point Energies=\" in line:\n self.other[\"E_ZPVE\"] = float(float_num.search(line).group(0))\n if \"Sum of electronic and thermal Enthalpies=\" in line:\n self.other[\"enthalpy\"] = float(float_num.search(line).group(0))\n if \"Sum of electronic and thermal Free Energies=\" in line:\n self.other[\"free_energy\"] = float(\n float_num.search(line).group(0)\n )\n if \"Zero-point correction=\" in line:\n self.other[\"ZPVE\"] = float(float_num.search(line).group(0))\n if \"Rotational symmetry number\" in line:\n self.other[\"rotational_symmetry_number\"] = int(\n re.search(\"\\d+\", line).group(0)\n )\n\n # Gradient\n if re.search(\"Threshold\\s+Converged\", line) is not None:\n line = f.readline()\n n += 1\n grad = {}\n\n def add_grad(line, name, grad):\n line = line.split()\n grad[name] = {\n \"value\": line[2],\n \"threshold\": line[3],\n \"converged\": True if line[4] == \"YES\" else False,\n }\n return grad\n\n while line != \"\":\n if \"Predicted change in Energy\" in line:\n break\n if re.search(\"Maximum\\s+Force\", line) is not None:\n grad = add_grad(line, \"Max Force\", grad)\n if re.search(\"RMS\\s+Force\", line) is not None:\n grad = add_grad(line, \"RMS Force\", grad)\n if re.search(\"Maximum\\s+Displacement\", line) is not None:\n grad = add_grad(line, \"Max Disp\", grad)\n if re.search(\"RMS\\s+Displacement\", line) is not None:\n grad = add_grad(line, \"RMS Disp\", grad)\n line = f.readline()\n n += 1\n self.other[\"gradient\"] = grad\n\n # capture errors\n for err in ERRORS:\n if err in line:\n self.other[\"error\"] = ERRORS[err]\n self.other[\"error_msg\"] = line.strip()\n break\n else:\n self.other[\"error\"] = None\n\n line = f.readline()\n n += 1\n\n for i, a in enumerate(self.atoms):\n a.name = str(i + 1)\n\n if \"finished\" not in self.other:\n self.other[\"finished\"] = False\n if \"error\" not in self.other:\n self.other[\"error\"] = None\n if not self.other[\"finished\"] and not self.other[\"error\"]:\n self.other[\"error\"] = ERRORS[\"Unknown message\"]\n self.other[\"error_msg\"] = \"Unknown message\"\n return\n\n def read_com(self, f):\n found_atoms = False\n found_constraint = False\n atoms = []\n other = {}\n for line in f:\n # header\n if line.startswith(\"%\"):\n continue\n if line.startswith(\"#\"):\n method = re.search(\"^#([NnPpTt]\\s+?)(\\S+)|^#\\s*?(\\S+)\", line)\n #route can be #n functional/basis ...\n #or #functional/basis ...\n #or # functional/basis ...\n if method.group(3):\n other['method'] = method.group(3)\n else:\n other['method'] = method.group(2)\n if \"temperature=\" in line:\n other[\"temperature\"] = re.search(\n \"temperature=(\\d+\\.?\\d*)\", line\n ).group(1)\n if \"solvent=\" in line:\n other[\"solvent\"] = re.search(\n \"solvent=(\\S+)\\)\", line\n ).group(1)\n if \"scrf=\" in line:\n other[\"solvent_model\"] = re.search(\n \"scrf=\\((\\S+),\", line\n ).group(1)\n if \"EmpiricalDispersion=\" in line:\n other[\"emp_dispersion\"] = re.search(\n \"EmpiricalDispersion=(\\S+)\", line\n ).group(1)\n if \"int=(grid(\" in line:\n other[\"grid\"] = re.search(\"int=\\(grid(\\S+)\", line).group(1)\n for _ in range(4):\n line = f.readline()\n line = line.split()\n other[\"charge\"] = line[0]\n other[\"mult\"] = line[1]\n found_atoms = True\n continue\n # constraints\n if found_atoms and line.startswith(\"B\") and line.endswith(\"F\"):\n found_constraint = True\n if \"constraint\" not in other:\n other[\"constraint\"] = []\n other[\"constraint\"] += [float_num.findall(line)]\n continue\n # footer\n if found_constraint:\n if \"footer\" not in other:\n other[\"footer\"] = \"\"\n other[\"footer\"] += line\n continue\n # atom coords\n nums = float_num.findall(line)\n line = line.split()\n if len(line) == 5 and is_alpha(line[0]) and len(nums) == 4:\n if not is_int(line[1]):\n continue\n a = Atom(element=line[0], coords=nums[1:], flag=nums[0])\n atoms += [a]\n elif len(line) == 4 and is_alpha(line[0]) and len(nums) == 3:\n a = Atom(element=line[0], coords=nums)\n atoms += [a]\n else:\n continue\n self.atoms = atoms\n self.other = other\n return\n\n\nclass Frequency:\n \"\"\"\n ATTRIBUTES\n :data: Data - contains frequencies, intensities, and normal mode vectors\n :imaginary_frequencies: list(float)\n :real_frequencies: list(float)\n :lowest_frequency: float\n :by_frequency: dict keyed by frequency containing intensities and vectors\n {freq: {intensity: float, vector: np.array}}\n :is_TS: bool - true if len(imaginary_frequencies) == 1, else False\n \"\"\"\n\n class Data:\n \"\"\"\n ATTRIBUTES\n :frequency: float\n :intensity: float\n :vector: (2D array) normal mode vectors\n \"\"\"\n\n def __init__(self, frequency, intensity=None, vector=[], forcek=[]):\n self.frequency = frequency\n self.intensity = intensity\n self.vector = np.array(vector)\n self.forcek = np.array(forcek)\n\n def __init__(self, data, hpmodes=None):\n \"\"\"\n :data: should either be a str containing the lines of the output file\n with frequency information, or a list of Data objects\n :hpmodes: required when data is a string\n \"\"\"\n self.data = []\n self.imaginary_frequencies = None\n self.real_frequencies = None\n self.lowest_frequency = None\n self.by_frequency = {}\n self.is_TS = None\n\n if isinstance(data[0], Frequency.Data):\n self.data = data\n self.sort_frequencies()\n return\n else:\n if hpmodes is None:\n raise TypeError(\n \"hpmode argument required when data is a string\"\n )\n\n lines = data.split(\"\\n\")\n num_head = 0\n for line in lines:\n if \"Harmonic frequencies\" in line:\n num_head += 1\n if hpmodes and num_head != 2:\n warn(\"Log file damaged, cannot get frequencies\")\n return\n self.parse_lines(lines, hpmodes)\n self.sort_frequencies()\n return\n\n def parse_lines(self, lines, hpmodes):\n num_head = 0\n idx = -1\n modes = []\n for line in lines:\n if \"Harmonic frequencies\" in line:\n num_head += 1\n if hpmodes and num_head == 2:\n # if hpmodes, want just the first set of freqs\n break\n continue\n if \"Frequencies\" in line and ((hpmodes and \"---\" in line) or \\\n (\"--\" in line and not hpmodes)):\n for i in float_num.findall(line):\n self.data += [Frequency.Data(float(i))]\n modes += [[]]\n idx += 1\n continue\n\n if (\"Force constants\" in line and \"---\" in line and hpmodes) or \\\n (\"Frc consts\" in line and \"--\" in line and not hpmodes):\n force_constants = float_num.findall(line)\n for i in range(-len(force_constants), 0, 1):\n self.data[i].forcek = float(force_constants[i])\n continue\n\n if \"IR Inten\" in line and ((hpmodes and \"---\" in line) or \\\n (not hpmodes and \"--\" in line)):\n for i in float_num.findall(line):\n self.data[idx].intensity = float(i)\n continue\n\n if hpmodes:\n match = re.search(\n \"^\\s+\\d+\\s+\\d+\\s+\\d+(\\s+[+-]?\\d+\\.\\d+)+$\", line\n )\n if match is None:\n continue\n values = float_num.findall(line)\n coord = int(values[0]) - 1\n atom = int(values[1]) - 1\n moves = values[3:]\n for i, m in enumerate(moves):\n tmp = len(moves) - i\n mode = modes[-tmp]\n try:\n vector = mode[atom]\n except IndexError:\n vector = [0, 0, 0]\n modes[-tmp] += [[]]\n vector[coord] = m\n modes[-tmp][atom] = vector\n else:\n match = re.search(\"^\\s+\\d+\\s+\\d+(\\s+[+-]?\\d+\\.\\d+)+$\", line)\n if match is None:\n continue\n values = float_num.findall(line)\n atom = int(values[0]) - 1\n moves = np.array(values[2:], dtype=np.float)\n n_moves = len(moves) // 3\n for i in range(-n_moves, 0):\n modes[i].append(moves[3*n_moves+3*i:4*n_moves+3*i])\n\n for mode, data in zip(modes, self.data):\n data.vector = np.array(mode, dtype=np.float)\n return\n\n def sort_frequencies(self):\n self.imaginary_frequencies = []\n self.real_frequencies = []\n for i, data in enumerate(self.data):\n freq = data.frequency\n if freq < 0:\n self.imaginary_frequencies += [freq]\n elif freq > 0:\n self.real_frequencies += [freq]\n self.by_frequency[freq] = {\n \"intensity\": data.intensity,\n \"vector\": data.vector,\n }\n self.lowest_frequency = self.data[0].frequency\n self.is_TS = True if len(self.imaginary_frequencies) == 1 else False\n","sub_path":"fileIO.py","file_name":"fileIO.py","file_ext":"py","file_size_in_byte":23585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"375921798","text":"import os # isort:skip\nfrom decouple import config\nimport django_heroku\nimport dj_database_url\ngettext = lambda s: s\nDATA_DIR = os.path.dirname(os.path.dirname(__file__))\n\"\"\"\nDjango settings for mylaptop project.\n\nGenerated by 'django-admin startproject' using Django 1.11.25.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.11/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.11/ref/settings/\n\"\"\"\n\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/\n\n\nSECRET_KEY = config('SECRET_KEY')\nDEBUG = config('DEBUG', default=False, cast=bool)\n\nALLOWED_HOSTS = ['coollaptop.herokuapp.com', '127.0.0.1']\n\n\n# Application definition\n\n\nROOT_URLCONF = 'mylaptop.urls'\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.11/topics/i18n/\n\nLANGUAGE_CODE = 'en'\n\nTIME_ZONE = 'Europe/Kiev'\n\nUSE_I18N = False\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.11/howto/static-files/\n\nSTATIC_URL = '/static/'\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(DATA_DIR, 'media')\nSTATIC_ROOT = os.path.join(DATA_DIR, 'mylaptop', 'static')\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n)\nSITE_ID = 8\n\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'mylaptop', 'templates'),],\n 'OPTIONS': {\n 'context_processors': [\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.template.context_processors.media',\n 'django.template.context_processors.csrf',\n 'django.template.context_processors.tz',\n 'sekizai.context_processors.sekizai',\n 'django.template.context_processors.static',\n 'cms.context_processors.cms_settings'\n ],\n 'loaders': [\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n ],\n },\n },\n]\n\n\nMIDDLEWARE = [\n 'cms.middleware.utils.ApphookReloadMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'cms.middleware.user.CurrentUserMiddleware',\n 'cms.middleware.page.CurrentPageMiddleware',\n 'cms.middleware.toolbar.ToolbarMiddleware',\n 'cms.middleware.language.LanguageCookieMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django_otp.middleware.OTPMiddleware',\n\n]\n\nINSTALLED_APPS = [\n 'djangocms_admin_style',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.admin',\n 'django.contrib.sites',\n 'django.contrib.sitemaps',\n 'django.contrib.staticfiles',\n 'django.contrib.messages',\n 'cms',\n 'menus',\n 'sekizai',\n 'treebeard',\n 'djangocms_text_ckeditor',\n 'filer',\n 'easy_thumbnails',\n 'djangocms_column',\n 'djangocms_file',\n 'djangocms_link',\n 'djangocms_picture',\n 'djangocms_style',\n 'djangocms_snippet',\n 'djangocms_googlemap',\n 'djangocms_video',\n\n 'mylaptop',\n 'accounts',\n 'egs',\n 'questions',\n 'django_otp',\n 'django_otp.plugins.otp_static',\n 'django_otp.plugins.otp_totp',\n 'two_factor',\n\n]\n\n\nLANGUAGES = (\n # Customize this\n ('en', gettext('en')),\n)\nCMS_LANGUAGES = {\n # Customize this\n 1: [\n {\n 'code': 'en',\n 'name': gettext('en'),\n 'redirect_on_fallback': True,\n 'public': True,\n 'hide_untranslated': False,\n },\n ],\n 'default': {\n 'redirect_on_fallback': True,\n 'public': True,\n 'hide_untranslated': False,\n },\n}\n\nCMS_TEMPLATES = (\n # Customize this\n ('fullwidth.html', 'Fullwidth'),\n ('sidebar_left.html', 'Sidebar Left'),\n ('sidebar_right.html', 'Sidebar Right'),\n ('homepage.html', 'home'),\n\n)\n\nCMS_PERMISSION = True\n\nCMS_PLACEHOLDER_CONF = {}\n\nCMS_TOOLBAR_ANONYMOUS_ON = False\n\nDATABASES = {\n 'default': {\n 'CONN_MAX_AGE': 0,\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'HOST': 'localhost',\n 'NAME': 'Laptop',\n 'PASSWORD': 'mortal99',\n 'PORT': '5432',\n 'USER': 'postgres'\n }\n}\n\ndb_from_env = dj_database_url.config()\nDATABASES['default'].update(db_from_env)\n\nMIGRATION_MODULES = {\n \n}\n\nTHUMBNAIL_PROCESSORS = (\n 'easy_thumbnails.processors.colorspace',\n 'easy_thumbnails.processors.autocrop',\n 'filer.thumbnail_processors.scale_and_crop_with_subject_location',\n 'easy_thumbnails.processors.filters'\n)\n\nEMAIL_USE_TLS = True\nEMAIL_USE_SSL = False\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_USER = 'nineball.hustler.nine@gmail.com'\nDEFAULT_FROM_EMAIL = EMAIL_HOST_USER\nEMAIL_HOST_PASSWORD = 'mortal99kombat'\nEMAIL_PORT = 587\n\n\nLOGIN_URL = 'two_factor:login'\n\n\nSECURE_SSL_REDIRECT = True\nSESSION_COOKIE_SECURE = True\nCSRF_COOKIE_SECURE = True\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n","sub_path":"mylaptop/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"277183242","text":"\nimport time\nimport sys\n\nsys.path.append(\"..\")\nimport database.db_operator as db_operator\nimport log.custom_logger as custom_logger\n\nclass CommonDBOperation:\n # 通用,常用的数据库操作\n\n def __init__(self):\n pass\n\n def get_the_last_trading_date(self,day):\n # 获取传入日期参数最近的交易日期, 即上一个交易日\n # day: 交易日期,如 2021-06-09\n # return: 如果存在最近的交易日期,则返回日期\n # 如果不存在,则返回 0000-00-00\n\n # 查询SQL\n selecting_sql = \"SELECT trading_date FROM trading_days WHERE trading_date < '%s' ORDER BY \" \\\n \"ABS(DATEDIFF(trading_date, '%s')) ASC LIMIT 1\" % (day,day)\n\n # 查询\n selecting_result = db_operator.DBOperator().select_one(\"financial_data\", selecting_sql)\n\n if selecting_result is not None:\n return selecting_result[\"trading_date\"]\n else:\n # 日志记录\n log_msg = \"无法获取 \"+day+\" 最近的交易日期\"\n custom_logger.CustomLogger().log_writter(log_msg, 'error')\n return \"0000-00-00\"\n\n\n\n\n\n\n\nif __name__ == '__main__':\n go = CommonDBOperation()\n last_trade_day = go.get_the_last_trading_date(\"2001-05-06\")\n print(last_trade_day)","sub_path":"data_miner/common_db_operation.py","file_name":"common_db_operation.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"557199454","text":"import discord\nfrom discord.ext import commands\nimport random\nclass BAfun():\n\n def __init__(ctx, bot):\n ctx.bot = bot\n ctx.toggle = False\n ctx.nsword = ctx.nlove = ctx.nsquat = ctx.npizza = ctx.nbribe = ctx.ndad = ctx.ncalc \\\n = ctx.nbutt = ctx.ncom = ctx.nflirt = ctx.nup = 0\n \n@commands.command(name=\"8ball\")\nasync def _ball(self, ctx, *, question):\n ': Ask me a question'\n question = question\n answers = random.randint(1, 20)\n\n if question == \"\":\n return\n\n elif answers == 1:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` It is certain```\"\"\")\n\n elif answers == 2:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` It is decidedly so```\"\"\")\n\n elif answers == 3:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Without a doubt```\"\"\")\n\n elif answers == 4:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Yes definitely```\"\"\")\n\n elif answers == 5:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` You may rely on it```\"\"\")\n\n elif answers == 6:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` As i see it, yes```\"\"\")\n\n elif answers == 7:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Most likely```\"\"\")\n\n elif answers == 8:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Outlook good```\"\"\")\n\n elif answers == 9:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Yes```\"\"\")\n\n elif answers == 10:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Signs point to yes```\"\"\")\n\n elif answers == 11:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Reply hazy try again```\"\"\")\n\n elif answers == 12:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Ask again later```\"\"\")\n\n elif answers == 13:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Better not to tell you now```\"\"\")\n\n elif answers == 14:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Cannot predict now```\"\"\")\n\n elif answers == 15:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Concentrate and ask again```\"\"\")\n\n elif answers == 16:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Don't count on it```\"\"\")\n\n elif answers == 17:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` My reply is no```\"\"\")\n\n elif answers == 18:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` My sources say no```\"\"\")\n\n elif answers == 19:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Outlook not so good```\"\"\")\n\n elif answers == 20:\n await ctx.send(f\"\"\"\\U0001f3b1 Question by {ctx.author.name}: {question}``` Very doubtful```\"\"\")\n \n@commands.command()\nasync def sword(ctx, *, user: discord.Member):\n \"\"\"Sword Duel!\"\"\"\n author = ctx.message.author\n if user.id == ctx.bot.user.id:\n await ctx.send(\"I'm not the fighting kind\")\n else:\n await ctx.send(author.mention + \" and \" + user.mention + \" dueled for \" + str(randint(2, 120)) +\n \" gruesome hours! It was a long, heated battle, but \" +\n choice([author.mention, user.mention]) + \" came out victorious!\")\n ctx.counter(n)\n\n@commands.command()\nasync def love(ctx, user: discord.Member):\n \"\"\"Found your one true love?\"\"\"\n author = ctx.message.author\n if user.id == ctx.bot.user.id:\n await ctx.send(\"I am not capable of loving like you can. I'm sorry.\" )\n else:\n await ctx.send(author.mention + \" is capable of loving \" + user.mention + \" a whopping \" +\n str(randint(0, 100)) + \"%!\")\n ctx.counter(n)\n\n@commands.command()\nasync def squat(ctx):\n \"\"\"How is your workout going?\"\"\"\n author = ctx.message.author\n await ctx.send(author.mention + \" puts on their game face and does \" + str(randint(2, 1000)) +\n \" squats in \" + str(randint(4, 90)) + \" minutes. Wurk it!\")\n ctx.counter(n)\n\n@commands.command()\nasync def pizza(ctx):\n \"\"\"How many slices of pizza have you eaten today?\"\"\"\n author = ctx.message.author\n await ctx.send(author.mention + \" has eaten \" + str(randint(2, 120)) + \" slices of pizza today.\")\n ctx.counter(n)\n\n@commands.command()\nasync def bribe(ctx):\n \"\"\"Find out who is paying under the table\"\"\"\n author = ctx.message.author\n await ctx.send(author.mention + \" has bribed \" + ctx.bot.user.mention + \" with \" +\n str(randint(10, 10000)) + \" dollars!\")\n ctx.counter(n)\n\n@commands.command()\nasync def daddy(ctx):\n \"\"\"Pass the salt\"\"\"\n author = ctx.message.author\n await ctx.send(\"I'm kink shaming you, \" + author.mention)\n ctx.counter(n)\n\n@commands.command()\nasync def calculated(ctx):\n \"\"\"That was 100% calculated!\"\"\"\n await ctx.send(\"That was \" + str(randint(0, 100)) + \"% calculated!\")\n ctx.counter(n)\n\n@commands.command()\nasync def butts(ctx):\n \"\"\"butts\"\"\"\n await ctx.send(\"ლ(́◉◞౪◟◉‵ლ)\")\n ctx.counter(n)\n\n@commands.command()\nasync def _commands(ctx):\n \"\"\"Command the bot\"\"\"\n await ctx.send(\"Don't tell me what to do.\")\n ctx.counter(n)\n\n@commands.command()\nasync def flirt(ctx):\n \"\"\"Slide into DMs\"\"\"\n await ctx.send(\" ;)) ))) hey b a b e ; ; ;))) ) ;)\")\n ctx.counter(n)\n\n@commands.command()\nasync def updog(ctx):\n \"\"\"This is updog\"\"\"\n await ctx.send(\"What's updog?\")\n ctx.counter(n)\n@commands.command(pass_context=True)\nasync def poke(ctx, member: discord.Member):\n \"\"\"poke someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n poke = \"**{0} poked {1}!**\"\n\n choices = ['https://pa1.narvii.com/6021/b50b8078fa1d8e8f6d2ebfb085f106c642141723_hq.gif',\n 'https://media1.tenor.com/images/8fe23ec8e2c5e44964e5c11983ff6f41/tenor.gif',\n 'https://media.giphy.com/media/WvVzZ9mCyMjsc/giphy.gif',\n 'https://media.giphy.com/media/pWd3gD577gOqs/giphy.gif',\n 'http://gifimage.net/wp-content/uploads/2017/09/anime-poke-gif-12.gif', 'https://i.gifer.com/S00v.gif',\n 'https://i.imgur.com/1NMqz0i.gif']\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=poke.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n\n@commands.command(pass_context=True)\nasync def hug(ctx, member: discord.Member):\n \"\"\"hug someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n hug = \"**{0}Aww, I see you are lonely, take a hug <3{1}!**\"\n\n choices = ['https://cdn.discordapp.com/attachments/447337220895145998/466226631778893824/hug-rk_6GyncG.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466227315110576129/hug-ry6o__7D-.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466227511165190175/hug-Bk5haAocG.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466228974326906891/hug-BkBs2uk_b.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466229286966394881/hug-HkfgF_QvW.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466230001872666635/hug-BkZngAYtb.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466230123209687040/hug-Bk5T2_1Ob.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466230234795212802/hug-Hy4hxRKtW.gif']\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=hug.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n\n@commands.command(pass_context=True)\nasync def slap(ctx, member: discord.Member):\n \"\"\"Slap someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n slap = \"**{0}Hmm, why do you want this?Slaps.{1}!**\"\n\n choices = ['https://cdn.discordapp.com/attachments/447337220895145998/466229677300908042/slap-rJYqQyKv-.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466229535059345408/slap-r1PXzRYtZ.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466229453236731904/slap-SkSCyl5yz.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466231429337055242/slap-B1-nQyFDb.gif',\n 'https://cdn.discordapp.com/attachments/447337220895145998/466231614352130048/slap-HkskD56OG.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466231875120267284/slap-By2iXyFw-.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466232154112917504/slap-SkKn-xc1f.gif'\n 'https://cdn.discordapp.com/attachments/447337220895145998/466232493889290241/slap-rJrnXJYPb.gif']\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=slap.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n\n\n@commands.command()\nasync def dog(ctx):\n ''''sends cute dog pics'''\n r = requests.get(\"https://dog.ceo/api/breeds/image/random\").json()\n embed=discord.Embed()\n embed.set_image(url=r[\"message\"])\n await ctx.send(embed=embed)\n\n\n\n@commands.command(pass_context=True, no_pm=True)\nasync def insult(ctx, user : discord.Member=None):\n \"\"\"Insult the user\"\"\"\n\n msg =\" How original. No one else had thought of trying to get the bot to insult itself. I applaud your creativity. Yawn. Perhaps this is why you don't have friends. You don't add anything new to any conversation. You are more of a bot than me, predictable answers, and absolutely dull to have an actual conversation with.\"\n if user != None:\n if user.id == ctx.bot.user.id:\n user = ctx.message.author\n await ctx.send(user.mention + msg)\n else:\n await ctx.send(user.mention + msg + random.choice(msg))\n else:\n await ctx.send(ctx.message.author.mention + msg + random.choice(msg))\n\n@commands.command(pass_context=True)\nasync def bite(ctx, member: discord.Member):\n \"\"\"bites someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n bite = \"**{0}bites you.{1}!**\"\n\n choices = ['https://cdn.discordapp.com/attachments/456701536912015361/466571069973856256/bite-HkutgeXob.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466571762339938304/bite-ry00lxmob.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466572007258193920/bite-H1_Jbemjb.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466572188372434964/bite-H1hige7sZ.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466572377233293322/bite-Hk1sxlQjZ.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466572552739880961/bite-rkakblmiZ.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466572804385669120/bite-BJXRmfr6-.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466573024078987284/bite-ry3pQGraW.gif']\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=bite.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n\n@commands.command(pass_context=True)\nasync def cuddle(ctx, member: discord.Member):\n \"\"\"cuddle someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n cuddle = \"**cuddles you.{1}!**\"\n\n choices = ['https://cdn.discordapp.com/attachments/456701536912015361/466573538841591809/cuddle-SJn18IXP-.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466573996201082900/cuddle-r1s9RqB7G.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466574139805794306/cuddle-SJceIU7wZ.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466574279127859200/cuddle-r1XEOymib.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466574467070427156/cuddle-S1T91Att-.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466574644577697792/cuddle-BkZCSI7Pb.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466574850375548939/cuddle-Byd1IUmP-.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466575399862665216/cuddle-BkN0rIQDZ.gif']\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=cuddle.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n\n\n@commands.command(pass_context=True)\nasync def pat(ctx, member: discord.Member):\n \"\"\"pat someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n pat = \"**you have been patted .{1}!**\"\n\n choices = ['https://cdn.discordapp.com/attachments/456701536912015361/466577618771378176/pat-rktsca40-.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466577986209185812/pat-rkZbJAYKW.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466578464619626496/pat-SJva1kFv-.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466578677090484224/pat-BkJBQlckz.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466578825468182538/pat-H1s5hx0Bf.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466579159435706380/pat-rJMskkFvb.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466579338490544128/pat-rkBZkRttW.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466579500117917727/pat-Sk2FyQHpZ.gif']\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=pat.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n\n@commands.command(pass_context=True)\nasync def kiss(ctx, member: discord.Member):\n \"\"\"kiss someone!\"\"\"\n author = ctx.message.author.mention\n mention = member.mention\n\n kiss = \"** kissed you.{1}!**\"\n\n choices = ['https://cdn.discordapp.com/attachments/456701536912015361/466579840070582284/kiss-B1MJ2aODb.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466580423116324874/kiss-Hkt-nTOwW.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466581686591946763/kiss-r1VWnTuPW.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466582897755947017/kiss-BkUJNec1M.gif',\n 'https://cdn.discordapp.com/attachments/456701536912015361/466583102047780914/kiss-Sk1k3TdPW.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466583257341755392/kiss-BJv0o6uDZ.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466583404222087168/kiss-S1PCJWASf.gif'\n 'https://cdn.discordapp.com/attachments/456701536912015361/466583780736499712/kiss-SJ3dXCKtW.gif']\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=kiss.format(author, mention), colour=discord.Colour(0xba4b5b))\n embed.set_image(url=image)\n\n await ctx.send(embed=embed)\n@commands.command(pass_context=True)\nasync def pepe(ctx, user: discord.Member = None):\n \"\"\"kiss someone!\"\"\"\n user = user or ctx.message.author\n\n pepe = \"** kissed you.{1}!**\"\n\n choices = [\"http://i.imgur.com/vpIyEue.png\",\n \"http://i.imgur.com/0koMC0v.jpg\",\n \"http://i.imgur.com/9Q6KMZa.png\",\n \"http://i.imgur.com/54xy6jr.png\",\n \"http://i.imgur.com/QvCngiJ.jpg\",\n \"http://i.imgur.com/ftWgrOE.jpg\",\n \"http://i.imgur.com/rhDSqRv.jpg\",\n \"http://i.imgur.com/89NZ3zM.jpg\",\n \"http://i.imgur.com/I4cIH5b.png\",\n \"http://i.imgur.com/GIFc4uX.png\",\n \"http://i.imgur.com/bgShJpZ.png\",\n \"http://i.imgur.com/jpfPLyn.png\",\n \"http://i.imgur.com/pZeYoej.png\",\n \"http://i.imgur.com/M8V9WKB.jpg\",\n \"http://i.imgur.com/ZBzHxNk.jpg\",\n \"http://i.imgur.com/xTyJ6xa.png\",\n \"http://i.imgur.com/TOozxRQ.png\",\n \"http://i.imgur.com/Eli5HdZ.png\",\n \"http://i.imgur.com/pkikqcA.jpg\",\n \"http://i.imgur.com/gMF8eo5.png\",\n \"http://i.imgur.com/HYh8BUm.jpg\",\n \"http://i.imgur.com/ZGVrRye.jpg\",\n \"http://i.imgur.com/Au4F1px.jpg\",\n \"http://i.imgur.com/gh36k9y.jpg\",\n \"http://i.imgur.com/MHDoRuN.png\",\n \"http://i.imgur.com/V3MJfyK.png\",\n \"http://i.imgur.com/QGGTipc.jpg\",\n \"http://i.imgur.com/PRFrTgz.png\",\n \"http://i.imgur.com/9UBJrwM.jpg\",\n \"http://i.imgur.com/WQY9Vhb.jpg\",\n \"http://i.imgur.com/sIbQdou.jpg\",\n \"http://i.imgur.com/LlUMg00.jpg\",\n \"http://i.imgur.com/MmijlWa.png\",\n \"http://i.imgur.com/i0CrtrX.png\",\n \"http://i.imgur.com/Dfpudwp.jpg\",\n \"http://i.imgur.com/hhg0wVF.gif\",\n \"http://i.imgur.com/7VDiIHN.jpg\",\n \"http://i.imgur.com/nxvXpNV.jpg\",\n \"http://i.imgur.com/DZYEjrW.gif\",\n \"http://i.imgur.com/mnyQ0Rh.jpg\",\n \"http://i.imgur.com/aHawbbs.jpg\",\n \"http://i.imgur.com/g8cCHV7.jpg\",\n \"http://i.imgur.com/E2cMU7Y.jpg\",\n \"http://i.imgur.com/PkmcgGF.jpg\",\n \"http://i.imgur.com/7qLQ1xl.jpg\",\n \"http://i.imgur.com/7qLQ1xl.jpg\",\n \"http://i.imgur.com/arSsPwf.png\",\n \"http://i.imgur.com/xcYh4iC.png\",\n \"http://i.imgur.com/9692WND.jpg\",\n \"http://i.imgur.com/diAK5Nu.jpg\",\n \"http://i.imgur.com/zDs0tRW.jpg\",\n \"http://i.imgur.com/PEM87nV.jpg\",\n \"http://i.imgur.com/zlCzlND.jpg\",\n \"http://i.imgur.com/n0OHxDl.jpg\",\n \"http://i.imgur.com/TQRf1WH.png\",\n \"http://i.imgur.com/zi9ad15.jpg\",\n \"http://i.imgur.com/b8A6Qke.jpg\",\n \"http://i.imgur.com/YuLapEu.png\",\n \"http://i.imgur.com/fWFXkY1.jpg\",\n \"http://i.imgur.com/i5vNvWU.png\",\n \"http://i.imgur.com/oXwUwtJ.jpg\",\n \"http://i.imgur.com/hadm4jV.jpg\",\n \"http://i.imgur.com/gbCvkqo.png\",\n \"http://i.imgur.com/wDiiWBG.jpg\",\n \"http://i.imgur.com/Mvghx4V.jpg\",\n \"http://i.imgur.com/SnTAjiJ.jpg\",\n \"http://i.imgur.com/QvMYBnu.png\",\n \"http://i.imgur.com/WkzPvfB.jpg\",\n \"http://i.imgur.com/PfAm4ot.png\",\n \"http://i.imgur.com/SIk4a45.png\",\n \"http://i.imgur.com/aISFmQq.jpg\",\n \"http://i.imgur.com/sMQkToE.png\",\n \"http://i.imgur.com/7i3cBrP.png\",\n \"http://i.imgur.com/1oMSz6e.png\",\n \"http://i.imgur.com/nVCRnRv.png\",\n \"http://i.imgur.com/FzWmxmi.jpg\",\n \"http://i.imgur.com/rpUI20F.jpg\",\n \"http://i.imgur.com/FDmnFDZ.jpg\",\n \"http://i.imgur.com/40Z1Yyg.jpg\",\n \"http://i.imgur.com/osy5Nu4.png\",\n \"http://i.imgur.com/4w81MSS.jpg\",\n \"http://i.imgur.com/qRXQFYa.png\",\n \"http://i.imgur.com/A1af62j.jpg\",\n \"http://i.imgur.com/wOc6fUe.jpg\",\n \"http://i.imgur.com/Z6ILiJ4.jpg\",\n \"http://i.imgur.com/537UpEJ.jpg\",\n \"http://i.imgur.com/HDc6kko.png\",\n \"http://i.imgur.com/oyLpuXq.jpg\",\n \"http://i.imgur.com/iCmGtJS.jpg\",\n \"http://i.imgur.com/MjpnlQm.png\",\n \"http://i.imgur.com/c6MWRQ9.jpg\"]\n\n\n image = random.choice(choices)\n\n embed = discord.Embed(description=f\"\"\"{user.name}\"\"\", colour=discord.Colour(0xba4b5b))\n embed.add_field(name=' Random', value=f''' ~~pepe~~''', inline=False)\n embed.set_image(url=image)\n\n\n await ctx.send(embed=embed)\n\n\n\n@commands.cooldown(1,120 , commands.BucketType.user)\n@commands.command(aliases= [\"s\"])\nasync def spawn(ctx, user: discord.Member = None): \n user = user or ctx.message.author\n \n\n\n spawn = \"** A wild .{1}!**\"\n\n \n choices = [\"http://www.pokestadium.com/sprites/xy/shiny/xerneas.gif\",\n \"http://www.pokestadium.com/sprites/xy/xerneas-active.gif\",\n \"http://www.pokestadium.com/sprites/xy/zekrom.gif\",\n \"http://www.pokestadium.com/sprites/xy/charizard.gif\",\n \"http://www.pokestadium.com/sprites/xy/shiny/charizard.gif\",\n \"http://www.pokestadium.com/sprites/xy/yveltal.gif\",\n \"http://www.pokestadium.com/sprites/xy/shiny/yveltal.gif\",\n \"http://www.pokestadium.com/sprites/xy/raikou.gif\",\n \"http://www.pokestadium.com/sprites/xy/shiny/raikou.gif\",\n \"https://cdn.discordapp.com/attachments/386324037552308224/503050326627319809/PokecordSpawn.jpg\",\n \"https://cdn.discordapp.com/attachments/386324037552308224/503050526603214848/PokecordSpawn.jpg\",\n \"https://cdn.discordapp.com/attachments/386324037552308224/503050157286227968/PokecordSpawn.jpg\",\n \"https://cdn.discordapp.com/attachments/482056981931098112/502861665180581908/PokecordSpawn.jpg\",\n \"https://img.nijimen.net/uploads/topic/wide_image/18879/78ea52a0-5e3c-48ee-bbe4-8ff6fe38764b.jpg\"\n \"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRE1NX0EsJ0SUcP1LEdglNTN12UIatAoXfA1rxuz1fkL8Q8vWL9zQ\",\n \"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTOENKjnLEl2H8OdMbOaVqJT0QWr0toBNsWfKa3wQWh_mj827UsLg\",\n \"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQo8_G9cOLmqWNGNFh1BxSx_bkpNOxIW7sv2bqlClQgI_u9TiVx\"]\n \n image = random.choice(choices)\n\n embed = discord.Embed(description=f\"\"\"{user.name}\"\"\", colour=discord.Colour(0xba4b5b))\n embed.add_field(name=' A wild pokémon has appeared!', value=f''' ~~Guess the pokemon~~''', inline=False)\n embed.set_image(url=image)\n\n\n\n await ctx.send(embed=embed)\n\n\n@commands.command()\nasync def cat(ctx):\n \"\"\"Get a random cat image!\n\n **Usage:** `g_dog`\n\n **Permission:** User\"\"\"\n isVideo = True\n while isVideo:\n r = requests.get('https://random.dog/woof.json')\n js = r.json()\n if js['url'].endswith('.mp4'):\n pass\n else:\n isVideo = False\n colours = [0x1abc9c, 0x11806a, 0x2ecc71, 0x1f8b4c, 0x3498db, 0x206694, 0x9b59b6, 0x71368a, 0xe91e63, 0xad1457, 0xf1c40f, 0xc27c0e, 0xa84300, 0xe74c3c, 0x992d22, 0x95a5a6, 0x607d8b, 0x979c9f, 0x546e7a]\n col = int(random.random() * len(colours))\n content = [\":dog: Don't be sad! This doggy wants to play with you!\", \"You seem lonely, {0.mention}. Here, have a dog. They're not as nice as cats, but enjoy!\".format(ctx.message.author), \"Weuf, woof, woooooooooof. Woof you.\", \"Pupper!\", \"Meow... wait wrong animal.\"]\n con = int(random.random() * len(content))\n em = discord.Embed(color=colours[col])\n em.set_image(url=js['url'])\n await ctx.send(content=content[con], embed=em)\n\n@commands.command()\nasync def neko(ctx):\n ''''sends cute dog pics'''\n r = requests.get(\"https://nekos.life/api/neko\").json()\n\n colours = [0x1abc9c, 0x11806a, 0x2ecc71, 0x1f8b4c, 0x3498db, 0x206694, 0x9b59b6, 0x71368a, 0xe91e63, 0xad1457, 0xf1c40f, 0xc27c0e, 0xa84300, 0xe74c3c, 0x992d22, 0x95a5a6, 0x607d8b, 0x979c9f, 0x546e7a]\n col = int(random.random() * len(colours))\n content = [\":neko: Don't be sad! This neko wants to play with you!\", \"You seem lonely, {0.mention}. Here, have a neko. They're not as nice , but enjoy!\".format(ctx.message.author), \"Weuf, woof, woooooooooof. Woof you.\", \"Pupper!\", \"Meow... wait its neko.\"]\n con = int(random.random() * len(content))\n embed=discord.Embed()\n embed.set_image(url=r[\"neko\"])\n await ctx.send(content=content[con],embed=embed)\n\n\n@commands.command(pass_context=True)\nasync def rps(ctx, choice):\n \"\"\"\"\"\"\n choices = [\"rock\", \"paper\", \"scissors\"]\n await ctx.send(\"You chose {} | CPU chose {}\".format(choice, random.choice(choices)))\n\ndef setup(bot):\n bot.add_cog(BAfun(bot))","sub_path":"fun.py","file_name":"fun.py","file_ext":"py","file_size_in_byte":25221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"10581818","text":"\"\"\"\nWCH5Dataset update to apply normalization on the fly to the test dataset\n\"\"\"\n\n# PyTorch imports\nfrom torch.utils.data import Dataset\nimport h5py\n\nimport numpy as np\n\n# WatChMaL imports\nimport preprocessing.normalize_funcs as norm_funcs\n\nclass WCH5DatasetTest(Dataset):\n \"\"\"\n Dataset storing image-like data from Water Cherenkov detector\n memory-maps the detector data from the hdf5 file\n The detector data must be uncompresses and unchunked\n labels are loaded into memory outright\n No other data is currently loaded\n \"\"\"\n\n def __init__(self, test_dset_path, norm_params_path, chrg_norm=\"identity\", time_norm=\"identity\", shuffle=1, test_subset=None, seed=42):\n \n f = h5py.File(test_dset_path, \"r\")\n \n hdf5_event_data = f[\"event_data\"]\n hdf5_labels = f[\"labels\"]\n hdf5_energies = f[\"energies\"]\n hdf5_positions = f[\"positions\"]\n hdf5_angles = f[\"angles\"]\n \n assert hdf5_event_data.shape[0] == hdf5_labels.shape[0]\n \n assert hasattr(norm_funcs, chrg_norm) and hasattr(norm_funcs, time_norm), \"Functions \"+ chrg_norm + \" and/or \" + time_norm + \" are not implemented in normalize_funcs.py, aborting.\"\n \n # Create a memory map for event_data - loads event data into memory only on __getitem__()\n self.event_data = np.memmap(test_dset_path, mode=\"r\", shape=hdf5_event_data.shape,\n offset=hdf5_event_data.id.get_offset(), dtype=hdf5_event_data.dtype)\n \n # Load the contents which could fit easily into memory\n self.labels = np.array(hdf5_labels)\n self.energies = np.array(hdf5_energies)\n self.positions = np.array(hdf5_positions)\n self.angles = np.array(hdf5_angles)\n \n # Load the normalization parameters used by normalize_hdf5 methods\n norm_params = np.load(norm_params_path, allow_pickle=True)\n self.chrg_acc = norm_params[\"c_acc\"]\n self.time_acc = norm_params[\"t_acc\"]\n \n self.chrg_func = getattr(norm_funcs, chrg_norm)\n self.time_func = getattr(norm_funcs, time_norm)\n \n # Set the total size of the trainval dataset to use\n self.reduced_size = test_subset\n \n self.test_indices = np.arange(len(self))\n if self.reduced_size is not None:\n assert len(self.test_indices)>=self.reduced_size\n self.test_indices = np.random.choice(self.labels.shape[0], self.reduced_size)\n \n # Seed the pseudo random number generator\n if seed is not None:\n np.random.seed(seed)\n \n # Shuffle the indices\n if shuffle:\n np.random.shuffle(self.test_indices)\n \n def __getitem__(self, index):\n return np.array(self.event_data[index,:]), np.concatenate([np.squeeze(self.chrg_func(np.expand_dims(self.event_data[index, :, :, :19], axis=0), self.chrg_acc, apply=True)), np.squeeze(self.time_func(np.expand_dims(self.event_data[index, :, :, 19:], axis=0), self.time_acc, apply=True))], axis=2), self.labels[index], self.energies[index], self.angles[index], index, self.positions[index]\n \n def __len__(self):\n if self.reduced_size is None:\n return self.labels.shape[0]\n else:\n return self.reduced_size","sub_path":"io_utils/data_handling_test.py","file_name":"data_handling_test.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"417744585","text":"from pymongo import MongoClient\nfrom modules.appleId_check import AppleId\nfrom config import Config\n\n\nclass ProfileExistence:\n\n def __init__(self):\n\n self.client = MongoClient(Config.MONGO_URI)\n db = self.client.Apple_db\n self.collection = db.account\n self.dict = {}\n\n def db_check(self, id):\n\n # if database consists the profile\n if self.collection.find_one({'profile_id': id}):\n\n for doc in self.collection.find({'profile_id': id}):\n # print(doc)\n self.dict['profileExists'] = doc['profileExists']\n self.dict['profile_id'] = doc['profile_id']\n\n return self.dict\n\n # when profile isn't in database\n else:\n obj = AppleId()\n data_from_apple = obj.id_check(id)\n # print(data_from_fb)\n self.db_loader(data_from_apple)\n return data_from_apple\n\n def db_loader(self, data):\n\n # print(data)\n if data['profileExists'] is False:\n pass\n else:\n\n d = {\"profileExists\": data['profileExists'],\n \"profile_id\": data['profile_id']\n }\n self.collection.insert_one(d)\n\n # close db connection\n self.client.close()\n\n\nif __name__ == '__main__':\n obj = ProfileExistence()\n print(obj.db_check(\"jaqsoms43@gmail.com\"))\n\n","sub_path":"apple-api/modules/appleId_check_db.py","file_name":"appleId_check_db.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"100845173","text":"#!/usr/bin/python\n#\n# Derived from download_and_preprocess_flowers.sh\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#\n# ==============================================================================\n\"\"\"\n Script to download and preprocess the flowers data set. This data set\n provides a demonstration for how to perform fine-tuning (i.e. tranfer\n learning) from one model to a new data set.\n\n This script provides a demonstration for how to prepare an arbitrary\n data set for training an Inception v3 model.\n\n We demonstrate this with the flowers data set which consists of images\n of labeled flower images from 5 classes:\n\n daisy, dandelion, roses, sunflowers, tulips\n\n The final output of this script are sharded TFRecord files containing\n serialized Example protocol buffers. See build_image_data.py for\n details of how the Example protocol buffer contains image data.\n\n usage:\n ./download_and_preprocess_flowers.py [data-dir]\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom subprocess import call\nimport os\nimport os.path\nimport shutil\nimport sys\nimport random\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print('Usage: download_and_preprocess_flowers.sh [data dir]\\n')\n sys.exit(-1)\ndata_dir = os.path.realpath(sys.argv[1])\n\n# Create the output and temporary directories.\nwork_dir = __file__ + \".runfiles/inception/inception\"\nscratch_dir = data_dir + '/raw-data/'\ntry:\n os.makedirs(scratch_dir);\nexcept OSError as e:\n print('Mkdir error: \"%s\" %s' % (scratch_dir,os.strerror(e.errno)))\n\n# Download the flowers data.\ndata_url = 'http://download.tensorflow.org/example_images/flower_photos.tgz'\nbase_dir = os.path.dirname(os.path.realpath(__file__))\ncurrent_dir = os.getcwd();\ntry:\n os.chdir(data_dir)\nexcept OSError as e:\n print(os.strerror(e.errno))\n sys.exit(-1)\n\ntarball = \"flower_photos.tgz\"\nif not os.path.isfile(tarball):\n print('Downloading flower data set.\\n')\n call(['curl', '-o', tarball, data_url])\nelse:\n print('Skipping download of flower data.')\n\n# Note the locations of the train and validation data.\ntrain_directory = scratch_dir + 'train/'\nvalidation_directory = scratch_dir + 'validation/'\n\n# process\nprint(\"Organizing the validation data into sub-directories.\")\nlabels_file = scratch_dir + 'labels.txt'\n\n# Expands the data into the flower_photos/ directory and rename it as the\n# train directory.\ncall(['tar', 'xf', 'flower_photos.tgz'])\n\nshutil.rmtree(train_directory, True)\nshutil.rmtree(validation_directory, True)\n\nos.rename('flower_photos', train_directory)\n\n# Generate a list of 5 labels: daisy, dandelion, roses, sunflowers, tulips\nlabels_file = scratch_dir + 'labels.txt'\n\nlabels = [d for d in os.listdir(train_directory) if os.path.isdir(os.path.join(train_directory, d))]\nlabels.sort()\nwith open(labels_file, 'w') as f:\n [f.write(label+'\\n') for label in labels]\n\n\n# Generate the validation data set.\nos.makedirs(validation_directory)\nfor label in labels:\n validation_dir_for_label = validation_directory + label\n train_dir_for_label = train_directory + label\n os.makedirs(validation_dir_for_label)\n\n # Move the first randomly selected 100 images to the validation set.\n images = [f for f in os.listdir(train_dir_for_label)]\n random.shuffle(images)\n validation_images = images[0:99]\n\n for image in validation_images:\n os.rename(train_dir_for_label + '/' + image, validation_dir_for_label + '/' + image)\n\n\n# Build the TFRecords version of the image data.\nos.chdir(current_dir)\nbuild_script = work_dir + \"/build_image_data\"\noutput_directory = data_dir\nos.system(build_script +\n ' --train_directory=\"%s\"'\n ' --validation_directory=\"%s\"'\n ' --output_directory=\"%s\"'\n ' --labels_file=\"%s\"' %\n (train_directory, validation_directory, output_directory, labels_file));\n\n","sub_path":"inception/inception/data/download_and_preprocess_flowers.py","file_name":"download_and_preprocess_flowers.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"207873333","text":"def tic_tac_toe_check(board):\n \n col = []\n cols = []\n game_board = []\n topL_to_bottomR = []\n topR_to_bottomL = []\n winner = []\n with_empty = {'x','o',''}\n without_empty = {'x','o'}\n \n #check that what is being passed in is not just a string or different data type\n #Will catch things such as:\n #test_board = 'x', 'x', '', 'x', 'x', 'x', 'x', 'x', 'x' (tuple)\n if isinstance(board, list) is False:\n #change to type error\n raise TypeError('Element is of type \\'' + str(type(board)) + '\\'. A list must be passed in.')\n #list is empty -> []\n if not board:\n return None\n \n #check that there are 9 spots\n if len(board) != 9:\n raise ValueError('Board does not have 9 spots. It has ' + str(len(board)) + ' spots.')\n\n #check that each element is a string. \n #Will catch things such as:\n #test_board = [['', '', '', '', '', '', '', '', '']] (list of lists)\n for s in board:\n if s:\n if not isinstance(s, str):\n raise ValueError('Element is not a string: ' + str(s))\n if not s:\n if not isinstance(s, str):\n raise ValueError('Element is not a string: ' + str(s))\n\n #All game pieces are the same. Either all 'x', 'o', or '' (empty string)\n if len(set(board)) == 1:\n if 'x' in board:\n raise ValueError('Player \\'x\\' cannot win in more than one way.')\n elif 'o' in board:\n raise ValueError('Player \\'o\\' cannot win in more than one way.')\n elif '' in board:\n return None\n\n #check if any elements are uppercase\n for s in board:\n if s.isupper():\n raise ValueError('Uppercase is not allowed.')\n \n #check if a string in the list is more than one letter, must only be 'x' not 'xx'\n for s in board:\n if s != '':\n if len(s) != 1:\n raise ValueError('Element must be of length 1')\n \n #checking for invalid characters\n if '' in board: #empty in board\n if (set(board) != set(with_empty)):\n if 'x' in board: #will allow only 'x' and ''\n if((set(board) != set({'x',''}))):\n raise ValueError('Elements must be \\'x\\', \\'o\\', or \\'\\'')\n elif 'o' in board: #will allow only 'o' and ''\n if (set(board) != set({'o',''})):\n raise ValueError('Elements must be \\'x\\', \\'o\\', or \\'\\'')\n else:\n if set({''}) != set(board):\n raise ValueError('Elements must be \\'x\\', \\'o\\', or \\'\\'')\n elif '' not in board: #no empty in board\n if (set(board) != set(without_empty)):\n #checks for board of either all 'x' or all 'o'\n if(set(board) != set({'x'})) or (set(board) != set({'o'})):\n raise ValueError('Elements must be \\'x\\', \\'o\\', or \\'\\'')\n \n #passed in as: board -> ['1', '2', '3', '4', '5', '6', '7', '8', '9']\n #append as a list of lists -> [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] \n game_board.append(board[0:3]) #first row ie: ['1', '2', '3']\n game_board.append(board[3:6]) #second row ie: ['4', '5', '6']\n game_board.append(board[6:9]) #third row ie: ['7', '8', '9']\n \n i = 0\n while i < 3:\n \n #get diagonal (top left -> bottom right)\n topL_to_bottomR.append(game_board[i][i])\n \n j = 0 \n while j < 3:\n #get columns\n col.append(game_board[j][i])\n j += 1\n i += 1\n\n #diagonal (top right -> bottom left)\n i = 0\n j = 2\n while i < 3:\n topR_to_bottomL.append(game_board[i][j])\n i += 1\n j -= 1\n \n #append as a list of lists -> [['1', '4', '7'], ['2', '5', '8'], ['3', '6', '9']]\n cols.append(col[0:3]) #first col ie: ['1', '4', '7']\n cols.append(col[3:6]) #second col ie: ['2', '5', '8']\n cols.append(col[6:9]) #third col ie: ['3', '6', '9']\n \n #Check for winners\n #If string isn't empty, if set length is 1 add winner for row\n for row in game_board:\n if '' not in row:\n if len(set(row)) == 1:\n winner.append(row[0])\n \n #If string isn't empty, if set length is 1 add winner for col \n for col in cols:\n if '' not in col:\n if len(set(col)) == 1:\n winner.append(col[0])\n \n #If string isn't empty, if set length is 1 add winner for Top L to Bottom R Diagonal\n if len(set(topL_to_bottomR)) == 1:\n if '' not in topL_to_bottomR:\n winner.append(topL_to_bottomR[0])\n \n #If string isn't empty, if set length is 1 add winner for Top R to Bottom L Diagonal\n if len(set(topR_to_bottomL)) == 1:\n if '' not in topR_to_bottomL:\n winner.append(topR_to_bottomL[0])\n \n winner_set = set(winner)\n set_length = len(winner_set)\n\n if len(winner) == 1 and '' not in winner_set:\n return next(iter(winner_set)) #return tuple(winner_set)[0] #next(iter(winner_set))\n else:\n if set_length > 1:\n raise ValueError('Two players are not allowed to win.')\n elif len(winner) > 1:\n raise ValueError('Player \\'' + next(iter(winner_set)) + '\\' cannot win in more than one way.')\n else:\n return None","sub_path":"640/impl-2.py","file_name":"impl-2.py","file_ext":"py","file_size_in_byte":5356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"319866929","text":"# -*- coding: utf-8 -*-\n# @Time : 2021-04-23 10:58\n# @Author : zxl\n# @FileName: Offer015.py\n\n\nclass Solution:\n def hammingWeight(self, n: int) -> int:\n\n count = 0\n while n:\n count += n%2\n n//=2\n return count\n\n\n","sub_path":"Offer015.py","file_name":"Offer015.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"335484083","text":"import itertools\nperms = itertools.permutations([1, 2, 3], 2)\nnext(perms) \n# (1, 2) , (1, 3), (2, 1) ...\n# 找排列组合的自带method, 太tm强了,这都有!!\n\n\nlist(itertools.product('ABC', '123'))\n#[('A', '1'), ('A', '2'), ('A', '3'), \n#('B', '1'), ('B', '2'), ('B', '3'), \n#('C', '1'), ('C', '2'), ('C', '3')]\n# itertools.product() function returns an iterator containing the Cartesian product of two sequences\n\nlist(itertools.combinations('ABC', 2))\n# [('A', 'B'), ('A', 'C'), ('B', 'C')]\n# itertools.combinations() function returns an iterator containing all the possible combinations of the given sequence of the given length","sub_path":"PythonWorkSpace/LearnPython/Advanced Iterators/itertools_showcase.py","file_name":"itertools_showcase.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"323690747","text":"\"\"\"Bodega Custmize CLI class.\"\"\"\nfrom enum import Enum\nfrom bodega_utils import Utils\n\n\nclass Types(Enum):\n \"\"\"Values TYPE can take in CUSTOMIZE command.\"\"\"\n\n DEV_MACHINE = 'dev_machine'\n\n\nclass PositionalArguments(Enum):\n \"\"\"POSITIONAL_ARGUMENTs for CUSTOMIZE command.\"\"\"\n\n HOST_INFO = 'host_info'\n\n\nclass NamedArguments(Enum):\n \"\"\"NAMED_ARGUMENTs for CUSTOMIZE command.\"\"\"\n\n SD_DEV_MOUNTRC_FILE = 'sd_dev_mountrc_file'\n PEM_FILE = \"pem_file\"\n GIT_REPO_FILE = \"git_repo_file\"\n\n\nclass BodegaCustomize(object):\n \"\"\"Sub-parser for the CUSTOMIZE command.\"\"\"\n\n def __init__(self, sub_parser, bodega_commands):\n \"\"\"Initialize BodegaCustomize class.\"\"\"\n self.commands = bodega_commands\n\n self.parser = sub_parser\n self.subparsers = self.parser.add_subparsers()\n\n self._init_subparsers()\n\n def _init_subparsers(self):\n self._init_dev_machine()\n\n def _init_dev_machine(self):\n description = \"\"\"Configure a existing dev machine\"\"\"\n sub_parser = self.subparsers.add_parser(Types.DEV_MACHINE.value,\n description=description,\n epilog=Utils.epilog)\n sub_parser.add_argument(PositionalArguments.HOST_INFO.value,\n type=Utils.parse_userhost,\n help='Host information @, ' +\n 'username is optional')\n sub_parser.add_argument(\n Utils.get_short_arg_from_name(\n NamedArguments.SD_DEV_MOUNTRC_FILE.value),\n Utils.get_long_arg_from_name(\n NamedArguments.SD_DEV_MOUNTRC_FILE.value),\n default=Utils.get_default_sd_dev_file(),\n help='sd_dev_mountrc file to use [default:%(default)s]',\n metavar='FILE')\n sub_parser.add_argument(\n Utils.get_short_arg_from_name(\n NamedArguments.PEM_FILE.value),\n Utils.get_long_arg_from_name(\n NamedArguments.PEM_FILE.value),\n default=Utils.get_default_ubuntu_pem_key(),\n help='pem file to use [default:%(default)s]',\n metavar='FILE')\n sub_parser.add_argument(\n Utils.get_short_arg_from_name(\n NamedArguments.GIT_REPO_FILE.value),\n Utils.get_long_arg_from_name(\n NamedArguments.GIT_REPO_FILE.value),\n default=None,\n help='git repo file to use, \" + \\\n \"refer to conf/sd_dev_git_repos.defaults',\n metavar='YML FILE')\n\n sub_parser.set_defaults(func=self._exec_configure_dev_machine)\n\n def _exec_configure_dev_machine(self, args_dict):\n username, host = args_dict[PositionalArguments.HOST_INFO.value]\n sync_file = args_dict[NamedArguments.SD_DEV_MOUNTRC_FILE.value]\n pem_file = args_dict[NamedArguments.PEM_FILE.value]\n git_repo_file = args_dict[NamedArguments.GIT_REPO_FILE.value]\n self.commands.configure_dev_machine(username, host,\n sync_file=sync_file,\n git_repo_file=git_repo_file,\n pem_file=pem_file)\n","sub_path":"lab/bodega/cli/bodega_customize.py","file_name":"bodega_customize.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"193815873","text":"#!/usr/bin/env python\n\"\"\"\n================================================================================\n:mod:`config` -- Configuration parser\n================================================================================\n\n.. module:: config\n :synopsis: Read configuration file\n\n.. inheritance-diagram:: pymontecarlo.util.config\n\nConfiguration parser to read INI type files.\nThis parser differs slightly from those available in the :mod:`ConfigParser`\nmodule as the sections, options and values can be accessed using attributes\ninstead of getters and setters.\nWhile the access of the data is different, this class uses the\n:class:`SafeConfigParser` of the :mod:`ConfigParser` module to read and\nwrite configuration file.\n\n.. warning::\n\n This parser does *not* support section or option starting with a number.\n\nLet's take the configuration file::\n\n [section1]\n option1=value1\n option2=value2\n\n [section2]\n option3 = value3\n\nTo load the configuration file, use the :meth:`read` method::\n\n >>> config = ConfigParser()\n >>> with open(filepath, 'r') as fp:\n ... config.read(fp)\n\nTo get the value of ``option1`` in ``section1``::\n\n >>> config.section1.option1\n 'value1'\n\nor of ``option3`` in ``section2``::\n\n >>> config.section2.option3\n 'value3'\n\nTo check if a section is present, use the ``in`` statement::\n\n >>> 'section3' in config\n False\n >>> 'option2' in config.section1\n True\n\nTo iterate over all sections and options::\n\n >>> for section, option, value in config:\n ... print section, option, value\n 'section1' 'option1' 'value1'\n 'section1' 'option2' 'value2'\n 'section2' 'option3' 'value3'\n\nNote that the order may changed.\n\nTo add a section or option::\n\n >>> config.add_section('section3')\n >>> 'section3' in config\n True\n >>> config.section3.option4 = 'value4'\n\nThe following syntax can be shorten as :meth:`add_section` method returns the\nadded section::\n\n >>> config.add_section('section3').option4 = 'value4'\n\nIf the added section already exists, no section is added and the current one\nis returned::\n\n >>> config.add_section('section1').option1\n 'value1'\n\nFinally, the configuration can be saved back to a file::\n\n >>> with open(filepath, 'w') as fp:\n ... config.write(fp)\n\n\"\"\"\n\n# Script information for the file.\n__author__ = \"Philippe T. Pinard\"\n__email__ = \"philippe.pinard@gmail.com\"\n__version__ = \"0.1\"\n__copyright__ = \"Copyright (c) 2011 Philippe T. Pinard\"\n__license__ = \"GPL v3\"\n\n# Standard library modules.\nfrom configparser import ConfigParser as _ConfigParser\n\n# Third party modules.\n\n# Local modules.\n\n# Globals and constants variables.\n\nclass _Section(object):\n def __init__(self, options={}):\n self.__dict__.update(options)\n\n def __iter__(self):\n for option_name, value in self.__dict__.items():\n yield option_name, value\n\n def __contains__(self, option_name):\n return option_name in self.__dict__\n\nclass ConfigParser(object):\n \"\"\"\n Configuration parser.\n \"\"\"\n\n def __contains__(self, section_name):\n return section_name in self.__dict__\n\n def __iter__(self):\n for section_name, section in self.__dict__.items():\n for option_name, value in section:\n yield section_name, option_name, value\n\n def add_section(self, section_name):\n \"\"\"\n Adds a new section if the specified section name doesn't exist.\n Does nothing if the section already exists.\n\n :return: section\n \"\"\"\n if section_name not in self.__dict__:\n self.__dict__[section_name] = _Section()\n return self.__dict__[section_name]\n\n def read(self, fileobj, ignore_errors=False):\n \"\"\"\n Reads the configuration from the file object.\n\n If ``ignore_errors`` is ``True`` and a section or option starts with\n a number, a :exc:`IOError` exception is raised.\n If not, these sections or options are skipped.\n\n :arg fileobj: file object\n :arg ignore_errors: whether to raise exception or skip invalid\n section(s) and option(s)\n \"\"\"\n parser = _ConfigParser()\n parser.read_file(fileobj)\n\n for section in parser.sections():\n if section[0].isdigit():\n if ignore_errors:\n continue\n raise IOError(\"Section name (%s) cannot start with a digit\" % section)\n\n options = {}\n\n for option in parser.options(section):\n if option[0].isdigit():\n if ignore_errors:\n continue\n raise IOError(\"Option name (%s) cannot start with a digit\" % option)\n\n options[option] = parser.get(section, option)\n\n self.__dict__[section] = _Section(options)\n\n def write(self, fileobj):\n \"\"\"\n Writes the configuration inside the file object.\n\n :arg fileobj: file object\n \"\"\"\n parser = _ConfigParser()\n\n # Add sections\n for section_name in self.__dict__:\n parser.add_section(section_name)\n\n # Add options\n for section_name, option_name, value in self:\n parser.set(section_name, option_name, str(value))\n\n parser.write(fileobj)\n","sub_path":"pymontecarlo/util/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"429806656","text":"# 2675번: 문자열 반복\n# https://www.acmicpc.net/problem/2675\n# Version: Python 3.9.7\n\n\nfrom sys import stdin\n\nread = stdin.readline\n\nif __name__ == \"__main__\":\n for _ in range(int(read())):\n count, string = read().rstrip().split()\n for char in string:\n print(char * int(count), end=\"\")\n print()\n\n","sub_path":"boj/bronze2/2675.py","file_name":"2675.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"651403410","text":"class Graph:\n def __init__(self, vertices=[], edges=[]):\n self._vertices = vertices\n self._edges = edges\n\n def add_node(self, *vertices):\n for vertex in vertices:\n self._vertices.append(vertex)\n\n def create_adj(self, *edges):\n for edge in edges:\n self._edges.append(edge)\n\n def vertices(self): return self._vertices\n def edges(self): return self._edges\n\n def __str__(self):\n traversal = \"\"\n for i in self._edges:\n vertex_from = self._vertices[i[0]]\n vertex_to = self._vertices[i[1]]\n traversal += str(vertex_from) + \" <-> \" + str(vertex_to) + \"\\n\"\n return traversal\n\n\ndef read_int(prompt):\n return int(input(prompt))\n\n\nif __name__ == '__main__':\n g = Graph()\n\n print(\"1. Add node to graph\")\n print(\"2. Create adjacency\")\n print(\"3. Print adjacencies\")\n\n while True:\n print(\"Vertices:\", g.vertices())\n print(\"Edges\", g.edges())\n inp = read_int(\"Your choice: \")\n if inp == 1:\n g.add_node(input(\" Enter node: \"))\n elif inp == 2:\n g.create_adj([read_int(\" Enter edge from: \"),\n read_int(\" Enter edge to: \")])\n else:\n print(g)\n","sub_path":"MCA/Data Structures/Graph_adj.py","file_name":"Graph_adj.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"133511127","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.core.validators\nimport uuidfield.fields\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='ManagrUser',\n fields=[\n ('password', models.CharField(max_length=128, verbose_name='password')),\n ('last_login', models.DateTimeField(verbose_name='last login', default=django.utils.timezone.now)),\n ('id', uuidfield.fields.UUIDField(editable=False, unique=True, primary_key=True, blank=True, serialize=False, max_length=32)),\n ('email', models.EmailField(max_length=255, unique=True, verbose_name='email address')),\n ('phone_number', models.CharField(unique=True, verbose_name='mobile phone number', default=None, null=True, validators=[django.core.validators.RegexValidator(regex='^\\\\+?1?\\\\d{9,15}$', message=\"Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.\")], blank=True, max_length=20)),\n ('is_active', models.BooleanField(default=True)),\n ('is_admin', models.BooleanField(default=False)),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"account/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"265298686","text":"#!/usr/bin/python3\nimport numpy as np\nimport networkx as nx\nimport itertools\nimport scipy.stats as stats\nimport essentials as es\nimport random\nimport time\n#Scripted by David Vargas\n#---------------------------------------------\n#Convention if directed networks are introduced,\n#Aij=1 if there is an edge from j to i. This\n#means one would sum over row i to get the total\n#number of incoming edges to node i.\n#Here I am summing over rows.\n#Unfinished function - quantum assortativity\n#Next implement hierarchical clustering algorithm\n#described on page 388 of Newman's book on networks\n#Next implement fractal dimension calculation proposed\n#by Simona.\n\ndef strengths(mutualinformation):\n #Return the strength of all nodes in the network in order.\n return np.sum(mutualinformation, axis = 1)\n\ndef density(matrix):\n #Calculates density, also termed connectance in some\n #literature. Defined on page 134 of Mark Newman's book\n #on networks.\n l = len(matrix)\n lsq = l*(l-1)\n return np.sum(matrix)/lsq \n\n# def clustering(matrix):\n# #Calculates the clustering coefficient\n# #as it is defined in equation 7.39 of\n# #Mark Newman's book on networks. Page 199.\n# matrixcube = np.linalg.matrix_power(matrix, 3)\n# matrixsq = np.linalg.matrix_power(matrix, 2)\n# #Zero out diagonal entries. So we do not count edges as\n# #connected triples.\n# for i in range(len(matrixsq)):\n# matrixsq[i][i] = 0\n# denominator = np.sum(matrixsq)\n# numerator = np.trace(matrixcube)\n# #if there are no closed paths of length\n# #three the clustering is automatically\n# #set to zero.\n# if numerator == 0.:\n# return 0.\n# else:\n# return numerator/denominator\n\ndef clustering(matrix):\n #Calculates the clustering coefficient\n #as it is defined in equation 7.39 of\n #Mark Newman's book on networks. Page 199.\n matrixcube = np.linalg.matrix_power(matrix, 3)\n numerator = np.trace(matrixcube)\n #if there are no closed paths of length\n #three the clustering is automatically\n #set to zero.\n if numerator == 0.:\n return 0.\n else:\n matrixsq = np.linalg.matrix_power(matrix, 2)\n denominator = np.sum(matrixsq) - np.trace(matrixsq)\n return numerator/denominator\n\ndef localclustering(matrix):\n l = len(matrix)\n localclustering = []\n matrixcube = np.linalg.matrix_power(matrix, 3)\n for i in range(l):\n matrix2 = np.outer(matrix[i,:], matrix[i,:])\n numerator = matrixcube[i][i]\n denominator = (np.sum(matrix2)-np.trace(matrix2))\n if denominator != 0:\n localclustering.append(numerator/denominator)\n else:\n localclustering.append(0)\n # squaretmp = 0\n # for i in range(l):\n # for j in range(l):\n # for k in range(j):\n # squaretmp += matrix[i][j]*matrix[i][k]\n # if squaretmp != 0:\n # localclustering.append(0.5*matrixcube[i][i]/squaretmp)\n # else:\n # localclustering.append(0)\n # squaretmp = 0\n return np.array(localclustering)\n\ndef rhotype(rho):\n localtmp = 0\n localtmp2 = 0\n d = len(rho)\n basisstate = np.zeros(d)\n brastate = np.zeros(d)\n #By construction I do not have to conjugate the elements to get the bra.\n #This is because basis state is a vector with a single one in a list of zeros.\n for i in range(d):\n basisstate[i] = 1\n brastate = basisstate\n #Map basis state to basis state.\n basisstate = np.dot(rho, basisstate)\n# print 'basis',basisstate\n# print 'bra',brastate,'basis',basisstate\n# print 'rho',rho\n expectation=np.dot(brastate, basisstate)\n basisstate[i] = 0\n# print tuple([expectation,i])\n if expectation >= localtmp:\n localtmp = expectation\n localtmp2 = i\n rhotype = localtmp2\n return int(rhotype)\n\ndef rhotypes(rhos):\n L = len(rhos)\n rhoTypes = np.zeros(L, dtype = int)\n for i in range(L):\n rhoTypes[i] = rhotype(rhos[i])\n return rhoTypes\n\ndef quantumassortativity(rhos,mutualinformation,typefunction):\n L = len(rhos)\n sites = np.array(range(L))\n rhoTypes = typefunction(rhos)\n types = np.unique(rhoTypes)\n longtype = {}\n for atype in types:\n longtype[atype] = atype*np.ones(L, dtype = int)\n ed = len(types)\n eab = np.zeros((ed,ed))\n sitesbytype = {}\n sitesbytype2 = []\n for atype in types:\n abool = np.equal(rhoTypes,longtype[atype])\n sitesbytype[atype] = list(sites[abool])\n for atype in types:\n for btype in types:\n for i in sitesbytype[atype]:\n for j in sitesbytype[btype]:\n eab[atype][btype] += mutualinformation[i][j]\n eab = eab/np.sum(eab)\n trace = np.trace(eab)\n prodsum = np.sum(np.dot(eab,eab))\n if 1. - prodsum != 0:\n assortativity = (trace-prodsum)/(1.-prodsum)\n return assortativity\n else:\n return nan\n \n# def disparity(matrix):\n# #Disparity defined on page 199 of doi:10.1016/j.physrep.2005.10.009 \n# #Equation 2.39, Here I take the average of this quantity over the\n# #entire network\n# l = len(matrix)\n# numerator = np.sum(matrix**2, axis = 1)/l\n# denominator = np.sum(matrix, axis = 1)\n# #Logical Check\n# logos = denominator > 0\n# numerator = numerator[logos]\n# denominator = denominator[logos]\n# denominator = denominator**2\n# #Check for zero denominator.\n\n# if sum(denominator) == 0.:\n# return np.nan\n# else: \n# return sum(numerator/denominator)\n\ndef disparity(matrix):\n #Disparity defined on page 199 of doi:10.1016/j.physrep.2005.10.009 \n #Equation 2.39, Here I take the average of this quantity over the\n #entire network\n l = len(matrix)\n numerator = np.sum(matrix**2, axis = 1)/l\n denominator = np.sum(matrix, axis = 1)**2 + 1.E-16j\n return np.sum(numerator/denominator).real# .real\n # #Check for zero denominator.\n # if sum(denominator) == 0.:\n # return np.nan\n # else: \n # return sum(numerator/denominator)\n\ndef disparitylattice(matrix):\n #Local disparity across the entire lattice.\n numerator = np.sum(matrix**2, axis = 1)\n denominator = np.sum(matrix, axis = 1)**2 + 1.E-16j\n disparity = (numerator/denominator).real\n return disparity\n\ndef strengthdist(mutualinformation, bins = np.linspace(0, 1, 11)):\n #Compute the weighted analog of a degree distribution.\n strens = strengths(mutualinformation)\n # maxinfo=np.max(strens)\n # mininfo=np.min(strens)\n return np.histogram(strens,bins)\n\ndef pearson(mutualinformation):\n L = len(mutualinformation)\n pearsonR = np.zeros((L,L))\n pvalues = np.zeros((L,L))\n for i in range(L):\n for j in range(L):\n if i != j:\n r,p = stats.pearsonr(mutualinformation[i], mutualinformation[j])\n pearsonR[i][j] = r\n pvalues[i][j] = p\n else:\n pearsonR[i][j] = 0.\n pvalues[i][j] = 0.\n return [pearsonR, pvalues]\n\ndef edgeweightdist(mutualinformation, bins):\n L = len(mutualinformation)\n edges = es.flatten(list(mutualinformation))\n return np.histogram(edges,bins)[0]\n\ndef coarsegrainnetwork(mutualinformation, bins):\n #Default behavior of histograms is to have the intervals\n #Closed on the left and open on the right.\n #The bin with the largest values is closed on both ends.\n L = len(mutualinformation)\n coarsematrix = np.zeros((L,L))\n ll = len(bins)\n for i in range(L):\n for j in range(L):\n for k in range(ll-2):\n if bins[k] <= mutualinformation[i][j] < bins[k+1]:\n coarsematrix[i][j] = k\n if bins[ll-2] <= mutualinformation[i][j] <= bins[ll-1]:\n coarsematrix[i][j] = ll-2\n return coarsematrix\n\n#NetworkX additions\n#---------------------------------------------\n\ndef distance(mutualinformation):\n #Initialize array\n length = len(mutualinformation)\n thisdistance = np.zeros((length,length))\n #If an element has value less than (10^-14) in absolute value,\n #then treat it as of value (10^-16), set its distance\n #to 10^16. Otherwise set it mij^(-1).\n #The value (10^-14) must be adjusted in coordination with\n #the cutoff applied to the weighted network of interest.\n #The purpose of setting this value equal to 10^16 is\n #so that the geodesic path length algorithm will ignore\n #any edges less than the cutoff treating.\n for i in range(length):\n for j in range(length):\n if np.abs(mutualinformation[i, j]) <= 1E-14:\n thisdistance[i, j] = np.power(10.,16)\n else:\n thisdistance[i, j] = np.power(mutualinformation[i, j],-1)\n return thisdistance\n\ndef geodesic(distance, i, j):\n #Initialize networkx graph object\n #NetworkX indexing starts at zero.\n #Ends at N-1 where N is the number of nodes.\n latticelength = len(distance)\n G = nx.Graph(distance)\n #Use networkx algorithm to compute the shortest path from\n #the first lattice site to the last lattice site.\n pathlength = nx.shortest_path_length(G, source = i-1, target = j-1, weight = 'weight')\n #The pathlength is tested for an unreasonable value.\n #An unreasonable value for the path length is a function of the cutoff\n #applied to the weighted network under analysis and the value set in\n #the distance function thisdistance[i,j]=np.power(10.,16)\n if pathlength > np.power(10., 15):\n return np.nan\n return pathlength\n\ndef harmoniclength(distance):\n #page 11, equation 2 The Structure and Function of Complex Networks\n #If the geodesic distance between two nodes is a number then \n #append it to alist to include it in the sum.\n l = len(distance)\n# print 'Node count: ', l\n factor = 1./(0.5*l*(l-1))\n# print 'Factor: ', factor\n alist = []\n for i in range(1, len(distance) + 1):\n for j in range(i+1, len(distance) + 1):\n geo = geodesic(distance, i, j)\n if not np.isnan(geo):\n# print '(i,j)',tuple([i,j])\n alist.append(1./geo)\n# print 'alist',alist\n# print 'Harmonic Mean of Distances: ', 1./(factor*sum(alist))\n return 1./(factor*sum(alist))\n\ndef eigenvectorcentralitynx0(mutualinformation):\n #Uses the power method to find eigenvector of \n #a weighted adjacency matrix.\n G = nx.Graph(mutualinformation)\n eigvcent = nx.eigenvector_centrality(G, weight='weight', max_iter=2000)\n return eigvcent\n\ndef eigenvectorcentralitynx(mutualinformation, startingvector):\n #Identical to eigenvectorcentralitynx0, but requires an additional argument startingvector.\n #starting vector provides an initial guess for the eigen vector centrality of all nodes.\n #startingvector must be a python dictionary. key = node, value = eigenvector centrality estimate.\n G = nx.Graph(mutualinformation)\n eigvcent = nx.eigenvector_centrality(G, weight = 'weight', max_iter = 2000, nstart = startingvector)\n return eigvcent\n\n#Here I provide some test cases. These test cases assume the weighted\n#networks being provided are quantum mutual information networks.\ntest=True\ndef main():\n if test==True:\n testrho = np.array([[0.1, 0], [0, 0.9]])\n testrho2 = np.array([[0.7, 0], [0, 0.3]])\n testrho3 = np.array([[0.5, 0.], [0.0, 0.5]])\n testrhos = [testrho, testrho2, testrho3]\n singlet = np.array([[0., 0., 1.], [0., 0., 0.], [1., 0., 0.]])\n ghz = np.array([[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]])\n w = np.array([[0, 0.636514, 0.636514],\n [0.636514, 0, 0.636514],\n [0.636514, 0.636514, 0]])\n fourqubits = np.array([[0, 1, 0, 0], [1, 0, 1, 1],\n [0, 1, 0, 1], [0, 1, 1, 0]])\n states = [singlet, ghz, w, fourqubits]\n names = ['singlet', 'ghz', 'w', 'Four Qubits']\n functions = [strengths, density, clustering, localclustering, disparity,\n disparitylattice, distance]#, eigenvectorcentralitynx0]\n measurenames = ['Strengths', 'Density', 'Clustering', \n 'Local Clustering', 'Average Disparity', \n 'Nodal Disparity', 'Distances']#,\n# 'Eigenvector Centrality']\n for i in range(len(states)):\n print(names[i])\n for function in functions:\n print(function, function(states[i]))\n print('Rhos: ', testrho, '\\n', testrho2, '\\n', testrho3, '\\n')\n print('Rho Types: ', rhotypes(testrhos))\n print(quantumassortativity(testrhos, ghz, rhotypes))\n #Counterintuitive result for pearson correlation of ghz state.\n #It is negative. This is because we are arbitarily setting the \n #diagonal of the mutual information matrix to zero. \n print(pearson(ghz))\n \n print(\"Edge Weight Distribution: \", edgeweightdist(ghz, [0, 0.5, 1]))\n print(\"Full Matrix: \", ghz)\n print(\"Coarse Matrix:\", coarsegrainnetwork(ghz, [0, 0.5, 1]))\n \n \n # print(\"Local Clustering: \", localclustering(matrix))\n \n # total = 0\n # total2 = 0\n # for i in range(10000):\n # matrix = np.zeros((26, 26))\n # for i in range(26):\n # for j in range(26):\n # matrix[i][j] = random.random()\n # t0 = time.time()\n # clustering(matrix)\n # t1 = time.time()\n # clustering2(matrix)\n # t2 = time.time()\n # total += (t1-t0)/(t2-t1)\n # total2 += clustering2(matrix) - clustering(matrix)\n # print(total/10000)\n # print(total2/10000)\n #This effect should go away in the thermodynamic limit. \n #I can check this. Next I should check how robust the\n #result is against the size of the numerical noise.\n # def GHZ(L):\n # mutualinformation=np.zeros((L,L))\n # for i in range(L):\n # for j in range(L):\n # if i!=j:\n # mutualinformation[i][j]=0.5#+0.01*(np.random.rand()-0.5)\n # else:\n # mutualinformation[i][j]=0.\n # return mutualinformation\n # for l in [4,10,20,50]:\n # print l,'\\n',pearson(GHZ(l))[0][l/2][l/2+1]\n # a=1.E-14*np.ones((20,20))\n # for i in range(len(a)):\n # a[i][i]=0.\n # print 'disparity', disparity(a)\n # print 'clustering', clustering(GHZ(3))\n # print 0.2*GHZ(3)\n # a=0.01*np.ones(100)*range(100)\n # for i in a:\n # print clustering(i*GHZ(3))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"networkmeasures.py","file_name":"networkmeasures.py","file_ext":"py","file_size_in_byte":14824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"223273380","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread('rb15.jpg')\n\n\"\"\"\nAffine transforms\n- scaling\n- rotation\n- translation\n- skewing\n- preserve collinearity and parallelism\n\nNon-affine transforms\n- also known as projective transformation, homography\n- does not preserve parallelism, length, and angle\n- does preserve collinearity and incidence\n\nTranslation Matrix = |1 0 Tx|\n |0 1 Ty|\nTx = shift along x-axis\nTy = shift along y-axis\nuse cv2.warpAffine to implement translations\n\nRotation Matrix:\nM = |cos(theta) -sin(theta)|\n |sin(theta) cos(theta) |\n\ncv2.getRotationMatrix2D(rotation_center_x, rotation_center_y, angle of rotation, scale)\n\"\"\"\n\nheight, width = img.shape[:2]\nquarter_height, quarter_width = height/4, width/4\n\nT = np.float32([[1, 0, -quarter_width], [0, 1, -quarter_height]])\n\nimg_translation = cv2.warpAffine(img, T, (width, height))\ncv2.imshow('Translation', img_translation)\n\nrotation_matrix = cv2.getRotationMatrix2D((width/2, height/2), 90, 1)\nrotated_image = cv2.warpAffine(img, rotation_matrix, (width, height))\n\ncv2.imshow('Rotation', rotated_image)\n\nt_img = cv2.transpose(img)\ncv2.imshow(\"Transpose\", t_img)\n\nh_flipped = cv2.flip(image, 1)\nv_flipped = cv2.flip(image, -1)\n\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"translations, rotations, and transformations.py","file_name":"translations, rotations, and transformations.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"348595680","text":"# indexing a local csv file test.csv\nINDEX_NAME = 'titanic' # 数据库名字\nTYPE_NAME = 'passenger' # 表名字\nID_FIELD = 'passengerid' # 文档ID\n\nimport csv\nimport sys\n\nresponse = open(sys.argv[1], 'rt', encoding=\"utf-8\") # put this the same directory as test.csv\nfile_object = csv.reader(response)\nheader = file_object.__next__() # header得第一行 file_object去第一行\nheader = [item.lower() for item in header] # 第一行内容小写\n\nbulk_data = [] \n\nfor row in file_object:\n data_dict = {}\n for i in range(len(row)):\n data_dict[header[i]] = row[i]\n op_dict = {\n \"index\": {\n \"_index\": INDEX_NAME, \n \"_type\": TYPE_NAME, \n \"_id\": data_dict[ID_FIELD]\n }\n }\n bulk_data.append(op_dict)\n bulk_data.append(data_dict)\n\n# step1 : create ES client\nfrom elasticsearch import Elasticsearch\nesHost1 = {\"host\" : \"localhost\", \"port\" : 9200}\nes = Elasticsearch(hosts=[esHost1])\n\n# step2 : check\n# if the index already exist, delete it and create it again\nif es.indices.exists(INDEX_NAME):\n print(\"deleting '%s' index...\" % (INDEX_NAME))\n res = es.indices.delete(index = INDEX_NAME)\n print(\" response: '%s'\" % (res))\n\n# step3 : settings\n# since we are running locally, use one shard and no replicas\n# Each index created can have specific settings associated with it.\nrequest_body = {\n \"settings\" : {\n \"index\" : {\n \"number_of_shards\": 1,\n \"number_of_replicas\": 0\n }\n }\n}\n# Default for number_of_shards is 5\n# Default for number_of_replicas is 1 (ie one replica for each primary shard)\n# The index settings can also be defined with JSON:\n'''\n\n$ curl -XPUT 'http://localhost:9200/twitter/' -d '{\n \"settings\" : {\n \"index\" : {\n \"number_of_shards\" : 3,\n \"number_of_replicas\" : 2\n }\n }\n}'\n\n'''\n# or more simplified\n'''\n\n$ curl -XPUT 'http://localhost:9200/twitter/' -d '{\n \"settings\" : {\n \"number_of_shards\" : 3,\n \"number_of_replicas\" : 2\n }\n}'\n\n'''\n# You do not have to explicitly specify index section inside the settings section.\n\n# step4 : create index\nprint(\"creating '%s' index...\" % (INDEX_NAME))\nres = es.indices.create(index = INDEX_NAME, body = request_body)\nprint(\" response: '%s'\" % (res))\n\n# bulk index the data\nprint(\"bulk indexing...\")\nres = es.bulk(index = INDEX_NAME, body = bulk_data, refresh = True)\n\n# sanity check\nres = es.search(index = INDEX_NAME, size=30, body={\"query\": {\"match_all\": {}}})\n# display the result immediately:\n# print(\" response: '%s'\" % (res)) \n\n# To display the results more clearly, we can loop through them:\nprint(\"results:\")\nfor hit in res['hits']['hits']:\n print(\"\\n\") # str\n print(hit[\"_source\"]) # dict\n\nresponse.close # close the file\n","sub_path":"es4.py","file_name":"es4.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"577984340","text":"#!/usr/bin/python\n\n\"\"\"\nUnit test for MetaData.\n\"\"\"\n\n# Get object to test \nimport sys\nsys.path.append('../')\nfrom MetaData import MetaData\n\n# Get base class to run tests off of\nimport unittest\n\n# Create derived class that has the tests.\nclass TestMetaData(unittest.TestCase):\n def setUp(self):\n self.metaData = MetaData({})\n\n def test_meta_data_is_processed(self):\n testStr = '\\n'\n\n self.metaData.process(testStr)\n metaData = self.metaData.get()\n self.assertEqual('myblog', metaData['blogId'])\n\n def test_blank_meta_data_returns_none(self):\n testStr = ''\n self.metaData.process(testStr)\n metaData = self.metaData.get()\n self.assertEqual({}, metaData);\n\n\n\n\n# Main function will run all tests in classes derived from TestCase\nif __name__ == \"__main__\":\n unittest.main()\n\n\n","sub_path":"unit_tests/MetaData.t.py","file_name":"MetaData.t.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"478601341","text":"#Create a function named exponents() that takes two lists as parameters named bases and powers. \n#Return a new list containing every number in bases raised to every number in powers.\n\n\ndef exponents(bases, powers):\n new_ar = []\n for a in bases:\n for b in powers:\n new_ar.append(a**b)\n\n return new_ar\n\nprint(exponents([2, 3, 4], [1, 2, 3]))\n","sub_path":"6_1_Looping_Exponents.py","file_name":"6_1_Looping_Exponents.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"506611961","text":"import snowboydecoder\nimport sys\nimport signal\n\ninterrupted = False\n\ndef signal_handler(signal, frame):\n global interrupted\n interrupted = True\n\ndef interrupt_callback():\n global interrupted\n return interrupted\n\nmodel = r'resources/snowboy.umdl' # 修改model,指定其文件名\n\n# capture SIGINT signal, e.g., Ctrl+C\nsignal.signal(signal.SIGINT, signal_handler)\n\n# 唤醒词检测函数,调整sensitivity参数可修改唤醒词检测的准确性\ndetector = snowboydecoder.HotwordDetector(model, sensitivity=0.5)\nprint('Listening... Press Ctrl+C to exit')\n\n# main loop\n# 回调函数 detected_callback=snowboydecoder.play_audio_file \n# 修改回调函数可实现我们想要的功能\ndetector.start(detected_callback=snowboydecoder.play_audio_file,\n interrupt_check=interrupt_callback,\n sleep_time=0.03)\n\n# 释放资源\ndetector.terminate()\n","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"203364033","text":"import os \r\nfrom PIL import Image\r\n\r\nif not os.path.exists('../data/'):\r\n\tos.mkdir('../data')\r\nimgs = os.listdir()\r\nimgs = [i for i in imgs if '.jpg' in i]\r\nfor i in imgs:\r\n\timg = Image.open(i)\r\n\timg = img.resize((120,120))\r\n\timg.save(f'../data/{i}')\r\n\tprint(f'已完成第{i}张图片')\r\n","sub_path":"rawdata/datamake.py","file_name":"datamake.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"577738248","text":"import Transactions\r\nimport Payments\r\nimport Customers\r\nimport Database as db\r\nimport Constants\r\n\r\n#name,prv_out_standing, payments_recvd, outstd_bal, old_points, points_added, new_points\r\nCustomers_test_data = [[\"Jhon\",30000,0,30000,100,0,100],\r\n [\"Ram\",50000,0,50000,200,0,200],\r\n [\"Raj\",450000,0,450000,600,0,600],\r\n [\"Ian\",26000,0,26000,400,0,400],\r\n [\"Sachin\",110000,0,110000,500,0,500]]\r\n\r\n#name, date, amount\r\nPayments_data = [[\"Jhon\",\"10-06-2016\",1000],\r\n [\"Jhon\",\"10-07-2016\",2000],\r\n [\"Jhon\",\"10-09-2016\",10000],\r\n [\"Ram\",\"10-11-2016\",11200],\r\n [\"Ram\",\"10-12-2016\",5000]]\r\n#name, trans_id, date, amount,trans_type\r\nTransactions_data = [[\"Jhon\",112,\"1-06-2016\",5000,Constants.TRANS_SCHD],\r\n [\"Jhon\",113,\"2-06-2016\",3000,Constants.TRANS_SWIPE],\r\n [\"Jhon\",114,\"3-06-2016\",4000,Constants.TRANS_ONLINE],\r\n [\"Ram\",1,\"1-06-2016\",5000,Constants.TRANS_ONLINE],\r\n [\"Ram\",2,\"2-06-2016\",7000,Constants.TRANS_SWIPE]]\r\n\r\n\r\n\r\ndef main():\r\n print(\"Hello World!\")\r\n for row in Customers_test_data:\r\n # print(row)\r\n Customers.AddCustomer(row)\r\n #db.printTable(Constants.CUSTOMER_TBL)\r\n\r\n for row in Transactions_data:\r\n print(\"Transaction:\", row)\r\n Transactions.ProcessTrans(row)\r\n #db.printTable(Constants.TRANS_TBL)\r\n #db.printTable(Constants.CUSTOMER_TBL)\r\n\r\n for row in Payments_data:\r\n print(\"Payment : \", row)\r\n Payments.ProcessPayments(row)\r\n #db.printTable(Constants.TRANS_TBL)\r\n #db.printTable(Constants.PAYMENTS_TBL)\r\n #db.printTable(Constants.CUSTOMER_TBL)\r\n Customers.generateStatment();\r\n\r\n for row in Transactions_data:\r\n print(\"Transaction:\",row)\r\n Transactions.ProcessTrans(row)\r\n #db.printTable(Constants.TRANS_TBL)\r\n #db.printTable(Constants.CUSTOMER_TBL)\r\n\r\n for row in Payments_data:\r\n print(\"Payment : \", row)\r\n Payments.ProcessPayments(row)\r\n #db.printTable(Constants.TRANS_TBL)\r\n #db.printTable(Constants.PAYMENTS_TBL)\r\n #db.printTable(Constants.CUSTOMER_TBL)\r\n Customers.generateStatment();\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"589676043","text":"\"\"\"\nCreated on Aug 28, 2018\n\n@author: mjasnik\n\"\"\"\n\n# imports\nimport os\nimport getpass\nfrom os import geteuid\n\n# timekpr imports\nfrom timekpr.common.constants import constants as cons\nfrom timekpr.common.log import log\nfrom timekpr.client.interface.dbus.administration import timekprAdminConnector\nfrom timekpr.common.utils.config import timekprConfig\nfrom timekpr.common.constants import messages as msg\n\n\nclass timekprAdminClient(object):\n \"\"\"Main class for holding all client logic (including dbus)\"\"\"\n\n # --------------- initialization / control methods --------------- #\n\n def __init__(self, pIsDevActive=False):\n \"\"\"Initialize admin client\"\"\"\n # dev\n self._isDevActive = pIsDevActive\n\n # get our connector\n self._timekprAdminConnector = timekprAdminConnector(self._isDevActive)\n\n # main object for GUI\n self._adminGUI = None\n\n def startTimekprAdminClient(self, *args):\n \"\"\"Start up timekpr admin (choose gui or cli and start this up)\"\"\"\n # check whether we need CLI or GUI\n lastParam = args[len(args)-1]\n timekprForceCLI = False\n\n # check for script\n if (\"/timekpra\" in lastParam or \"timekpra.py\" in lastParam):\n # whether we have X running or wayland?\n timekprX11Available = os.getenv(\"DISPLAY\") is not None\n timekprWaylandAvailable = os.getenv(\"WAYLAND_DISPLAY\") is not None\n timekprMirAvailable = os.getenv(\"MIR_SOCKET\") is not None\n\n # if we are required to run graphical thing\n if (timekprX11Available or timekprWaylandAvailable or timekprMirAvailable):\n # save logging for later use in classes down tree\n self._logging = {cons.TK_LOG_L: cons.TK_LOG_LEVEL_DEBUG, cons.TK_LOG_D: cons.TK_LOG_TEMP_DIR, cons.TK_LOG_W: (cons.TK_LOG_OWNER_ADMIN_SU if geteuid() == 0 else cons.TK_LOG_OWNER_ADMIN), cons.TK_LOG_U: getpass.getuser()}\n # logging init\n log.setLogging(self._logging)\n\n # configuration init\n _timekprConfigManager = timekprConfig(pIsDevActive=self._isDevActive, pLog=self._logging)\n # load config\n _timekprConfigManager.loadMainConfiguration()\n # resource dir\n _resourcePathGUI = os.path.join(_timekprConfigManager.getTimekprSharedDir(), \"client/forms\")\n\n # use GUI\n from timekpr.client.gui.admingui import timekprAdminGUI\n # load GUI and process from there\n self._adminGUI = timekprAdminGUI(cons.TK_VERSION, _resourcePathGUI, getpass.getuser(), self._isDevActive)\n # nor X nor wayland are available\n else:\n # print to console\n log.consoleOut(msg.getTranslation(\"TK_MSG_CONSOLE_GUI_NOT_AVAILABLE\") + \"\\n\")\n # forced CLI\"\n timekprForceCLI = True\n else:\n # CLI\n timekprForceCLI = True\n\n # for CLI connections\n if timekprForceCLI:\n # connect\n self._timekprAdminConnector.initTimekprConnection(True)\n # connected?\n if self._timekprAdminConnector.isConnected()[1]:\n # use CLI\n # validate possible parameters and their values, when fine - execute them as well\n self.checkAndExecuteAdminCommands(*args)\n\n # --------------- parameter validation methods --------------- #\n\n def checkAndExecuteAdminCommands(self, *args):\n \"\"\"Init connection to timekpr dbus server\"\"\"\n # initial param len\n paramIdx = 0\n paramLen = len(args)\n adminCmdIncorrect = False\n tmpIdx = 0\n\n # determine parameter offset\n for rArg in args:\n # count offset\n tmpIdx += 1\n # check for script\n if \"/timekpra\" in rArg or \"timekpra.py\" in rArg:\n paramIdx = tmpIdx\n\n # this gets the command itself (args[0] is the script name)\n adminCmd = args[paramIdx] if paramLen > paramIdx else \"timekpra\"\n\n # now based on params check them out\n # this gets saved user list from the server\n if adminCmd == \"--help\":\n # fine\n pass\n # this gets saved user list from the server\n elif adminCmd == \"--userlist\":\n # check param len\n if paramLen != paramIdx + 1:\n # fail\n adminCmdIncorrect = True\n else:\n # get list\n result, message, userList = self._timekprAdminConnector.getUserList()\n\n # process\n if result == 0:\n # process\n self.printUserList(userList)\n else:\n # log error\n log.consoleOut(message)\n\n # this gets user configuration from the server\n elif adminCmd == \"--userconfig\":\n # check param len\n if paramLen != paramIdx + 2:\n # fail\n adminCmdIncorrect = True\n else:\n # get user config\n result, message, userConfig = self._timekprAdminConnector.getUserConfig(args[paramIdx+1])\n\n # process\n if result == 0:\n # process\n self.printUserConfig(args[paramIdx+1], userConfig)\n else:\n # log error\n log.consoleOut(message)\n\n # this sets allowed days for the user\n elif adminCmd == \"--setalloweddays\":\n # check param len\n if paramLen != paramIdx + 3:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetAllowedDays(args[paramIdx+1], args[paramIdx+2])\n\n # this sets allowed hours per specified day or ALL for every day\n elif adminCmd == \"--setallowedhours\":\n # check param len\n if paramLen != paramIdx + 4:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetAllowedHours(args[paramIdx+1], args[paramIdx+2], args[paramIdx+3])\n\n # this sets time limits per allowed days\n elif adminCmd == \"--settimelimits\":\n # check param len\n if paramLen != paramIdx + 3:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetTimeLimits(args[paramIdx+1], args[paramIdx+2])\n\n # this sets time limits per week\n elif adminCmd == \"--settimelimitweek\":\n # check param len\n if paramLen != paramIdx + 3:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetTimeLimitWeek(args[paramIdx+1], args[paramIdx+2])\n\n # this sets time limits per month\n elif adminCmd == \"--settimelimitmonth\":\n # check param len\n if paramLen != paramIdx + 3:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetTimeLimitMonth(args[paramIdx+1], args[paramIdx+2])\n\n # this sets whether to track inactive user sessions\n elif adminCmd == \"--settrackinactive\":\n # check param len\n if paramLen != paramIdx + 3:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetTrackInactive(args[paramIdx+1], args[paramIdx+2])\n\n # this sets time left for the user at current moment\n elif adminCmd == \"--settimeleft\":\n # check param len\n if paramLen != paramIdx + 4:\n # fail\n adminCmdIncorrect = True\n else:\n # set days\n self.processSetTimeLeft(args[paramIdx+1], args[paramIdx+2], args[paramIdx+3])\n\n else:\n # out\n adminCmdIncorrect = True\n\n # check whether command is supported\n if (adminCmd not in cons.TK_USER_ADMIN_COMMANDS and adminCmd not in cons.TK_ADMIN_COMMANDS) or adminCmd == \"--help\" or adminCmdIncorrect:\n # fail\n if adminCmdIncorrect:\n log.consoleOut(msg.getTranslation(\"TK_MSG_CONSOLE_COMMAND_INCORRECT\"), *args)\n\n log.consoleOut(\"\\n\" + msg.getTranslation(\"TK_MSG_CONSOLE_USAGE_NOTES\"))\n # initial order\n cmds = [\"--help\", \"--userlist\", \"--userconfig\"]\n # print initial commands as first\n for rCmd in cmds:\n log.consoleOut(\" \", rCmd, cons.TK_USER_ADMIN_COMMANDS[rCmd])\n\n # put a little space in between\n log.consoleOut(\"\")\n\n # print help\n for rCmd, rCmdDesc in cons.TK_USER_ADMIN_COMMANDS.items():\n # do not print already known commands\n if rCmd not in cmds:\n log.consoleOut(\" \", rCmd, rCmdDesc)\n\n # --------------- parameter execution methods --------------- #\n\n def printUserList(self, pUserList):\n \"\"\"Format and print userlist\"\"\"\n # print to console\n log.consoleOut(msg.getTranslation(\"TK_MSG_CONSOLE_USERS_TOTAL\", len(pUserList)))\n # loop and print\n for rUser in pUserList:\n log.consoleOut(rUser)\n\n def printUserConfig(self, pUserName, pPrintUserConfig):\n \"\"\"Format and print user config\"\"\"\n # print to console\n log.consoleOut(msg.getTranslation(\"TK_MSG_CONSOLE_CONFIG_FOR\") % (pUserName))\n # loop and print the same format as ppl will use to set that\n for rUserKey, rUserConfig in pPrintUserConfig.items():\n # join the lists\n if \"ALLOWED_W\" in rUserKey or \"LIMITS_P\" in rUserKey:\n # print join\n log.consoleOut(\"%s: %s\" % (rUserKey, \";\".join(list(map(str, rUserConfig)))))\n # join the lists\n elif \"ALLOWED_H\" in rUserKey:\n # hrs\n hrs = \"\"\n # print join\n if len(rUserConfig) > 0:\n for rUserHour in sorted(list(map(int, rUserConfig))):\n # get config per hr\n hr = \"%s\" % (rUserHour) if rUserConfig[str(rUserHour)][cons.TK_CTRL_SMIN] <= 0 and rUserConfig[str(rUserHour)][cons.TK_CTRL_EMIN] >= 60 else \"%s[%s-%s]\" % (rUserHour, rUserConfig[str(rUserHour)][cons.TK_CTRL_SMIN], rUserConfig[str(rUserHour)][cons.TK_CTRL_EMIN])\n # empty\n if hrs == \"\":\n hrs = \"%s\" % (hr)\n else:\n hrs = \"%s;%s\" % (hrs, hr)\n\n log.consoleOut(\"%s: %s\" % (rUserKey, hrs))\n elif \"TRACK_IN\" in rUserKey:\n log.consoleOut(\"%s: %s\" % (rUserKey, bool(rUserConfig)))\n else:\n log.consoleOut(\"%s: %s\" % (rUserKey, str(rUserConfig)))\n\n def processSetAllowedDays(self, pUserName, pDayList):\n \"\"\"Process allowed days\"\"\"\n # defaults\n dayMap = ()\n result = 0\n\n # day map\n try:\n # try to parse parameters\n dayMap = list(map(int, pDayList.split(\";\")))\n except Exception as ex:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (str(ex))\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setAllowedDays(pUserName, dayMap)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n\n def processSetAllowedHours(self, pUserName, pDayNumber, pHourList):\n \"\"\"Process allowed hours\"\"\"\n # this is the dict for hour config\n allowedHours = {}\n result = 0\n\n # allowed hours\n try:\n # check hours\n for rHour in str(pHourList).split(\";\"):\n # verify hour\n hour = int(rHour.split(\"[\", 1)[0])\n # if we have advanced config (minutes)\n if \"[\" in rHour and \"]\" in rHour and \"-\" in rHour:\n # get minutes\n minutes = rHour.split(\"[\", 1)[1].split(\"]\")[0].split(\"-\")\n # verify minutes\n tmp = int(minutes[0])\n tmp = int(minutes[1])\n # get our dict done\n allowedHours[str(hour)] = {cons.TK_CTRL_SMIN: min(max(int(minutes[0]), 0), 60), cons.TK_CTRL_EMIN: min(max(int(minutes[1]), 0), 60)}\n else:\n # get our dict done\n allowedHours[str(hour)] = {cons.TK_CTRL_SMIN: 0, cons.TK_CTRL_EMIN: 60}\n except Exception as ex:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (str(ex))\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setAllowedHours(pUserName, pDayNumber, allowedHours)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n\n def processSetTimeLimits(self, pUserName, pDayLimits):\n \"\"\"Process time limits for days\"\"\"\n # defaults\n dayLimits = ()\n result = 0\n\n # day limists\n try:\n # try to parse parameters\n dayLimits = list(map(int, pDayLimits.split(\";\")))\n except Exception as ex:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (str(ex))\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setTimeLimitForDays(pUserName, dayLimits)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n\n def processSetTimeLimitWeek(self, pUserName, pTimeLimitWeek):\n \"\"\"Process time limits for week\"\"\"\n # defaults\n weekLimit = 0\n result = 0\n\n # week limit\n try:\n # try to parse parameters\n weekLimit = int(pTimeLimitWeek)\n except Exception as ex:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (str(ex))\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setTimeLimitForWeek(pUserName, weekLimit)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n\n def processSetTimeLimitMonth(self, pUserName, pTimeLimitMonth):\n \"\"\"Process time limits for month\"\"\"\n # defaults\n monthLimit = 0\n result = 0\n\n # week limit\n try:\n # try to parse parameters\n monthLimit = int(pTimeLimitMonth)\n except Exception as ex:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (str(ex))\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setTimeLimitForMonth(pUserName, monthLimit)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n\n def processSetTrackInactive(self, pUserName, pTrackInactive):\n \"\"\"Process track inactive\"\"\"\n # defaults\n trackInactive = None\n result = 0\n\n # check\n if pTrackInactive not in [\"true\", \"True\", \"TRUE\", \"false\", \"False\", \"FALSE\"]:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (\"please specify true or false\")\n else:\n trackInactive = True if pTrackInactive in [\"true\", \"True\", \"TRUE\"] else False\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setTrackInactive(pUserName, trackInactive)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n\n def processSetTimeLeft(self, pUserName, pOperation, pLimit):\n \"\"\"Process time left\"\"\"\n # defaults\n limit = 0\n result = 0\n\n # limit\n try:\n # try to parse parameters\n limit = int(pLimit)\n except Exception as ex:\n # fail\n result = -1\n message = msg.getTranslation(\"TK_MSG_PARSE_ERROR\") % (str(ex))\n\n # preprocess successful\n if result == 0:\n # invoke\n result, message = self._timekprAdminConnector.setTimeLeft(pUserName, pOperation, limit)\n\n # process\n if result != 0:\n # log error\n log.consoleOut(message)\n","sub_path":"client/admin/adminprocessor.py","file_name":"adminprocessor.py","file_ext":"py","file_size_in_byte":16989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"109722134","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 7 12:55:30 2018\n\n@author: Henry Tessier\n\"\"\"\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nimport numpy as np\nimport re\nimport random\nfrom collections import Counter\nimport seaborn as sns\n\n\n# Base url, and a lambda func to return url for a given year\nbase_url = 'http://kenpom.com/index.php'\nurl_year = lambda x: '%s?y=%s' % (base_url, str(x) if x != 2018 else base_url)\n\n# Create a method that parses a given year and spits out a raw dataframe\ndef import_raw_year(year):\n \n #Imports raw data from a ken pom year into a dataframe\n \n f = requests.get(url_year(year))\n soup = BeautifulSoup(f.text, \"lxml\")\n table_html = soup.find_all('table', {'id': 'ratings-table'})\n\n # Weird issue w/ in the html\n # Prevents us from just using pd.read_html\n # Let's find all the thead contents and just replace/remove them\n # This allows us to easily put the table row data into a dataframe using panda\n thead = table_html[0].find_all('thead')\n\n table = table_html[0]\n for x in thead:\n table = str(table).replace(str(x), '')\n\n df = pd.read_html(table)[0]\n df['year'] = year\n return df\n \n\n# Import all the years into a singular dataframe\ndf = None\npickyear = input(\"Enter Year (2002 - 2018): \")\nprint(\"\")\nprint(\"Gathering most recent statistics...\")\ndf = pd.concat( (df, import_raw_year(pickyear)), axis=0) \n\n# Column rename based off of original website\ndf.columns = ['Rank', 'Team', 'Conference', 'W-L', 'AdjEM', \n 'AdjustO', 'AdjustO Rank', 'AdjustD', 'AdjustD Rank',\n 'AdjustT', 'AdjustT Rank', 'Luck', 'Luck Rank', \n 'SOS_Pyth', 'SOS Pyth Rank', 'SOS OppO', 'SOS OppO Rank',\n 'SOS OppD', 'SOS OppD Rank', 'NCSOS Pyth', 'NCSOS Pyth Rank', 'Year']\n \n# Lambda that returns true if given string is a number and a valid seed number (1-16)\nvalid_seed = lambda x: True if str(x).replace(' ', '').isdigit() \\\n and int(x) > 0 and int(x) <= 16 else False\n\n# Use lambda to parse out seed/team\ndf['Seed'] = df['Team'].apply(lambda x: x[-2:].replace(' ', '') \\\n if valid_seed(x[-2:]) else np.nan )\n\ndf['Team'] = df['Team'].apply(lambda x: x[:-2] if valid_seed(x[-2:]) else x)\n\n# Split W-L column into wins and losses\ndf['Wins'] = df['W-L'].apply(lambda x: int(re.sub('-.*', '', x)) )\ndf['Losses'] = df['W-L'].apply(lambda x: int(re.sub('.*-', '', x)) )\ndf.drop('W-L', inplace=True, axis=1)\n\n\ndf=df[[ 'Year', 'Rank', 'Team', 'Conference', 'Wins', 'Losses', 'Seed','AdjEM', \n 'AdjustO', 'AdjustO Rank', 'AdjustD', 'AdjustD Rank',\n 'AdjustT', 'AdjustT Rank', 'Luck', 'Luck Rank', \n 'SOS_Pyth', 'SOS Pyth Rank', 'SOS OppO', 'SOS OppO Rank',\n 'SOS OppD', 'SOS OppD Rank', 'NCSOS Pyth', 'NCSOS Pyth Rank']]\n \ndf = df[['Team','Wins','Losses','AdjEM','SOS_Pyth']]\ndf.Team = df.Team.str.rstrip()\ndf.Team = df.Team.str.replace('\\s+', '_')\ndf.Team = df.Team.str.replace('.', '')\ndf.Team = df.Team.str.replace('&', '')\ndf.Team = df.Team.str.replace('\\'', '')\ndf['WLPercentage'] = df.Wins / (df.Losses + df.Wins)\ndf['Name'] = df.Team\ndf = df.set_index('Name')\n\n\n# ______________________Data Import Completed_________________________________\n\nprint(\"\")\nregion = {}\nx = 1\nwhile x < 17: \n region[\"Seed{0}\".format(x)] = input(\"Enter \"+str(x)+\" Seed Team: \")\n if (region[\"Seed{0}\".format(x)]) not in df.Team:\n print(x, \"seed team not found\")\n else:\n x += 1\n \n\ndef sim_game(Team1, Team2):\n #results = []\n #for x in range(reps): \n ELO1 = ((df.loc[Team1].AdjEM + 40) + ((df.loc[Team1].SOS_Pyth + 15) * df.loc[Team1].WLPercentage)) \n ELO2 = ((df.loc[Team2].AdjEM + 40) + ((df.loc[Team2].SOS_Pyth + 15) * df.loc[Team2].WLPercentage))\n m = ELO1 - ELO2\n A = (1/(1+10**(abs(m)/23)))\n odds = (1-A)\n if m < 0:\n odds = (1-odds)\n result = random.random() <= odds\n \n if result == True:\n return(Team1)\n else:\n return(Team2)\n \n\"\"\" \n#For running multiple simulations of 1 game rather than multiple simulations of 1 region\n\n results += [result]\n if results.count(True) > results.count(False):\n return(Team1)\n elif results.count(False) > results.count(True):\n return(Team2)\n else:\n if ELO1 > ELO2:\n return(Team1)\n else:\n return(Team2)\n\"\"\"\n\nreps = int(input('Enter number of tournaments to simulate: '))\n\n\n###################################\n###NCAA Tourney Region Simulator###\n###################################\n\nWinners = []\nRound1W = []\nRound2W = []\nRound3W = []\n\nfor x in range(reps):\n#Round 1\n Win1 = sim_game(region['Seed1'],region['Seed16'])\n Win2 = sim_game(region['Seed8'],region['Seed9'])\n Win3 = sim_game(region['Seed5'],region['Seed12'])\n Win4 = sim_game(region['Seed4'],region['Seed13'])\n Win5 = sim_game(region['Seed6'],region['Seed11'])\n Win6 = sim_game(region['Seed3'],region['Seed14'])\n Win7 = sim_game(region['Seed7'],region['Seed10'])\n Win8 = sim_game(region['Seed2'],region['Seed15'])\n Round1W += [Win1,Win2,Win3,Win4,Win5,Win6,Win7,Win8]\n\n#Round 2\n Win2_1 = sim_game(Win1,Win2)\n Win2_2 = sim_game(Win3,Win4)\n Win2_3 = sim_game(Win5,Win6)\n Win2_4 = sim_game(Win7,Win8)\n Round2W += [Win2_1,Win2_2,Win2_3,Win2_4]\n\n#Round 3\n Win3_1 = sim_game(Win2_1,Win2_2)\n Win3_2 = sim_game(Win2_3,Win2_4)\n Round3W += [Win3_1,Win3_2]\n\n#Round 4\n WinFF = sim_game(Win3_1,Win3_2)\n Winners += [WinFF]\n\n#Graph for final round winner\n\ntotwins = Counter(Winners)\nfor x in totwins:\n totwins[x] = totwins[x]/reps\n\nresults = pd.DataFrame(list(totwins.items()), columns=['Team', 'Win Share %'])\nresults['Team'] = results['Team'].str.replace('_', ' ')\nresults[\"Win Share %\"] = (results[\"Win Share %\"] * 100)\nresults = results.sort_values([\"Win Share %\"], ascending = False)\nOutput = sns.barplot(x = results[\"Win Share %\"], y = results[\"Team\"])\nOutput.set(xlabel = \"Projected Win Shares (%)\")\n#print(results)\n\n######### Data for all previous rounds ##########\n\nround1wins = Counter(Round1W)\nround2wins = Counter(Round2W)\nround3wins = Counter(Round3W)\n\nfor x in round3wins:\n round3wins[x] = round3wins[x]/reps\nfor x in round2wins:\n round2wins[x] = round2wins[x]/reps\nfor x in round1wins:\n round1wins[x] = round1wins[x]/reps\n\nresults3 = pd.DataFrame(list(round3wins.items()), columns=['Team', 'Win Share %'])\nresults3['Team'] = results3['Team'].str.replace('_', ' ')\nresults3[\"Win Share %\"] = (results3[\"Win Share %\"] * 100)\nresults3 = results3.sort_values([\"Win Share %\"], ascending = False)\n\nresults2 = pd.DataFrame(list(round2wins.items()), columns=['Team', 'Win Share %'])\nresults2['Team'] = results2['Team'].str.replace('_', ' ')\nresults2[\"Win Share %\"] = (results2[\"Win Share %\"] * 100)\nresults2 = results2.sort_values([\"Win Share %\"], ascending = False)\n\nresults1 = pd.DataFrame(list(round1wins.items()), columns=['Team', 'Win Share %'])\nresults1['Team'] = results1['Team'].str.replace('_', ' ')\nresults1[\"Win Share %\"] = (results1[\"Win Share %\"] * 100)\nresults1 = results1.sort_values([\"Win Share %\"], ascending = False)\n\nprint(\"\")\nprint(\"Make Final Four Probability:\")\nprint(results)\nprint(\"\")\nprint(\"Make Elite Eight Probability:\")\nprint(results3)\nprint(\"\")\nprint(\"Make Sweet 16 Probability:\")\nprint(results2)\nprint(\"\")\nprint(\"Make Second Round Probability:\")\nprint(results1)\n","sub_path":"BracketModel.py","file_name":"BracketModel.py","file_ext":"py","file_size_in_byte":7456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"359603367","text":"import re\n\nimport pandas as pd\n\nfrom config.common import log\nfrom egovResearch.egovScDoc.spiders.docSpider.base_spider import *\nfrom pyQwSciLib import app\nfrom wSpider.egovernment.egov_spider_lite.extra.common_utils import *\n\n\n# app = create_app()\n\ndef filter_special_words():\n \"\"\"\n 过滤特殊字符\n :return:\n \"\"\"\n item_list = EGOVSCPolicyPaper.query.all()\n for item in item_list:\n title = item.title\n title = title.replace(\"\\n\",\"\")\n title = title.replace(\"\",\"\")\n title = title.strip()\n item.title = title\n item.update()\n\n pass\n\n\"\"\"读取和更新政策的年份信息\"\"\"\ndef get_year():\n \"\"\"\n 读取年份\n :return:\n \"\"\"\n item_list = db.session.query(\n EGOVSCPolicyPaper.id,\n EGOVSCPolicyPaper.release_time,\n EGOVSCPolicyPaper.material_date,\n EGOVSCPolicyPaper.year\n ).filter(\n EGOVSCPolicyPaper.year == None\n ).all()\n print(len(list(item_list)))\n for elem in item_list:\n item_id = elem[0]\n release_time = elem[1]\n material_date = elem[2]\n year = elem[3]\n if year is None:\n item = EGOVSCPolicyPaper.query.filter(EGOVSCPolicyPaper.id==item_id).first()\n if item.year is None:\n print(item.release_time,\" \",item.material_date,\" \",item.year)\n # if item.release_time is not None and item.material_date == \"\":\n # item.material_date = item.release_time\n # item.year = item.release_time.split(\"-\")[0]\n # item.update()\n if item.release_time is not None:\n item.material_date = item.release_time\n item.year = item.material_date.split(\"-\")[0]\n item.update()\n\nwith open(\"key_words.txt\",\"r\",encoding=\"UTF-8\") as f:\n key_words = f.read().split(\"\\n\")\ndef batch_judge_if_title_have_key_words(title):\n for key_word in key_words:\n if key_word in title:\n return True\n return False\n\n\"\"\"默认过滤是否和电子政务相关\"\"\"\ndef get_egov_related_title():\n \"\"\"\n 过滤是否和电子政务相关\n :return:\n \"\"\"\n item_list = EGOVSCPolicyPaper.query_by_city_year_and_flag(None,None,0)\n for item in item_list:\n elem = EGOVSCPolicyPaper.query.filter(\n EGOVSCPolicyPaper.id == item.id\n ).first()\n if batch_judge_if_title_have_key_words(item.title):\n elem.flag = EGOVSCPolicyPaper.__FILE_FLAG_BATCH_VALIDATED__\n log.info(\"---------{}---------\".format(elem.title))\n else:\n if judge_if_title_have_key_words(item.title):\n elem.flag = EGOVSCPolicyPaper.__FILE_FLAG_VALIDATED__\n log.info(\"--{}--\".format(elem.title))\n else:\n elem.flag = EGOVSCPolicyPaper.__FILE_FLAG_DELETED__\n elem.update()\n pass\n\n\"\"\"二次过滤\"\"\"\ndef filter_egov_related_title():\n \"\"\"\n 二次过滤是否和电子政务相关\n :return:\n \"\"\"\n item_list = EGOVSCPolicyPaper.query_by_city_year_and_flag(\n None,None,EGOVSCPolicyPaper.__FILE_FLAG_VALIDATED__)\n print(len(item_list))\n for item in item_list:\n elem = EGOVSCPolicyPaper.query.filter(\n EGOVSCPolicyPaper.id == item.id\n ).first()\n if batch_judge_if_title_have_key_words(item.title):\n elem.flag = EGOVSCPolicyPaper.__FILE_FLAG_BATCH_VALIDATED__\n log.info(\"---------{}---------\".format(elem.title))\n elem.update()\n pass\n\n\"\"\"查看模糊月份\"\"\"\ndef get_indefinite_month():\n \"\"\"\n 查找月份模糊的File\n :return:\n \"\"\"\n item_list = EGOVSCPolicyPaper.query.filter(\n EGOVSCPolicyPaper.flag == EGOVSCPolicyPaper.__FILE_FLAG_ARCHIVED__\n ).all()\n for elem in item_list:\n print(elem.material_date)\n pass\n\n\"\"\"读取城市列表\"\"\"\ndef read_cities():\n \"\"\"\n 初始化城市列表\n :return:\n \"\"\"\n with open(\"cities.txt\",\"r\",encoding=\"utf-8\") as f:\n city_list = f.read().split(\"\\n\")\n for city in city_list:\n item = EGOVSCPolicyPapersCompare()\n city_item = EGOVProvinceCityInfo.query.filter(\n EGOVProvinceCityInfo.city == city\n ).first()\n if city_item is None:\n city_name = \"{}市\".format(city)\n city_item = EGOVProvinceCityInfo.query.filter(\n EGOVProvinceCityInfo.city == city_name\n ).first()\n item.city_id = city_item.id\n item.city = city\n item.city_name = city_item.city\n item.save()\n\nsheets_name = [\n \"省会城市政府网站服务能力.xlsx\", # 0\n \"省会城市政府微博服务能力.xlsx\",\n \"省会城市政府微信服务能力.xlsx\", # 2\n \"省会城市政府APP服务能力.xlsx\",\n \"省会城市政府双微服务能力.xlsx\", # 4\n \"省会城市政府新媒体服务能力.xlsx\",\n \"省会城市电子政务综合服务能力.xlsx\", # 6\n]\nsheet_name = sheets_name[5]\n\"\"\"读取测评报告数据\"\"\"\ndef read_egovsc_data():\n \"\"\"\n 读取Excel中的测评数据结果\n :return:\n \"\"\"\n base_dir = \"D:\\Documents\\QingwuDOC\\eGovernment\\省会城市政策文件分词\\Manuscript\\数据\\{}\"\n data_sheet = pd.read_excel(base_dir.format(sheet_name))\n for elem in data_sheet.iterrows():\n elem = elem[1]\n if not pd.isna(elem[\"省会城市\"]):\n item = EGOVSCPolicyPapersCompare.query.filter(\n EGOVSCPolicyPapersCompare.city == elem[\"省会城市\"]\n ).first()\n if item is None:\n item = EGOVSCPolicyPapersCompare.query.filter(\n EGOVSCPolicyPapersCompare.city_name == elem[\"省会城市\"]\n ).first()\n print(item.city_name)\n item.egovsc_new_media_2016 = elem[\"2016年\"] if not pd.isna(elem[\"2016年\"]) else 0\n item.egovsc_new_media_2017 = elem[\"2017年\"] if not pd.isna(elem[\"2017年\"]) else 0\n if float(\"%.2f\" % (item.egovsc_new_media_2017-item.egovsc_new_media_2016)) == float(\n \"%.2f\" % elem[\"变化情况\"]):\n print(elem[\"变化情况\"])\n item.egovsc_new_media_variation = elem[\"变化情况\"]\n else:\n raise Exception\n item.update()\n\n\"\"\"政府网站元数据灰色关联排序\"\"\"\ndef update_website_metadata_gray_index():\n \"\"\"\n 政府网站元数据灰色关联排序\n :return:\n \"\"\"\n data_sheet = pd.read_excel(\"D:\\Desktop\\元数据data.xlsx\")\n print(data_sheet)\n for elem in data_sheet.iterrows():\n elem = elem[1]\n if not pd.isna(elem[\"省会城市\"]):\n item = EGOVSCPolicyPapersCompare.query.filter(\n EGOVSCPolicyPapersCompare.city_name == elem[\"省会城市\"]\n ).first()\n if item is not None:\n print(item.city_name)\n item.website_metadata_gray_index = elem[\"gray_index\"]\n item.update()\n\n\"\"\"国家行政学院电子政务发展指数\"\"\"\ndef update_chinese_academy_of_governance_egdi():\n \"\"\"\n 国家行政学院电子政务发展指数\n :return:\n \"\"\"\n data_sheet = pd.read_excel(\n \"D:\\Documents\\QingwuDOC\\eGovernment\\省会城市政策文件分词\\Manuscript\\数据\\中国行政学院报告\\中国城市电子政务报告.xlsx\",\n sheet_name=\"2016\"\n )\n for elem in data_sheet.iterrows():\n elem = elem[1]\n if not pd.isna(elem[\"city_name\"]):\n item = EGOVSCPolicyPapersCompare.query.filter(\n EGOVSCPolicyPapersCompare.city_name == elem[\"city_name\"]\n ).first()\n if item is not None:\n print(item.city_name)\n item.ccps_egdi_online_service_2016 = elem[\"在线服务指数\"]\n item.update()\n\n\"\"\"转移省会城市数据库文件\"\"\"\ndef transfer_city_egov_files():\n \"\"\"\n 转移文件\n :return:\n \"\"\"\n item_list = EGOVSCPolicyPaper.query.filter(\n EGOVSCPolicyPaper.flag == EGOVSCPolicyPaper.__FILE_FLAG_ARCHIVED__\n ).all()\n for elem in item_list:\n item = EGOVSCPolicyPaperAnalysis()\n same_item = EGOVSCPolicyPaperAnalysis.query.filter(\n EGOVSCPolicyPaperAnalysis.file_title.like(\n elem.title\n )\n ).first()\n if same_item is not None:\n print(same_item.file_title)\n continue\n item.paper_id = elem.id\n item.file_title = elem.title\n item.file_content = elem.file_content\n item.city_id = elem.city_id\n item.city_name = elem.city_name\n\n time_strs = elem.material_date.split(\"-\")\n item.year_interval_str = \"{}.{}\".format(time_strs[0], int(time_strs[1]))\n item.source_flag = 0\n item.save()\n pass\n\"\"\"转移中央数据库文件\"\"\"\ndef transfer_council_egov_files():\n \"\"\"\n 转移中央文件\n :return:\n \"\"\"\n from pyQwSciLib.models import EGOVPolicyPaper\n from time import strftime,strptime\n item_list = EGOVPolicyPaper.query.filter(\n EGOVPolicyPaper.id >= 8560\n ).all()\n print(len(item_list))\n for elem in item_list:\n item = EGOVSCPolicyPaperAnalysis()\n same_item = EGOVSCPolicyPaperAnalysis.query.filter(\n EGOVSCPolicyPaperAnalysis.file_title.like(\n elem.title\n )\n ).first()\n if same_item is not None:\n print(same_item.file_title)\n continue\n item.paper_id = elem.id\n item.file_title = elem.title\n file_content = str(elem.file_content, encoding='utf-8')\n\n item.file_content = file_content\n item.city_id = elem.city_id\n item.city_name = elem.city_name\n\n struct_time = strptime(elem.time,u\"%Y年%m月%d日\")\n str_time = strftime(u\"%Y-%m-%d\",struct_time)\n time_strs = str_time.split(\"-\")\n item.year_interval_str = \"{}.{}\".format(time_strs[0], int(time_strs[1]))\n print(item.year_interval_str)\n item.source_flag = 0\n item.org_flag = 1\n item.save()\n pass\n\"\"\"读取本地搜集省会城市文件\"\"\"\ndef read_city_files_from_local():\n \"\"\"\n 读取本地文件存入数据库\n :return:\n \"\"\"\n base_dir = \"D:\\Desktop\\修改政策\\\\2011.7-2016.6\\省会城市\"\n city_list = os.listdir(base_dir)\n for city in city_list:\n city_item = EGOVProvinceCityInfo.query.filter(\n EGOVProvinceCityInfo.city == \"{}市\".format(city)\n ).first()\n city_dir = \"{}\\{}\".format(base_dir,city)\n paper_list = os.listdir(city_dir)\n for paper in paper_list:\n item = EGOVSCPolicyPaperAnalysis()\n paper_file_name = paper.replace(\".txt\", \"\")\n title_info = re.findall(\"(\\d+).(\\d+)\", paper_file_name)\n year_interval_str = \"{}.{}\".format(title_info[0][0],title_info[0][1])\n title = paper_file_name.replace(year_interval_str,\"\").strip()\n # print(title_info)\n # print(title)\n # print(year_interval_str)\n item.city_id = city_item.id\n item.city_name = city_item.city\n item.paper_id = 0\n\n item.file_title = title\n item.year_interval_str = year_interval_str\n item.source_flag = 1\n item.save()\n with open(\"{}\\{}\".format(\n city_dir, paper\n ), \"r\", encoding=\"GBK\",errors=\"ignore\") as fc:\n # print(fc.read())\n item.file_content = fc.read()\n res = item.update()\n if res is False:\n print(paper)\n pass\n\"\"\"读取本地搜集中央文件\"\"\"\ndef read_council_files_from_local():\n \"\"\"\n 读取本地中央文件存入数据库\n :return:\n \"\"\"\n # base_dir = \"D:\\Desktop\\修改政策\\\\2011.7-2016.6\\国务院\"\n base_dir = \"D:\\Desktop\\修改政策\\\\2016.7-2017.6\\国务院\"\n paper_list = os.listdir(base_dir)\n for paper in paper_list:\n item = EGOVSCPolicyPaperAnalysis()\n paper_file_name = paper.replace(\".txt\", \"\")\n title_info = re.findall(\"(\\d+).(\\d+)\", paper_file_name)\n year_interval_str = \"{}.{}\".format(title_info[0][0],title_info[0][1])\n title = paper_file_name.replace(year_interval_str,\"\").strip()\n\n same_item = EGOVSCPolicyPaperAnalysis.query.filter(\n EGOVSCPolicyPaperAnalysis.file_title.like(\n title\n )\n ).first()\n if same_item is not None:\n print(same_item.file_title)\n continue\n\n item.city_id = 1\n item.city_name = \"国务院\"\n item.paper_id = 0\n\n item.file_title = title\n item.year_interval_str = year_interval_str\n item.source_flag = 1\n item.save()\n with open(\"{}\\{}\".format(\n base_dir, paper\n ), \"r\", encoding=\"GBK\",errors=\"ignore\") as fc:\n # print(fc.read())\n item.file_content = fc.read()\n\n res = item.update()\n if res is False:\n print(paper)\n pass\n\nyear_intervals = [\n \"2017.7之后\", # 0\n \"2016.7-2017.6\", # 1\n \"2015.7-2016.6\", # 2\n \"2014.7-2015.6\", # 3\n \"2013.7-2014.6\", # 4\n \"2012.7-2013.6\", # 5\n \"2011.7-2012.6\", # 6 # \"2011.6之前\" # 7\n \"2010.7-2011.6\", # 7\n \"2009.7-2010.6\", # 8\n \"2009.6之前\", # 9\n]\n\"\"\"更新年份区间\"\"\"\ndef update_year_interval():\n \"\"\"\n 更新年份区间\n :return:\n \"\"\"\n\n # id_list = db.session.query(EGOVSCPolicyPaper.id).all()\n # print(len(id_list))\n # for item_id in id_list:\n # item = EGOVSCPolicyPaper.query.filter(EGOVSCPolicyPaper.id == item_id).first()\n # print(item.id)\n # year_interval = item.material_date.split(\"-\")\n\n item_list = EGOVSCPolicyPaperAnalysis.query.filter(\n EGOVSCPolicyPaperAnalysis.org_flag == 1\n ).all()\n print(len(item_list))\n for item in item_list:\n year_interval = item.year_interval_str.split(\".\")\n year = int(year_interval[0])\n month = int(year_interval[1])\n if year >= 2018:\n item.year_interval = 0\n elif year < 2009:\n item.year_interval = 9\n else:\n if month <= 6:\n item.year_interval = 2018 - year\n else:\n item.year_interval = 2018 - year - 1\n item.update()\n\nconfigs = [\n {\n \"year\": 2014,\n \"year_interval_start\": 3,\n \"loop_minuend\": 10\n },\n {\n \"year\": 2015,\n \"year_interval_start\": 2,\n \"loop_minuend\": 9\n },\n {\n \"year\": 2016,\n \"year_interval_start\": 1,\n \"loop_minuend\": 8\n },\n {\n \"year\": 2017,\n \"year_interval_start\": 0,\n \"loop_minuend\": 7\n }\n]\ncount_configs = [\n # {\n # \"count_str\":\"counts\"\n # },\n {\n \"count_str\":\"total_counts\"\n }\n]\n\n\"\"\"更新文件数量\"\"\"\ndef update_file_counts():\n \"\"\"\n 更新文件数量(此处文件是指跟电子政务有关的文件)\n 更新文件总数,此处文件是指省会城市的所有文件\n :return:\n \"\"\"\n for count_config in count_configs:\n for config in configs:\n if count_config[\"count_str\"] == \"counts\":\n city_list = EGOVSCPolicyPaperAnalysis.query.all()\n item_list = EGOVSCPolicyPaperAnalysis.query.filter(\n EGOVSCPolicyPaperAnalysis.year_interval > config[\"year_interval_start\"]\n ).all()\n else:\n city_list = EGOVSCPolicyPaper.query.all()\n print(len(city_list))\n item_list = EGOVSCPolicyPaper.query.filter(\n EGOVSCPolicyPaper.year_interval > config[\"year_interval_start\"]\n ).all()\n print(len(item_list))\n\n file_year_city_list = []\n city_dicts = {}\n for city in city_list:\n city_dicts[city.city_id] = city.city_name\n for i in range(1, 7): # 一共5+1个回溯期\n file_year_city_list.append({})\n for city in city_list:\n file_year_city_list[i-1][city.city_id] = []\n\n for item in item_list:\n file_content = item.file_content\n for i in range(config[\"loop_minuend\"]-item.year_interval):\n file_year_city_list[5-i][item.city_id].append(file_content)\n if item.year_interval - config[\"year_interval_start\"] > 6: # 1 2 3 4 5 6\n file_year_city_list[5][item.city_id].append(file_content)\n\n for index, year_list in enumerate(file_year_city_list):\n for city_id, file_list in year_list.items():\n egovsc_compare_item = EGOVSCPolicyPapersCompare.query.filter(\n EGOVSCPolicyPapersCompare.city_id == city_id\n ).first()\n if egovsc_compare_item is not None:\n if egovsc_compare_item.city_name == city_dicts[city_id]:\n print(city_dicts[city_id],\"recall:\",index,len(file_list))\n setattr(egovsc_compare_item,\n \"policy_{}_{}_recall_{}\".format(\n count_config[\"count_str\"],\n config[\"year\"],\n index+1\n ),\n len(file_list)\n )\n egovsc_compare_item.update()\n else:\n raise Exception\n\n\"\"\"读取并输出文件数量\"\"\"\ndef output_file_counts():\n \"\"\"\n 文件数量(此处文件是指跟电子政务有关的文件)\n 文件总数,此处文件是指省会城市的所有文件\n :return:\n \"\"\"\n writer = pd.ExcelWriter(\"D:\\\\Desktop\\\\data.xlsx\")\n city_list = EGOVSCPolicyPaperAnalysis.query.all()\n\n city_dicts = {}\n for city in city_list:\n city_dicts[city.city_id] = city.city_name\n\n def sum_file_counts(df,item_list):\n for index, city in enumerate(city_dicts.items()):\n df.loc[index, \"城市\"] = city[1]\n for i in range(0,8): # 一共8个年份\n df.loc[index, \"{}\".format(i+2)] = 0\n for item in item_list:\n city_index = df[(df[\"城市\"] == item.city_name)].index[0]\n df.loc[city_index,\"{}\".format(item.year_interval)] += 1\n df.columns = [\"省会城市\"] + year_intervals[2:]\n\n egov_item_list = EGOVSCPolicyPaperAnalysis.query.filter(\n EGOVSCPolicyPaperAnalysis.year_interval > 1\n ).all()\n total_item_list = []\n total_item_list_res = db.session.query(\n EGOVSCPolicyPaper.id,\n EGOVSCPolicyPaper.year_interval,\n EGOVSCPolicyPaper.city_name\n ).filter(\n EGOVSCPolicyPaper.year_interval > 1\n ).all()\n print(len(total_item_list_res))\n for elem in total_item_list_res:\n item = EGOVSCPolicyPaper()\n item.year_interval = elem[1]\n item.city_name = elem[2]\n total_item_list.append(item)\n df_egov = pd.DataFrame()\n df_total = pd.DataFrame()\n sum_file_counts(df_egov,egov_item_list)\n sum_file_counts(df_total,total_item_list)\n df_egov.to_excel(writer,\"EGOV\",index=None)\n df_total.to_excel(writer,\"TOTAL\",index=None)\n writer.save()\n\nogd_key_words = [\n # \"数据开放\",\n \"政务公开\",\n \"信息公开\",\n # \"大数据行动\",\n # \"大数据发展\",\n \"申请公开\"\n]\ndef filter_ogd_papers():\n item_list = EGOVSCPolicyPaper.query.filter(\n EGOVSCPolicyPaper.flag == 6 ,EGOVSCPolicyPaper.year_interval > 0).all()\n print(len(item_list))\n item_list = EGOVSCPolicyPaper.query.filter(EGOVSCPolicyPaper.flag == 6).all()\n counter = 0\n for item in item_list:\n for word in ogd_key_words:\n if word in item.title:\n print(item.title)\n counter += 1\n # item.flag = EGOVSCPolicyPaper.__FILE_FLAG_OGD__\n # item.update()\n break\n print(len(item_list))\n print(counter)\n pass\n\nfield_list = [\n\n]\nif __name__ == '__main__':\n with app.app_context():\n # output_file_counts()\n\n # query = db.session.query(EGOVSCPolicyPapersCompare)\n # df = pd.read_sql(query.statement, query.session.bind)\n # df.to_excel(\"D:\\\\Desktop\\\\xlsxdata.xlsx\")\n\n filter_ogd_papers()\n pass\n","sub_path":"egovResearch/egovScDoc/scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":20574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"49212279","text":"import json\nimport pickle\nimport shutil\n\nimport pandas as pd\nimport sklearn.datasets\nimport random\nimport os\nimport uuid\nimport uuid as myuuid\nfrom river import compose\nfrom river import linear_model\nfrom river import metrics\nfrom river import preprocessing\n\nimport time\nfrom confluent_kafka import Producer, Consumer, KafkaException, KafkaError, TopicPartition\nimport certifi\n\ndef predict():\n current_model_path = os.path.join(app_config['root_folder'], app_config['models_sub_folder'], app_config['latest_version'],\n app_config['model_f_name'])\n\n md=pd.read_pickle(current_model_path)\n model =md['model']\n\n consumer = get_kafka_consumer()\n producer = get_kafka_producer()\n while (True):\n msg = consumer.poll(timeout=1.0)\n if msg is None: continue\n\n\n message = json.loads(msg.value().decode(\"utf-8\"))\n message['y_hat']=model.predict_one(message['x'])\n producer.produce(y_cap_topic,message)\n producer.flush()\n\n uuid = message['uuid']\n with open(os.path.join(app_config['root_folder'],app_config['raw_data_folder'],app_config['data_sub_folder'],uuid),'w') as f:\n f.write(json.dumps(message))\n\n\ndef get_kafka_consumer():\n curdir = os.getcwd()\n config_dir = curdir + '/../config/config.json'\n kafka_config = json.load(open(config_dir))\n kafka_consumer_config = kafka_config\n kafka_consumer_config['group.id'] = 'prediction-x-1'\n kafka_consumer_config['auto.offset.reset'] = 'earliest'\n consumer = Consumer(kafka_consumer_config)\n\n tls = [TopicPartition(x_topic, 0),TopicPartition(x_topic, 1),TopicPartition(x_topic, 2),TopicPartition(x_topic, 3)]\n consumer.assign(tls)\n return consumer\n\ndef get_kafka_producer():\n curdir = os.getcwd()\n config_dir = curdir + '/../config/config.json'\n kafka_config = json.load(open(config_dir))\n kafka_config['ssl.ca.location'] = certifi.where()\n kafka_config['client.id'] = 'test-sw-1'\n producer = Producer(kafka_config)\n return producer\n\n\n\napp_config = json.load(open(\"../config/app_config.json\"))\nx_topic='X'\ny_cap_topic='X_Y_CAP'\n\nif __name__ == '__main__':\n print('Start consuming x-data')\n predict()\n '''\n data_folder = root_folder + data_sub_folder\n truth_folder = root_folder + truth_sub_folder\n datasets_folder = root_folder + datasets_sub_folder\n dataset_metadata_config = root_folder + dataset_metadata_config_file\n model_metadata_config = root_folder + model_metadata_config_file\n print('Initializing')\n initialize()\n '''\n #create_initial_data()\n #gen_data(data_folder,truth_folder)\n #create_versioned_data(dataset_metadata_config,truth_folder,data_folder,datasets_folder)\n #create_versioned_model()","sub_path":"src/model_inference_api.py","file_name":"model_inference_api.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"380427632","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/5/21 14:03\n# @Author : Gavin\n\nimport redis\nimport logging\nlogger = logging.getLogger('InsertRequest')\n\n\ndef InsertRequest(url, type):\n try:\n r = redis.Redis(host='127.0.0.1', port=6379, db=0)\n if type == 0:\n r.lpush('ZhiLianCrawl:requests', url)\n if type == 1:\n r.lpush('ZhuoPinCrawl:requests', url)\n if type == 2:\n r.lpush('BossCrawl:requests', url)\n if type == 3:\n r.lpush('ChinaHRCrawl:requests', url)\n except:\n logger.info(\"Redis open failed!!!\")\n\n","sub_path":"code/RecruitmentMaster/RecruitmentMaster/src/InsertRedis.py","file_name":"InsertRedis.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"123726437","text":"def _pie(self, kwargs):\n\n\tkwargs['colors'] = kwargs.get('colors', self.colors)\n\tkwargs['colors'] = kwargs['colors'] + (len(kwargs['values'])-len(kwargs['colors']))*['#000000']\n\n\tdata = dict(\n\t\ttype = 'pie',\n\t\tvalues = kwargs['values'],\n\t\tlabels = kwargs.get('labels', ['']*len(kwargs['values'])),\n\t\ttextinfo = kwargs.get('textinfo', 'none'),\n\t\tmarker = dict(colors=kwargs['colors']),\n\t\thole = kwargs.get('hole', 0),\n\t\tdirection =kwargs.get('direction', 'clockwise'),\n\t\tsort = kwargs.get('sort', False),\n\t)\n\tself.data.append(data)\n\n\tkwargs['width'] = kwargs.get('width', 600)\n\t#self.layout.update(dict())\n\n\treturn kwargs","sub_path":"plotlywrapper/_pie.py","file_name":"_pie.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"114832787","text":"# coding=utf-8\n\"\"\"\nInternal tools for NimLime development & testing.\n\"\"\"\nfrom pprint import pformat\n\nimport sublime\nfrom nimlime_core import configuration\n\ntry:\n from cProfile import Profile\nexcept ImportError:\n from profile import Profile\nfrom functools import wraps\nfrom pstats import Stats\n\ntry:\n from StringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\ndebug_on = False\nif debug_on:\n sublime.message_dialog('NimLime running in debug mode.')\n\n\n# Debug printer\ndef debug_print(*args):\n \"\"\"\n Print when debugging.\n :type args: Any\n \"\"\"\n if configuration.in_debug_mode:\n res = []\n for o in args:\n if isinstance(o, str):\n res.append(o)\n else:\n res.append(pformat(o))\n print(''.join(res))\n\n\n# Profiling functions\nprofiler = Profile()\nprofiler_running = False\n\n\ndef profile_func(func):\n \"\"\"\n Decorator which profiles a single function.\n Call print_profile_data to print the collected data.\n :type func: Callable\n :rtype: Callable\n \"\"\"\n\n @wraps(func)\n def _profile_wrapper(*args, **kwargs):\n global profiler_running\n if not profiler_running:\n profiler_running = True\n try:\n profiler.enable()\n return func(*args, **kwargs)\n finally:\n profiler.disable()\n profiler_running = False\n\n return _profile_wrapper\n\n\ndef print_profile_data():\n \"\"\"\n Print the collected profile data.\n \"\"\"\n stream = StringIO()\n statistics = Stats(profiler, stream=stream)\n statistics.sort_stats('cumulative')\n statistics.print_stats()\n print(stream.getvalue())\n","sub_path":"nimlime_core/utils/internal_tools.py","file_name":"internal_tools.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"394830621","text":"import os\nimport nibabel as nib\nimport numpy as np\nimport pickle\n\n#folders = [\"..\\\\Calgary_PS_DTI_Dataset\\\\\", \"..\\\\b2000\\\\\"]\nfolders = [\"../Calgary_PS_DTI_Dataset/\"]\nniiFiles = list()\nsNames = dict()\nfor folder in folders:\n for dirpaths, dirs, files in os.walk(folder):\n for file in files:\n if file.endswith('.nii'):\n filePath = os.path.join(dirpaths, file)\n niiFiles.append(filePath)\n sEnd = file.rfind('_')\n if sEnd == -1:\n sEnd = len(file)-4\n sName = file[0:sEnd]\n sNames[filePath] = sName\n \nmaxVals = dict()\ncount = 0\nfor file in niiFiles:\n count+=1\n sName = sNames[file]\n print(file, sName, count)\n nii = nib.load(file)\n data = nii.get_fdata()\n for vol in range(35):\n maxVal = np.max(data[:,:,:,vol])\n maxVals[sName, vol] = maxVal\n#%%\nwith open('maxVals.pickle', 'wb+') as f:\n pickle.dump(maxVals, f)","sub_path":"CNN/MaxGenerator.py","file_name":"MaxGenerator.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"111663054","text":"# DistRDF version of the RDataFrame benchmark df104\n# - Used DistRDF RDataFrame constructor for Spark\n# - Added npartitions parameter for Spark RDataFrame constructor\n# - Replaced generator by list in RDataFrame construction (the former is not supported by DistRDF yet)\n# - Removed RunGraphs execution option\n# - Replaced use of TH1DModel by a tuple (CppWorkflow does not support the former yet)\n\nimport os\nimport ROOT\n\ndistributed = ROOT.RDF.Experimental.Distributed\nRDataFrame = distributed.Spark.RDataFrame\n\ndef initialize():\n # Compile a function to compute the invariant mass of the diphoton system\n ROOT.gInterpreter.Declare(\n \"\"\"\n #ifndef df104_HiggsToTwoPhotons\n #define df104_HiggsToTwoPhotons\n using Vec_t = const ROOT::VecOps::RVec;\n float ComputeInvariantMass(Vec_t& pt, Vec_t& eta, Vec_t& phi, Vec_t& e) {\n ROOT::Math::PtEtaPhiEVector p1(pt[0], eta[0], phi[0], e[0]);\n ROOT::Math::PtEtaPhiEVector p2(pt[1], eta[1], phi[1], e[1]);\n return (p1 + p2).mass() / 1000.0;\n }\n #endif\n \"\"\")\n\ndef run(path, npartitions):\n # Register initialization function\n distributed.initialize(initialize)\n\n # Create a ROOT dataframe for each dataset\n df = {}\n df[\"data\"] = RDataFrame(\"mini\", [os.path.join(path, \"data_{}.GamGam.root\".format(x)) for x in (\"A\", \"B\", \"C\", \"D\")]*10, npartitions=npartitions)\n df[\"ggH\"] = RDataFrame(\"mini\", [os.path.join(path, \"mc_343981.ggH125_gamgam.GamGam.root\")]*10, npartitions=npartitions)\n df[\"VBF\"] = RDataFrame(\"mini\", [os.path.join(path, \"mc_345041.VBFH125_gamgam.GamGam.root\")]*10, npartitions=npartitions)\n processes = list(df.keys())\n\n # Apply scale factors and MC weight for simulated events and a weight of 1 for the data\n for p in [\"ggH\", \"VBF\"]:\n df[p] = df[p].Define(\"weight\",\n \"scaleFactor_PHOTON * scaleFactor_PhotonTRIGGER * scaleFactor_PILEUP * mcWeight\");\n df[\"data\"] = df[\"data\"].Define(\"weight\", \"1.0\")\n\n # Select the events for the analysis\n for p in processes:\n # Apply preselection cut on photon trigger\n df[p] = df[p].Filter(\"trigP\")\n\n # Find two good muons with tight ID, pt > 25 GeV and not in the transition region between barrel and encap\n df[p] = df[p].Define(\"goodphotons\", \"photon_isTightID && (photon_pt > 25000) && (abs(photon_eta) < 2.37) && ((abs(photon_eta) < 1.37) || (abs(photon_eta) > 1.52))\")\\\n .Filter(\"Sum(goodphotons) == 2\")\n\n # Take only isolated photons\n df[p] = df[p].Filter(\"Sum(photon_ptcone30[goodphotons] / photon_pt[goodphotons] < 0.065) == 2\")\\\n .Filter(\"Sum(photon_etcone20[goodphotons] / photon_pt[goodphotons] < 0.065) == 2\")\n\n # Define a new column with the invariant mass and perform final event selection\n hists = {}\n for p in processes:\n # Make four vectors and compute invariant mass\n df[p] = df[p].Define(\"m_yy\", \"ComputeInvariantMass(photon_pt[goodphotons], photon_eta[goodphotons], photon_phi[goodphotons], photon_E[goodphotons])\")\n\n # Make additional kinematic cuts and select mass window\n df[p] = df[p].Filter(\"photon_pt[goodphotons][0] / 1000.0 / m_yy > 0.35\")\\\n .Filter(\"photon_pt[goodphotons][1] / 1000.0 / m_yy > 0.25\")\\\n .Filter(\"m_yy > 105 && m_yy < 160\")\n\n # Book histogram of the invariant mass with this selection\n hists[p] = df[p].Histo1D(\n (p, \"Diphoton invariant mass; m_{#gamma#gamma} [GeV];Events\", 30, 105, 160),\n \"m_yy\", \"weight\")\n\n # Run the event loop\n # Time also event loops at this stage\n watch = ROOT.TStopwatch()\n ggh = hists[\"ggH\"].GetValue()\n elapsed_ggh = watch.RealTime()\n print(\"\\tEvent loop ggh:\", elapsed_ggh, \"s\")\n watch.Start()\n vbf = hists[\"VBF\"].GetValue()\n elapsed_vbf = watch.RealTime()\n print(\"\\tEvent loop vbf:\", elapsed_vbf, \"s\")\n watch.Start()\n data = hists[\"data\"].GetValue()\n elapsed_data = watch.RealTime()\n print(\"\\tEvent loop data:\", elapsed_data, \"s\")\n\n # Create the plot\n\n # Set styles\n ROOT.gROOT.SetStyle(\"ATLAS\")\n\n # Create canvas with pads for main plot and data/MC ratio\n c = ROOT.TCanvas(\"c\", \"\", 700, 750)\n\n upper_pad = ROOT.TPad(\"upper_pad\", \"\", 0, 0.35, 1, 1)\n lower_pad = ROOT.TPad(\"lower_pad\", \"\", 0, 0, 1, 0.35)\n for p in [upper_pad, lower_pad]:\n p.SetLeftMargin(0.14)\n p.SetRightMargin(0.05)\n p.SetTickx(False)\n p.SetTicky(False)\n upper_pad.SetBottomMargin(0)\n lower_pad.SetTopMargin(0)\n lower_pad.SetBottomMargin(0.3)\n\n upper_pad.Draw()\n lower_pad.Draw()\n\n # Fit signal + background model to data\n upper_pad.cd()\n fit = ROOT.TF1(\"fit\", \"([0]+[1]*x+[2]*x^2+[3]*x^3)+[4]*exp(-0.5*((x-[5])/[6])^2)\", 105, 160)\n fit.FixParameter(5, 125.0)\n fit.FixParameter(4, 119.1)\n fit.FixParameter(6, 2.39)\n fit.SetLineColor(2)\n fit.SetLineStyle(1)\n fit.SetLineWidth(2)\n data.Fit(\"fit\", \"\", \"E SAME\", 105, 160)\n fit.Draw(\"SAME\")\n\n # Draw background\n bkg = ROOT.TF1(\"bkg\", \"([0]+[1]*x+[2]*x^2+[3]*x^3)\", 105, 160)\n for i in range(4):\n bkg.SetParameter(i, fit.GetParameter(i))\n bkg.SetLineColor(4)\n bkg.SetLineStyle(2)\n bkg.SetLineWidth(2)\n bkg.Draw(\"SAME\")\n\n # Draw data\n data.SetMarkerStyle(20)\n data.SetMarkerSize(1.2)\n data.SetLineWidth(2)\n data.SetLineColor(ROOT.kBlack)\n data.Draw(\"E SAME\")\n data.SetMinimum(1e-3)\n data.SetMaximum(8e3)\n data.GetYaxis().SetLabelSize(0.045)\n data.GetYaxis().SetTitleSize(0.05)\n data.SetStats(0)\n data.SetTitle(\"\")\n\n # Scale simulated events with luminosity * cross-section / sum of weights\n # and merge to single Higgs signal\n lumi = 10064.0\n ggh.Scale(lumi * 0.102 / 55922617.6297)\n vbf.Scale(lumi * 0.008518764 / 3441426.13711)\n higgs = ggh.Clone()\n higgs.Add(vbf)\n higgs.Draw(\"HIST SAME\")\n\n # Draw ratio\n lower_pad.cd()\n\n ratiobkg = ROOT.TF1(\"zero\", \"0\", 105, 160)\n ratiobkg.SetLineColor(4)\n ratiobkg.SetLineStyle(2)\n ratiobkg.SetLineWidth(2)\n ratiobkg.SetMinimum(-125)\n ratiobkg.SetMaximum(250)\n ratiobkg.GetXaxis().SetLabelSize(0.08)\n ratiobkg.GetXaxis().SetTitleSize(0.12)\n ratiobkg.GetXaxis().SetTitleOffset(1.0)\n ratiobkg.GetYaxis().SetLabelSize(0.08)\n ratiobkg.GetYaxis().SetTitleSize(0.09)\n ratiobkg.GetYaxis().SetTitle(\"Data - Bkg.\")\n ratiobkg.GetYaxis().CenterTitle()\n ratiobkg.GetYaxis().SetTitleOffset(0.7)\n ratiobkg.GetYaxis().SetNdivisions(503, False)\n ratiobkg.GetYaxis().ChangeLabel(-1, -1, 0)\n ratiobkg.GetXaxis().SetTitle(\"m_{#gamma#gamma} [GeV]\")\n ratiobkg.Draw()\n\n ratiosig = ROOT.TH1F(\"ratiosig\", \"ratiosig\", 5500, 105, 160)\n ratiosig.Eval(fit)\n ratiosig.SetLineColor(2)\n ratiosig.SetLineStyle(1)\n ratiosig.SetLineWidth(2)\n ratiosig.Add(bkg, -1)\n ratiosig.Draw(\"SAME\")\n\n ratiodata = data.Clone()\n ratiodata.Add(bkg, -1)\n ratiodata.Draw(\"E SAME\")\n for i in range(1, data.GetNbinsX()):\n ratiodata.SetBinError(i, data.GetBinError(i))\n\n # Add legend\n upper_pad.cd()\n legend = ROOT.TLegend(0.55, 0.55, 0.89, 0.85)\n legend.SetTextFont(42)\n legend.SetFillStyle(0)\n legend.SetBorderSize(0)\n legend.SetTextSize(0.05)\n legend.SetTextAlign(32)\n legend.AddEntry(data, \"Data\" ,\"lep\")\n legend.AddEntry(bkg, \"Background\", \"l\")\n legend.AddEntry(fit, \"Signal + Bkg.\", \"l\")\n legend.AddEntry(higgs, \"Signal\", \"l\")\n legend.Draw(\"SAME\")\n\n # Add ATLAS label\n text = ROOT.TLatex()\n text.SetNDC()\n text.SetTextFont(72)\n text.SetTextSize(0.05)\n text.DrawLatex(0.18, 0.84, \"ATLAS\")\n text.SetTextFont(42)\n text.DrawLatex(0.18 + 0.13, 0.84, \"Open Data\")\n text.SetTextSize(0.04)\n text.DrawLatex(0.18, 0.78, \"#sqrt{s} = 13 TeV, 10 fb^{-1}\");\n\n # Save the plot\n c.SaveAs(\"HiggsToTwoPhotons.pdf\");\n","sub_path":"benchmarks/df104_HiggsToTwoPhotons_10xdata.py","file_name":"df104_HiggsToTwoPhotons_10xdata.py","file_ext":"py","file_size_in_byte":7887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"209477204","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\n#importing datasets and executing basic operations on them\n\ndf1 = pd.read_csv(r\"C:\\Users\\user\\Downloads\\Datasets\\IMDB_title_basics\\data.tsv\", sep='\\t', \n dtype={'genres':str, 'startYear':str})\n\ndf2 = df1[['tconst', 'primaryTitle', 'genres', 'startYear','titleType']]\n\ndf3 = pd.read_csv(r\"C:\\Users\\user\\Downloads\\Datasets\\IMDB_title_ratings\\data.tsv\", delim_whitespace=True, \n dtype={'averageRating':float, 'numVotes':int})\n\ndf_SEnumbers = pd.read_csv(r\"C:\\Users\\user\\Downloads\\Datasets\\IMDB_TVSeries\\data.tsv\", delim_whitespace=True,\n dtype={'seasonNumber':str, 'episodeNumber':str})\ndfs = pd.merge(df2, df3)\ndf_without_na = dfs.dropna()\ndfs2 = pd.merge(dfs, df_SEnumbers)\n\n#creating dataframes for movies and tv episodes, filtering data\n\nmovies = df_without_na.drop(df_without_na[df_without_na.titleType != 'movie'].index)\nSciFiMovies = movies[movies.genres.str.contains('Sci-Fi') & (movies.numVotes >= 1000) & (movies.averageRating >= 7)]\npacked_SFM = SciFiMovies.drop(['tconst', 'genres', 'startYear', 'titleType'], axis=1)\nsortedSFM = packed_SFM.sort_values(by='averageRating', ascending=False)\nfinalSFM = sortedSFM.set_index('primaryTitle')\nSFM_rating_count = finalSFM['averageRating'].value_counts().sort_index()\n\ntv_df = pd.merge(df_without_na, df_SEnumbers)\ntv_df = tv_df.drop(tv_df[tv_df.titleType == 'tvMovie'].index)\ntv_df_without_na = tv_df.drop(tv_df[(tv_df.seasonNumber == r'\\N') | (tv_df.episodeNumber == r'\\N')].index)\nSciFiTV = tv_df_without_na[tv_df_without_na.genres.str.contains('Sci-Fi') & (tv_df_without_na.numVotes >= 1000) & \\\n (tv_df_without_na.averageRating >= 7)]\nSciFiTV = SciFiTV.drop(['tconst', 'startYear', 'titleType', 'parentTconst', 'genres'], axis=1)\nsortedSFTV = SciFiTV.sort_values(by='averageRating', ascending=False)\nfinalSFTV = sortedSFTV.set_index('primaryTitle')\nSFTV_rating_count = finalSFTV['averageRating'].value_counts().sort_index()\n\n#gathering info to show it on plot\n\nSFM_text = \"\"\nfor i in range(10):\n SFM_text += \"%i. %s avg.rate: %.1f \\n\" % (i+1, finalSFM.index[i], finalSFM['averageRating'][i])\nSFM_final_text = (\"Top 10 rated Sci-Fi movies ever:\\n\") + (SFM_text)\n\nSFTV_text = \"\"\nfor i in range(10):\n SFTV_text += \"%i. %s (S%s E%s) avg.rate: %.1f \\n\" % (i+1, finalSFTV.index[i], finalSFTV['seasonNumber'][i], \n finalSFTV['episodeNumber'][i], finalSFTV['averageRating'][i]) \nSFTV_final_text = (\"\\nTop 10 rated Sci-Fi episodes ever:\\n\") + (SFTV_text)\n\nfinal_text = SFM_final_text + SFTV_final_text\n\n#creating the plot\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nx = [x * 0.1 for x in range(70,100)]\ny_m = SFM_rating_count\ny_tv = SFTV_rating_count\nax.bar(y_m.index, y_m, width=-0.025, align='edge', label='Movies')\nax.bar(y_tv.index, y_tv, width=0.025, align='edge', label='TV Episodes')\nax.legend(loc='upper left', fontsize=15)\nax.set_title(\"Sci-Fi Movies / TV Episodes from IMDB database with over 1 000 ratings\", fontsize=15)\nax.set_xlabel('User rating', fontsize=15)\nax.set_ylabel('Number of movies / TV Episodes which received the rating', fontsize =15)\nax.set_yticks(range(0,90,5))\nax.set_xticks([x*0.1 for x in range(70,100)])\nax.set_xlim(left=6.9, right=10.0)\nax.text(9.23, 38, final_text, color='black', bbox=dict(edgecolor='grey', facecolor='white', \n boxstyle='round'), fontsize=11)\nax.yaxis.grid(True, linestyle='--')\nax.set_axisbelow(True)\n\nplt.show()\n\n#not used methods, helpful in different scenarios\n\n\"\"\"\nplt.gcf().subplots_adjust(bottom=1, top=1, left=1, right=1)\nymin, ymax = ax.get_ylim()\nxmin, xmax = ax.get_xlim()\nprint(xmin, xmax, ymin, ymax)\nfig.set_tight_layout(False)\n\"\"\"","sub_path":"comparison.py","file_name":"comparison.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"544762","text":"import numpy as np\nimport pywavefront\nfrom PIL import Image\nfrom pyrr import matrix44 as m44, Vector3 as v3\nfrom OpenGL.GL import *\n\nfrom shader import Shader\n\n\nclass LoadedObject:\n def __init__(self, path: str, x: float = 0.0, y: float = 0.0, z: float = 0.0, scale: float = 1.0):\n \"\"\"Object loaded from .obj and .mtl files, ready to be drawn.\"\"\"\n self._path = path\n self._wavefront = None\n self.vaos = None\n self._vbos = None\n self.materials = []\n self.textures = None\n self.use_texture = False\n self.lengths = []\n # Set position and model\n self.pos = m44.create_from_translation(v3([x, y, z]))\n self.model = self.pos\n self._scale = scale\n self._scale_matrix: m44 = m44.create_from_scale(v3([self._scale] * 3))\n # Load wavefront\n self._load_obj()\n\n def set_pos(self, pos: v3):\n self.pos = m44.create_from_translation(pos)\n self.model = self.pos\n\n def _load_obj(self) -> None:\n \"\"\"Loads wavefront obj and materials. Stores vertex data into VAOs and VBOs.\"\"\"\n self._wavefront = pywavefront.Wavefront(self._path, collect_faces=True, create_materials=True)\n\n # Generate buffers\n materials_count = len(self._wavefront.materials)\n self.vaos = glGenVertexArrays(materials_count)\n self._vbos = glGenBuffers(materials_count)\n self.textures = glGenTextures(materials_count)\n\n if materials_count == 1:\n # glGen* will return an int instead of an np.array if argument is 1.\n self.vaos = np.array([self.vaos], dtype=np.uint32)\n self._vbos = np.array([self._vbos], dtype=np.uint32)\n self.textures = np.array([self.textures], dtype=np.uint32)\n\n # For each material fill buffers and load a texture\n ind = 0\n for material in self._wavefront.materials.values():\n vertex_size = material.vertex_size\n scene_vertices = np.array(material.vertices, dtype=np.float32)\n # Store length and materials for drawing\n self.lengths.append(len(scene_vertices))\n self.materials.append(material)\n # Load texture by path (may break in some weird cases, I guess)\n if material.texture is not None:\n self._load_texture(material.texture.path, self.textures[ind])\n self.use_texture = True\n\n # Bind VAO\n glBindVertexArray(self.vaos[ind])\n # Fill VBO\n glBindBuffer(GL_ARRAY_BUFFER, self._vbos[ind])\n glBufferData(GL_ARRAY_BUFFER, scene_vertices.nbytes, scene_vertices, GL_STATIC_DRAW)\n\n # Set attribute buffers\n attr_format = {\n \"T2F\": (1, 2), # Tex coords (2 floats): ind=1\n \"C3F\": (2, 3), # Color (3 floats): ind=2\n \"N3F\": (3, 3), # Normal (3 floats): ind=3\n \"V3F\": (0, 3), # Position (3 floats): ind=0\n }\n\n cur_off = 0 # current start offset\n for attr in material.vertex_format.split(\"_\"):\n if attr not in attr_format:\n raise Exception(\"Unknown format\")\n\n # Apply\n attr_ind, attr_size = attr_format[attr]\n glEnableVertexAttribArray(attr_ind)\n glVertexAttribPointer(attr_ind, attr_size, GL_FLOAT, GL_FALSE, scene_vertices.itemsize * vertex_size,\n ctypes.c_void_p(cur_off))\n cur_off += attr_size * 4\n\n # Unbind (Technically not necessary but used as a precaution)\n glBindVertexArray(0)\n ind += 1\n\n @staticmethod\n def _load_texture(path: str, texture: int) -> None:\n \"\"\"\n Loads texture into buffer by given path and tex buffer ID.\n\n :param path: Texture path.\n :param texture: Texture buffer ID.\n \"\"\"\n # For use with GLFW\n glBindTexture(GL_TEXTURE_2D, texture)\n # Set the texture wrapping parameters\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)\n # Set texture filtering parameters\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)\n # Load image\n image = Image.open(path)\n image = image.transpose(Image.FLIP_TOP_BOTTOM)\n img_data = image.convert(\"RGBA\").tobytes()\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, img_data)\n\n def draw(self, shader: Shader, model=None) -> None:\n \"\"\"Draws loaded object onto GL buffer with selected shader.\"\"\"\n # shader.use_program() # Not really sure if that's how you should do it\n for vao, tex, length, mat in zip(self.vaos, self.textures, self.lengths, self.materials):\n glBindVertexArray(vao)\n glBindTexture(GL_TEXTURE_2D, tex)\n if model is not None:\n shader.set_model(model)\n else:\n shader.set_model(m44.multiply(self._scale_matrix, self.model))\n shader.set_v3(\"material.ambient\", mat.ambient)\n shader.set_v3(\"material.diffuse\", mat.diffuse)\n shader.set_v3(\"material.specular\", mat.specular)\n shader.set_float(\"material.shininess\", mat.shininess)\n glDrawArrays(GL_TRIANGLES, 0, length)\n","sub_path":"loaded_object.py","file_name":"loaded_object.py","file_ext":"py","file_size_in_byte":5492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"20101990","text":"\"\"\"\ntxt2psqldb.py\n处理 eh0(tcp)_8:58的数据,\n将数据打包成一个个请求,并且分类\n并存入数据库\n\"\"\"\n\nimport psycopg2\n\n\nclass FormatError(Exception):\n pass\n\n\nclass TXT2PSQLDB:\n \"\"\"\n root_path: 类型:str。设置文件根目录,以 / 或 \\ 结尾,例如:\"/root/\"\n file_name: 类型:str。设置文件名, 例如:\"demon.txt\"\n \"\"\"\n\n def __init__(self, header_amount=0, root_path=\"\", file_name=\"\"):\n self.header_amount = header_amount\n self.root_path = root_path\n self.file_name = file_name\n\n @property\n def file_name(self):\n return self.__file_name\n\n @file_name.setter\n def file_name(self, value):\n self.__file_name = value\n\n @property\n def root_path(self):\n return self.__root_path\n\n @root_path.setter\n def root_path(self, value):\n if value[-1] not in (\"/\", \"\\\\\"):\n raise FormatError(\"请按格式传参,root_path 例: '/root/';file_name 例: 'demon.txt'\")\n else:\n self.__root_path = value\n\n def __get_tar(self):\n \"\"\"\n 将行数据分割好放到self.__tar中\n :return:\n \"\"\"\n raise NotImplementedError\n\n def __classify(self):\n \"\"\"\n 把列分类好的数据放入self.__notes这个二维列表里面\n :return:\n \"\"\"\n raise NotImplementedError\n\n\nclass MYTXT2PSQLDB(TXT2PSQLDB):\n def __init__(self, header_amount=0, root_path=\"\", file_name=\"\"):\n super().__init__(header_amount, root_path, file_name)\n self.__tar = []\n self.__notes = []\n self.__list_info = []\n\n def __get_tar(self):\n fr = open(self.root_path + self.file_name, \"r\")\n temp = \"\"\n for line in fr:\n if line[0:3] == \"No.\":\n self.__tar.append(temp)\n temp = \"\"\n temp += line\n fr.close()\n\n def __classify(self):\n for i in range(1, len(self.__tar)):\n temp = []\n str_info = self.__tar[i].split(\"\\n\")[1].strip()\n list_info_temp = str_info.split(\" \")\n self.__list_info = []\n for j in range(len(list_info_temp)):\n if list_info_temp[j] != \"\":\n self.__list_info.append(list_info_temp[j])\n for k in range(self.header_amount - 2):\n temp.append(self.__list_info[k])\n temp.append(\" \".join(self.__list_info[6:]))\n temp.append(\"\\n\".join(self.__tar[i].split(\"\\n\")[3:]))\n self.__notes.append(temp)\n\n def run(self):\n # 打开数据库\n db = psycopg2.connect(\"dbname=tar_data user=postgres password=toor host=localhost\")\n cur = db.cursor()\n # 以 No. 为标志进行分割,划分各个数据包\n self.__get_tar()\n self.__classify()\n # 放入数据库\n match = \"(\"+(\"%s,\" * self.header_amount)[0:-1] +\")\"\n psql = \"insert into tcp values \" + match\n for i in range(len(self.__notes)):\n try:\n cur.execute(psql, self.__notes[i])\n db.commit()\n except Exception as e:\n print(e)\n db.rollback()\n cur.close()\n db.close()\n","sub_path":"txt2psqldb.py","file_name":"txt2psqldb.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"23647490","text":"import mxnet as mx\r\nimport logging\r\nimport time\r\n\r\nlogging.getLogger().setLevel(logging.DEBUG)\r\nbatch_s = 8\r\nprint(\"Mariya config\")\r\ntrain_data = mx.io.ImageRecordIter(\r\n path_imgrec=\"data.rec\",\r\n data_shape=(3, 128, 128),\r\n batch_size=batch_s)\r\ntest_data = mx.io.ImageRecordIter(\r\n path_imgrec=\"test_data.rec\",\r\n data_shape=(3, 128, 128),\r\n batch_size=batch_s)\r\nprint(\"data - ok\")\r\n\r\n#First 'layer', if it can be put that way.\r\ndata = mx.sym.var('data')\r\ninput = mx.sym.flatten(data=data)\r\nfirst = mx.sym.FullyConnected(data=input, num_hidden=2000)\r\nfirstact = mx.sym.Activation(data=first, act_type='relu')\r\nsecond = mx.sym.FullyConnected(data=firstact, num_hidden=1000)\r\nsecondact = mx.sym.Activation(data=second, act_type='relu')\r\nthird = mx.sym.FullyConnected(data=secondact, num_hidden=500)\r\nthirdact = mx.sym.Activation(data=third, act_type='relu')\r\nfourth = mx.sym.FullyConnected(data=thirdact, num_hidden=250)\r\nfourthact = mx.sym.Activation(data=fourth, act_type='sigmoid')\r\nfc = mx.sym.FullyConnected(data=fourthact, num_hidden=2)\r\nsoftmax = mx.sym.SoftmaxOutput(data=fc, name='softmax')\r\n#softmax = mx.sym.LogisticRegressionOutput(data=fc, name='softmax')\r\n\r\nprint(\"layers - ok\")\r\nfcnn_net = mx.mod.Module(symbol=softmax, context=mx.gpu())\r\nstart_time = time.clock()\r\nfcnn_net.fit(train_data,\r\n eval_data=test_data,\r\n optimizer='sgd',\r\n optimizer_params={'learning_rate': 0.001},\r\n eval_metric='acc',\r\n batch_end_callback=mx.callback.Speedometer(batch_s, 100),\r\n num_epoch=10)\r\nfit_time = time.clock() - start_time\r\nprint(\"Fit time: %f\", fit_time)\r\nacc = mx.metric.Accuracy()\r\nfcnn_net.score(test_data, acc)\r\nprint(acc)\r\n","sub_path":"lab2/src/fcnn_rrrs1.py","file_name":"fcnn_rrrs1.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"496823084","text":"def delete_wire(coordinate_begin, itemnet, distances, gate_connections, allwires, blocked):\n wires = []\n x_coordinate_start = int(coordinate_begin[0])\n y_coordinate_start = int(coordinate_begin[1])\n z_coordinate_start = int(coordinate_begin[2])\n coordinate = coordinate_begin\n \n # Switch order of gates\n end_gate = itemnet[0]\n start_gate = itemnet[1]\n distances.append(((start_gate, end_gate), 2))\n\n coordinates = gate_connections[itemnet]\n print(\"BEFOREDEL: \", len(allwires), len(blocked))\n # Delete wire from gate connections dictionary\n del gate_connections[itemnet]\n \n # Delete blocking wire\n for i in coordinates:\n print(\"incoo: \", i, type(i))\n if str(i) in blocked:\n print(\"DELETEBLOCK\", i)\n blocked.remove(str(i))\n deletelist = []\n # Delete blocking wire\n for i, item2 in enumerate(allwires):\n if item2.net == itemnet:\n # print(\"DELETETOM\")\n # print(allwires[i])\n deletelist.append(allwires[i])\n # print(\"DELETINGTHIS: \", str(deletelist))\n for delete_wire in deletelist: \n allwires.remove(delete_wire)\n print(\"AFTERDEL: \", len(allwires), len(blocked))\n\n return wires, x_coordinate_start, y_coordinate_start, z_coordinate_start, coordinate, gate_connections, allwires, blocked","sub_path":"code/functions/astardelete.py","file_name":"astardelete.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"303778442","text":"#!/usr/bin/env python3\n\n\"\"\"\n/************************************************************/\n/* Author(s): 3JRS - Janeel, Jennie, Jess, Richie, Steph\n/* Major: Information Technology\n/* Compiler: Python 3.6 \n/* Creation Date: 4/29/18\n/* Due Date: 12/12/18\n/* Course: CSC354-020\n/* Professor Name: Prof. Demarco\n/* Assignment: Software Engineering Project (Prototype)\n/* Filename: socket_communication.py\n/* Purpose: To write a server that will communicate with a client (which will also be a server) via client/server communication\n/************************************************************/\n\"\"\"\nimport socket\nimport sys, os \n\ndef Main():\n ipaddress = \"127.0.0.1\"\n IPaddr = socket.gethostbyname(ipaddress) #translate hostname to ip address\n message = \"TEST\"\n bufferSize = 1024\n port = 4444\n serverInfo = ((IPaddr, port)) \n \n try: #Attempt to connect to server\n clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n clientSocket.connect(serverInfo)\n print ('You have successfully connected')\n except socket.error as err:\n print('Socket connection error:', err)\n sys.exit()\n \n try:\n status = clientSocket.recv(bufferSize) #attempt to receive wait message \n status = status.decode()\n except socket.error as msg:\n print ('Unable to receive message from server: ' + str(msg[0]))\n \n connection = True \n while connection:\n try:\n final = clientSocket.recv(4) #Receieve GO from server\n final = final.decode() \n except Exception as s:\n print ('Unable to send client input and READY message: ', s)\n sys.exit(0)\n if (final == \"TEST\"):\n cInput(clientSocket)\n connection = False\n clientSocket.close() \n\nif __name__ == '__main__': #ensures in current module Main \n Main()\nelse:\n sys.exit(0)","sub_path":"socket_communication.py","file_name":"socket_communication.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"114481584","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/9/21 11:34\n# @Author : Burrows\n# @FileName: runTest.py\n\n'''封装公共测试流'''\n\nimport unittest\nimport time\nimport re\nimport json\n\nfrom jsonpath import jsonpath\n\nfrom base.runMethod import RunMethod\nfrom base.readLogger import ReadLogger\nfrom util.relyData import RelyData\nfrom base.aydException import *\n\nclass RunTest(unittest.TestCase, unittest.SkipTest, DataCheck):\n def __init__(self, methodName = 'runTest'):\n super(RunTest, self).__init__(methodName)\n\n # 获取logger和run_log\n read_logger = ReadLogger()\n self.logger = read_logger.get_logger()\n self.run_log_src = read_logger.get_run_log()\n\n # 使用自封装requests\n self.run_method = RunMethod()\n\n # 使用自封装关联数据\n self.rely_data = RelyData()\n\n self.case_id = '' # 用例id\n self.desc = '' # 用例描述\n self.resp = None # 响应数据\n self.req_msg = {'request': {}, '\\nresponse': {}} # 用例基本信息\n\n def get_resp(self):\n \"\"\"\n 获取响应信息\n :return: response data\n \"\"\"\n return self.resp\n\n def skipTest(self, reason):\n \"\"\"\n 过滤用例\n :param reason: 过滤用例原因\n :return: unittest.SkipTest\n \"\"\"\n raise unittest.SkipTest\n\n def getCasePro(self):\n \"\"\"\n 获取用例基本信息\n :return: case_id, desc\n \"\"\"\n return self.case_id, self.desc\n\n def getCaseMsg(self):\n \"\"\"\n 获取待执行用例详细信息\n :return: req_msg = {'request': {}, '\\nresponse': {}}\n \"\"\"\n return self.req_msg\n\n def start(self, url, uri, method, api_name, header, cookie, **kw):\n \"\"\"\n 用例运行主入口\n :param url: 请求地址\n :param uri: 请求路径\n :param method: 请求方法\n :param api_name: 接口名称\n :param header: header设置\n :param cookie: cookie设置\n :param kw: 其他参数\n :return: None\n \"\"\"\n\n # 获取case数据\n options = kw.get('options', {})\n skip = options.get('skip', '0') # skip默认值为0,为1表示跳过该case\n data_check = options.get('datacheck', None) # 数据校验\n toJsonData = options.get('jsonData', '0') # jsonData默认值为0,表示请求数据不做序列化\n self.case_id = kw.get('case_id') # case id\n self.desc = kw.get('desc') # case描述\n api_name = api_name # api名\n url = url + uri # 请求url\n method = method # 请求方法\n header = header # header设置\n cookie = cookie # cookie设置\n data = kw.get('request_data', '') # 请求数据,缺省为空\n validators = kw.get('validators') # 断言设置\n relyDataExport = kw.get('relyDataExport') # 关联输出,即该接口响应返回被其他接口关联字段\n relyDataImport = kw.get('relyDataImport') # 关联引入,即该接口运行所需的关联字段设置\n start_time = time.strftime(\"%Y/%m/%d %H:%M:%S\") # 开始时间\n start_timestamp = time.time() * 1000 # 时间戳,ms\n\n # 处理关联数据\n if relyDataImport is not None:\n for x in relyDataImport:\n datatype = x.get('datatype') # 获取目标关联数据替换源,可能是 request_data/header/cookie\n relyDataSrc = x.get('relyDataSrc') # 获取依赖字段,可能在request_data中为层级结构\n relyDataDes = x.get('relyDataDes') # 获取关联字段\n rely_value = self.rely_data.get_rely_from_file(relyDataDes) # 获取关联数据\n # 替换依赖字段值为关联数据\n if datatype in \"header\":\n header[relyDataSrc] = rely_value\n elif datatype in \"cookie\":\n cookie[relyDataSrc] = rely_value\n else:\n paths = jsonpath(data, '$..%s' % relyDataSrc, result_type='IPATH') # 获取目标字段的位置的层级结构,返回list\n # 替换request_data中所有目标key的值为关联数据\n for path in paths:\n lens = len(path)\n for index in range(lens):\n if re.match(r'[0-9]', path[index]):\n path[index] = int(path[index])\n if lens == 1:\n data[path[0]] = rely_value\n elif lens == 2:\n data[path[0]][path[1]] = rely_value\n elif lens == 3:\n data[path[0]][path[1]][path[2]] = rely_value\n elif lens == 4:\n data[path[0]][path[1]][path[2]][path[3]] = rely_value\n elif lens == 5:\n data[path[0]][path[1]][path[2]][path[3]][path[4]] = rely_value\n elif lens == 6:\n data[path[0]][path[1]][path[2]][path[3]][path[4]][path[5]] = rely_value\n else:\n self.logger.debug('层级结构过长')\n\n self.req_msg.get('request').setdefault('\\nreq.url', url)\n self.req_msg.get('request').setdefault('\\nreq.method', method)\n self.req_msg.get('request').setdefault('\\nreq.header', header)\n self.req_msg.get('request').setdefault('\\nreq.cookie', cookie)\n self.req_msg.get('request').setdefault('\\nreq.data', data)\n self.req_msg.get('request').setdefault('\\nreq.validators', validators)\n self.req_msg.get('request').setdefault('\\nreq.relyDataExport', relyDataExport)\n self.req_msg.get('request').setdefault('\\nreq.relyDataImport', str(relyDataImport))\n self.req_msg.get('request').setdefault('\\nreq.data_check', str(data_check) + '\\n')\n\n if int(skip) == 1:\n self.logger.debug('跳过用例 :%s(%s)' % (self.case_id, self.desc))\n self.skipTest('skip case')\n\n try:\n self.logger.debug('用例编号 :%s ' % self.case_id)\n self.logger.debug('接口名称 : %s' % api_name)\n self.logger.debug('用例描述 : %s' % self.desc)\n self.logger.debug('请求时间 : %s' % start_time)\n self.logger.debug(' 请求信息 '.center(50, '-'))\n self.logger.debug('url : %s' % url)\n self.logger.debug('method : %s' % method)\n self.logger.debug('header : %s' % header)\n self.logger.debug('cookie : %s' % cookie)\n self.logger.debug('请求数据 : %s' % data)\n self.logger.debug('断言设置 : %s' % validators)\n self.logger.debug('关联输出 : %s' % relyDataExport)\n self.logger.debug('关联引入 : %s' % relyDataImport)\n self.logger.debug('校验数据 : %s' % data_check)\n\n # 发送请求\n # 接口有异常的情况下,可能返回的不是json串,会报错\n if toJsonData == 1:\n resp = self.run_method.run_main(method, url, json.dumps(data), cookies=cookie, headers=header)\n else:\n resp = self.run_method.run_main(method, url, data, cookies=cookie, headers=header)\n resp_headers = dict(resp.headers) # 响应头\n resp_status_code = resp.status_code # 响应码\n resp_cookie = dict(resp.cookies) # 响应cookie\n resp_text = resp.text # 响应文本\n\n end_time = time.strftime(\"%Y/%m/%d %H:%M:%S\")\n end_timestamp = time.time() * 1000 # ms\n time_spend = '%.2f' % (end_timestamp - start_timestamp) # ms精度\n\n self.logger.debug(' 响应信息 '.center(50, '-'))\n self.logger.debug('响应时间 : %s' % end_time)\n self.logger.debug('响应耗时 : %s ms' % time_spend)\n self.logger.debug('响应码 : %s' % resp_status_code)\n self.logger.debug('响应头 : %s' % resp_headers)\n\n self.req_msg.get('\\nresponse').setdefault('\\nresp.status_code', resp_status_code)\n self.req_msg.get('\\nresponse').setdefault('\\nresp.headers', resp_headers)\n\n # 查看是否包含 断言查看一次错误就停止,后面加入错误提示\n self.assertEqual(resp_status_code, 200, msg='预计结果不符:http_code预期结果 200,实际结果【%s】' % (resp_status_code))\n\n # 响应结果处理,可能是文本、网页、dict\n if resp_text.startswith('{'):\n resp = resp.json()\n self.resp = resp\n self.req_msg.get('\\nresponse').setdefault('\\nresp.json', str(resp) + '\\n')\n\n # 保存被关联数据\n if relyDataExport is not None:\n for x in relyDataExport:\n datatype = x.get('datatype')\n relyKey = x.get('relyKey')\n keepKey = x.get('keepKey')\n if datatype in \"header\":\n self.rely_data.write_rely_to_file(relyKey, keepKey, resp_headers)\n elif datatype in \"cookie\":\n self.rely_data.write_rely_to_file(relyKey, keepKey, resp_cookie)\n else:\n self.rely_data.write_rely_to_file(relyKey, keepKey, resp)\n\n # 响应数据断言 json\n for valid in validators:\n check = valid.get('check') # 待检查字段\n expect = valid.get('expect') # 预期值\n resp_data = resp.get(check)\n if isinstance(expect, int):\n self.assertEqual(expect, resp_data, msg='预计结果不符:【%s】字段预期结果【%s】,实际结果【%s】' % (check, expect, resp_data))\n if isinstance(expect, str):\n self.assertIn(expect, resp_data, msg='预计结果不符:【%s】字段预期结果【%s】,实际结果【%s】' % (check, expect, resp_data))\n\n else:\n resp = resp_text\n resp = resp.replace(r\"<\", r\"<--\") # 注释html标签,防止误识别\n self.resp = resp\n self.req_msg.get('\\nresponse').setdefault('\\nresp.text', str(resp) + '\\n')\n\n\n # 保存被关联数据\n if relyDataExport is not None:\n for x in relyDataExport:\n datatype = x.get('datatype')\n relyKey = x.get('relyKey')\n keepKey = x.get('keepKey')\n if datatype in \"header\":\n self.rely_data.write_rely_to_file(relyKey, keepKey, resp_headers)\n elif datatype in \"cookie\":\n self.rely_data.write_rely_to_file(relyKey, keepKey, resp_cookie)\n else:\n pass\n\n # 响应数据断言 text\n for valid in validators:\n expect = valid.get('expect') # 预期值\n if isinstance(expect, str):\n self.assertIn(expect, resp_text, msg='预计结果不符:预期值【%s】在响应文本中不存在!' % expect)\n\n self.logger.debug('响应内容 : %s' % resp)\n\n # 数据校验\n if data_check == 1:\n raise DataCheck\n\n except DataCheck:\n raise\n except Exception as e:\n self.logger.debug('响应内容 : %s' % resp)\n self.logger.error('错误信息 : %s' % e)\n raise\n # finally:\n # self.logger.debug('结束测试 %s ' % self.case_id)\n","sub_path":"src/common/runTest.py","file_name":"runTest.py","file_ext":"py","file_size_in_byte":12066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"413153452","text":"# Get per capita personal income from CA1 table for SC counties for all years\nimport requests\nimport json\n\nkey = \"F414B54D-68CF-452A-BFD9-7B7BDA23AE7C\"\ndataset_name = \"RegionalIncome\"\nparameter_name = \"LineCode\"\ntable_name = \"CA1\"\nline_code = \"3\"\nyear = \"ALL\"\ngeo_fips = \"45000\"\nresult_format = \"json\"\nurl = \"https://apps.bea.gov/api/data?&UserID=\" + key + \\\n\"&method=GetData&datasetname=\" + dataset_name + \\\n\"&TableName=\" + table_name + \"&LineCode=\" + line_code + \\\n\"&Year=\" + year + \"&GeoFips=\" + geo_fips + \\\n\"&ResultFormat=\" + result_format\n\nresponse = requests.get(url) # Get response from site\ndata = response.json() # put response in object\n\nwith open(\"ca1_per_capita_personal_income_sc.json\", \"w\") as jsondata: # Write json response to file\n jsondata.write(json.dumps(data, sort_keys=True, indent=2))\n\n#for item in data[\"BEAAPI\"][\"Results\"][\"Data\"]: # Printing the info\n# number_meaning = item[\"CL_UNIT\"]\n# population = item[\"DataValue\"]\n# table_code = item[\"Code\"]\n# location_code = item[\"GeoFips\"]\n# location_name = item[\"GeoName\"]\n# year = item[\"TimePeriod\"]\n# dollar_exponent = item[\"UNIT_MULT\"]\n# print(year + \": \" + location_name + \"| \" + population)","sub_path":"regional_income/table_ca1/state/sc/ca1_per_capita_personal_income_sc.py","file_name":"ca1_per_capita_personal_income_sc.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"544576665","text":"#!-*- coding: utf-8 -*-\nfrom django.db import connection\nfrom django.template import Template, Context\n\nclass Middleware(object):\n def process_response(self, request, response):\n content_types = ('text/plain', 'text/html')\n if request.META['CONTENT_TYPE'] not in content_types:\n return response\n time = sum([float(q['time']) for q in connection.queries])\n template = Template(\"\"\"
\n

Number of requests: {{ count }}

\n

Time: {{ time }} с.

\n
\n \"\"\")\n renderred_template = template.render(Context(dict(time=time, count=len(connection.queries))))\n content = response.content.decode('utf-8')\n body = ''\n body_position = content.find(body)\n content = content[:body_position] + renderred_template + content[body_position:]\n response.content = content.encode('utf-8')\n return response","sub_path":"echo_ua_test/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"466481444","text":"#!/usr/bin/python3\n\nfrom sys import argv\nimport bs4 as bs\nimport re\nimport time\nfrom unidecode import unidecode\n\nscript, filename = argv\n\ninp = open(filename,'r')\nx=inp.read().split('')\ninp.close()\n\n#write header\ncsv=\"Case Id;Title;Date;Priority;Planned duration (minutes);Test Areas;Average Duration;Tags;Objective;Test Data;Preconditions & Assumptions\"\nf = open(\"output.csv\",\"a\")\nf.write(csv)\nf.close()\n\n\n#get date\ndate=time.strftime(\"%Y-%d-%m\")\n\n\n#create soups\ny=0\nsoups=[]\nwhile y < len(x):\n soups.append(bs.BeautifulSoup(x[y],'xml'))\n y+=1\n\n#parse soup one by one\ns=0\nwhile s < len(soups)-1:\n\n #parse name\n name=\"\".join(str(soups[s].find('testcase')))\n\n n=re.search('\"(.*)\">', name).group(1)\n\n #parse preconditions\n try:\n preconditions=soups[s].preconditions.text.replace('\"', '').rstrip('\\n')\n except AttributeError:\n preconditions=\"\"\n\n\n #parse actions\n actions=soups[s].find_all('actions')\n i = 0\n a=[]\n while i < len(actions):\n a.append(actions[i].text.replace('\"', '').rstrip('\\n'))\n i = i + 1\n\n\n\n #parse expected results\n expected_results=soups[s].find_all('expectedresults')\n z = 0\n exp=[]\n while z < len(expected_results):\n exp.append(expected_results[z].text.replace('\"', '').rstrip('\\n'))\n z = z+1\n\n\n #prepare csv\n csv= \"\\nnew;%s;%s;\\\"\\\";\\\"\\\";\\\"\\\";\\\"\\\";\\\"\\\";\\\"\\\";\\\"\\\";%s\\n\\\"\\\";Step Id;Action;Result\" % (n, date, preconditions)\n for i in range(len(actions)):\n csv+=\"\"\"\\n\"\";new;%s;%s\"\"\" % (a[i], exp[i])\n\n\n s+=1\n #write to file\n f = open(\"output.csv\",\"a\")\n f.write(csv)\n f.close()\n\n\n\n\n#replace line ending LF to CRLF, UTF8 --> ASCII encode\n\nwindows_line_ending = '\\r\\n'\nlinux_line_ending = '\\n'\n\n\n\nf = open(\"output.csv\", 'r')\ncontent = f.read()\ncontent = content.replace(linux_line_ending, windows_line_ending )\nencoded=unidecode(content)\nencoded.encode(\"ascii\")\nf.close()\n\nf = open(\"output.csv\", 'w')\nf.write(encoded)\nf.close()\n","sub_path":"tl2tr.py","file_name":"tl2tr.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"438104852","text":"#Ref: https://google.github.io/mediapipe/solutions/hands.html\n\n#imports\nimport cv2\nimport collections\nimport numpy as np\nimport mediapipe as mp\nimport time\nfrom sklearn import neighbors\nimport matplotlib\nfrom matplotlib import pyplot as plt \nimport pickle\nimport os as o\n\n#train data\nclass Train:\n #init\n def __init__(self, data_folder):\n #KNN\n self.clf = neighbors.KNeighborsClassifier(15)\n #training x and y\n t_x = []\n t_y = []\n #label\n self.lb = []\n\n #look for data\n for i, df in enumerate(o.listdir(data_folder)):\n #get path\n with open(o.path.join(data_folder, df), 'rb') as f:\n #load file\n d = pickle.load(f)\n #train path\n for h in d:\n t_y.append(i)\n t_x.append((h - h[0]).flatten())\n #CHECK THIS\n self.lb.append(df[5:-2])\n t_x = np.array(t_x)\n self.clf.fit(t_x, t_y)\n plt.switch_backend('Agg')\n\n #get certain shape\n def getshape(self, h):\n pre = self.clf.predict(\n np.expand_dims((h - h[0]).flatten(), 0))\n return self.lb[int(pre)]\n\n\nclass MH:\n #init\n def __init__(self, buffer_size=None):\n #get hands\n self.hands = mp.solutions.hands.Hands(\n min_tracking_confidence=0.9,\n min_detection_confidence=0.75\n )\n #get\n self.his = collections.deque(maxlen=None)\n\n #thresh & num\n self.tmt= 3\n self.tmn= 0\n\n #run img\n def run(self, img):\n #get img.shape\n img_width, img_height, _ = img.shape\n #input photo\n inpi = cv2.cvtColor(cv2.flip(img, 1), cv2.COLOR_BGR2RGB)\n inpi.flags.writeable = False\n #set result\n res = self.hands.process(cv2.cvtColor(inpi, cv2.COLOR_BGR2RGB))\n\n #check result arr\n if res.multi_hand_landmarks:\n #set track missing num to 0\n self.tmn = 0\n res_arr = np.asarray([[pt.x, pt.y] for pt in res.multi_hand_landmarks[0].landmark])\n self.his.append(res_arr)\n #if track missing num smaller that track missing thresh\n elif self.tmn < self.tmt:\n self.tmn += 1\n #otherwise clear history\n else:\n self.his.clear()\n self.tmn = 0\n plt.switch_backend('Agg')\n\n return res\n\n #draw\n def drawlol(self, image, res):\n image_width, image_height, _ = image.shape\n #flip img\n new_img = cv2.flip(image, 1) \n #check for landmarks\n if res.multi_hand_landmarks:\n for hand_landmarks in res.multi_hand_landmarks:\n #draww\n mp.solutions.drawing_utils.draw_landmarks(\n new_img,\n hand_landmarks,\n mp.solutions.hands.HAND_CONNECTIONS\n )\n #get x and y coordinate\n x = [landmark.x for landmark in hand_landmarks.landmark]\n y = [landmark.y for landmark in hand_landmarks.landmark]\n\n #get center\n center = np.asarray([np.mean(x)*image_width*1.87, np.mean(y)*image_height*0.65]).astype('int32')\n #draw circle and box\n cv2.circle(new_img, tuple(center), 10, (225,150,255), 3) #for checking the center \n cv2.rectangle(new_img, (center[0]-200,center[1]-200), (center[0]+200,center[1]+200), (255,255,255), 5)\n #put text\n if self.his:\n hshape = Train(\"/Users/leonachen/mediapipe/CmdSpaceOX/Interface/data_folder\").getshape(self.his[-1])\n cv2.putText(new_img,hshape,(center[0]-250,center[1]-209), cv2.FONT_HERSHEY_COMPLEX,3, (225, 150, 255), 9, cv2.LINE_AA)\n\n return new_img\n def close(self):\n self.hands.close()\n\n#get mp solution\nLM = mp.solutions.hands.HandLandmark\n\n#check function to determine what gesture\ndef check(h, a, w):\n his = np.asarray(a)\n if type(h) != list:\n h = [h]\n return all(hand in h for hand in his[-int(w):])\n\n#gesture state detector\nclass States:\n #init\n def __init__(self, win):\n #set states\n self.scrollh = -1 \n self.state = \"none\"\n self.ic = False\n #get history\n self.his = collections.deque(maxlen=100)\n plt.switch_backend('Agg')\n\n #run and set the states\n def run(self, hand, landmarks, i_history):\n #add hand to history\n self.his.append(hand)\n self.ic = False\n #check fo specific gestures\n if check(\"spiderman\", self.his, 8) and not self.state == \"scroll\":\n self.state = \"volume\"\n if check(\"peace\", self.his, 8)and not self.state == \"volume\":\n self.state = \"scroll\"\n elif check(\"call\", self.his, 5):\n self.state = \"audio\"\n \n if self.state == \"scroll\" or self.state==\"volume\":\n self.scrollh = 1 - landmarks[LM.MIDDLE_FINGER_MCP][1]\n if check(\"palm-open\", self.his, 5):\n self.scrollh = -1\n self.state = \"cursor\"\n elif self.state == \"audio\":\n pass\n\n else:\n if check(\"palm-open\", self.his, 5):\n self.state = \"cursor\"\n elif check(\"fist\", self.his, 5):\n self.ic = True\n else:\n self.state = \"none\"\n\n# if __name__ == \"__main__\":\n# #get mph\n# mph = MH(buffer_size=int(0.5 / 0.05))\n# stated = States(6)\n# handd = Train(\"/Users/leonachen/mediapipe/CmdSpaceOX/Interface/data_folder\")\n# #open cam\n# try:\n# cap = cv2.VideoCapture(0)\n# while cap.isOpened():\n# success, image = cap.read()\n# if not success:\n# print(\"Ignoring empty camera frame.\")\n# continue\n# #get res\n# res = mph.run(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n\n# hs=None\n# if mph.his: \n# hs = handd.getshape(\n# mph.his[-1])\n# stated.run(hs, mph.his[-1], mph.his)\n\n# #draw\n# img = mph.drawlol(image, res)\n# cv2.imshow('cemera hehe', img)\n# if cv2.waitKey(5) & 0xFF == 27:\n# break\n\n# time.sleep(0.05)\n# except:\n# mph.close()\n# cap.release()\n# raise\n\n\n\n","sub_path":"Interface/gest.py","file_name":"gest.py","file_ext":"py","file_size_in_byte":6436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"631050844","text":"##!/usr/bin/env python\n## encoding: utf-8\n#\"\"\"\n#Simple soundfile player used by 06_separated_threads.py example.\n\n#\"\"\"\n#from pyo import *\n\n#s = Server(duplex=0).boot()\n\n#a = SfPlayer('./Samples/test.aiff')\n#a.mix(2).out()\n\n\n#s.start()\n\n#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nSimple soundfile player used by 06_separated_threads.py example.\n\n\"\"\"\nfrom pyo import *\n\ns = Server()\ns.setInOutDevice(2)\ns.boot()\n\na = SfPlayer('./Samples/kick.wav')\n#chor = Chorus(a, depth=[1.1,1.9], feedback=0.5, bal=0.5).out()\nchor = Chorus(a, depth=[1.1,1.9], bal=0.5).out()\na2 = chor.mix(2).out()\n\n\ns.start()","sub_path":"play_snd.py","file_name":"play_snd.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"467937006","text":"# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\nfrom spack.package import *\n\n\nclass Twm(AutotoolsPackage, XorgPackage):\n \"\"\"twm is a window manager for the X Window System. It provides\n titlebars, shaped windows, several forms of icon management,\n user-defined macro functions, click-to-type and pointer-driven\n keyboard focus, and user-specified key and pointer button bindings.\"\"\"\n\n homepage = \"https://cgit.freedesktop.org/xorg/app/twm\"\n xorg_mirror_path = \"app/twm-1.0.9.tar.gz\"\n\n version(\"1.0.9\", sha256=\"1c325e8456a200693c816baa27ceca9c5e5e0f36af63d98f70a335853a0039e8\")\n\n depends_on(\"libx11\")\n depends_on(\"libxext\")\n depends_on(\"libxt\")\n depends_on(\"libxmu\")\n depends_on(\"libice\")\n depends_on(\"libsm\")\n\n depends_on(\"xproto@7.0.17:\")\n depends_on(\"bison\", type=\"build\")\n depends_on(\"flex\", type=\"build\")\n depends_on(\"pkgconfig\", type=\"build\")\n depends_on(\"util-macros\", type=\"build\")\n","sub_path":"var/spack/repos/builtin/packages/twm/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"521790072","text":"import pika, uuid, time, json, threading\nfrom datetime import datetime, timedelta\nimport os\nfrom src.entities import MesaageEntity, NotificationEntity, db_session, use_default_binding_settings\nfrom src.logger import LoggerProxy\n\ndef isoformat_to_datetime(dt_str):\n dt, _, us= dt_str.partition(\".\")\n dt= datetime.strptime(dt, \"%Y-%m-%dT%H:%M:%S\")\n us= int(us.rstrip(\"Z\"), 10)\n res = dt + timedelta(microseconds=us)\n return res\n\nhost = os.environ.get('RABBIT_HOST', 'localhost')\nmax_retry_count = os.environ.get('MAX_RETRY_COUNT', 10)\ndefault_rabbit_config = { \n # 'credentials': { 'username':'dev', 'password':'dev' },\n 'queue': { 'queue': 'notification_message_rpc', 'durable': True },\n 'exchange': { 'exchange': 'notification_rpc', 'exchange_type': 'fanout' },\n # ----------------------\n 'prefetch_count': 2,\n 'routing_key': 'message',\n 'callback_queue': { 'queue': 'message_rpc_callback', 'durable': True, 'exclusive': False },\n # 'port': 5672,\n 'host': host,\n 'no_ack': False\n }\n\nclass MessageRpcClientError(Exception):\n def __init__(self, message, inner=None):\n self.message = message\n self.inner = inner\n Exception.__init__(inner)\n\nclass CallbackProcessingError(MessageRpcClientError):\n def __init__(self, inner):\n super().__init__(message=str(inner), inner=inner)\n\n def __str__(self):\n return 'inner({0}) - {1}'.format(type(self.inner).__name__, \n str(self.inner))\n\nclass MessageRpcClient(object):\n def __init__(self, rabbit_config=None, max_retry_c=None):\n self.max_retry_count = max_retry_c if max_retry_c else max_retry_count\n self.config = rabbit_config or default_rabbit_config.copy()\n self.logger = LoggerProxy(self.__class__.__name__)\n\n def process_notification(self, notification_id, \n is_test=None, include_faliled=False, all_unsuccess=False):\n try:\n if not isinstance(notification_id, uuid.UUID):\n raise ValueError('MessageRpcClient - uuid is expected ofr param \"notification_id\"')\n\n self.logger.info('send messages for notification \"{0}\". (is_test: {1}, include_faliled: {2}, all_unsuccess: {3})', \n notification_id, is_test, include_faliled, all_unsuccess)\n\n created_messages_ids = []\n with db_session:\n n = NotificationEntity[notification_id]\n tmp_list = n.messages.select(lambda m: (all_unsuccess and m.state_id in ['Error', 'Created']) or (include_faliled and m.state_id == 'Error') or m.state_id == 'Created')\n tmp_id_list = [m.message_id for m in tmp_list]\n created_messages_ids.extend(tmp_id_list)\n\n if created_messages_ids and len(created_messages_ids) > 0:\n for m_id in created_messages_ids:\n th = threading.Thread(target=RpcWorker(self.config.copy(), self.max_retry_count).send_message, args=[m_id, is_test]) # <- 1 element list\n th.start()\n\n self.logger.info('{0} msgs was sended.', len(created_messages_ids))\n except Exception as e:\n raise MessageRpcClientError('process_notification({0}) error:\\n{1}'.format(notification_id, str(e)), e)\n\n# TODO: возможно стоит переделать на класс вида \"class CustomThread(threading.Thread)\"\nclass RpcWorker:\n def __init__(self, rabbit_config, max_retry_c):\n self.max_retry_count = max_retry_c\n self.config = rabbit_config\n\n self.routing_key = self.config.pop('routing_key') # required\n self.callback_queue_params = self.config.pop('callback_queue') # required\n\n self.no_ack = self.config.pop('no_ack', True)\n self.prefetch_count = self.config.pop('prefetch_count', None)\n\n self.queue_params = self.config.pop('queue', {})\n self.exchange_params = self.config.pop('exchange', {})\n\n # convert credentials dict to pika.PlainCredentials\n _key = 'credentials'\n if _key in self.config:\n self.config[_key] = pika.PlainCredentials(**self.config[_key])\n\n self.connection = None\n self.channel = None\n\n self.callback_queue = None\n self.callback_queue_name = None\n\n self.exchange = None\n # self.exchange_name = None\n self.queue = None\n self.queue_name = None\n\n self.response_received = False\n self.log_prefix = ''\n self.logger = LoggerProxy('{0}_{1}'.format(self.__class__.__name__, \n datetime.strftime(datetime.utcnow(), '%Y%m%dT%H00')))\n\n def log_info(self, message, *args, **kwargs):\n self.logger.info('{0}{1}'.format(self.log_prefix, message), *args, **kwargs)\n\n def _open_connection(self):\n self.connection = None\n _max_retry_count = self.max_retry_count\n while not (self.connection and self.connection.is_open):\n _max_retry_count -= 1\n try:\n self.connection = pika.BlockingConnection(pika.ConnectionParameters(**self.config))\n self.log_info('connect to Rabbit - successful')\n except pika.exceptions.AMQPError as e1:\n self.log_info('[TRY RECONNECT: max_retry_count:{0}] AMQPError: {1}', self.max_retry_count, str(e1))\n time.sleep(1)\n self.connection = None\n if self.max_retry_count <= 0:\n raise e1\n\n def _check_connection_is_open(self, rabbit_connection: pika.BlockingConnection):\n if not rabbit_connection or not rabbit_connection.is_open:\n raise MessageRpcClientError('connection is closed.')\n\n def _check_channel_is_open(self, rabbit_channel):\n if not rabbit_channel or not rabbit_channel.is_open:\n raise MessageRpcClientError('channel is closed.')\n\n def _open_channel(self):\n self._check_connection_is_open(self.connection)\n self.channel = self.connection.channel()\n if self.prefetch_count:\n self.channel.basic_qos(prefetch_count=self.prefetch_count)\n\n def _declare_callback_queue(self):\n self._check_channel_is_open(self.channel)\n self.callback_queue = self.channel.queue_declare(**self.callback_queue_params)\n self.callback_queue_name = self.callback_queue.method.queue\n\n def _main_queue_bind(self):\n self._check_channel_is_open(self.channel)\n if self.queue_params:\n self.queue = self.channel.queue_declare(**self.queue_params)\n self.queue_name = self.queue.method.queue\n if self.exchange_params:\n self.exchange = self.channel.exchange_declare(**self.exchange_params)\n self.exchange_name = self.exchange_params['exchange']\n self.exchange_type = self.exchange_params['exchange_type']\n\n # (опциоанльно) биндим основную очередь и обменник, если их параметры указаны\n if self.queue and self.exchange:\n r_key = self.routing_key if self.exchange_type != 'fanout' else ''\n self.channel.queue_bind(queue=self.queue_name, \n exchange=self.exchange_name,\n routing_key=r_key)\n\n def _stop(self):\n if self.channel:\n self.channel.stop_consuming()\n self.channel = None\n\n if self.connection:\n self.connection.close()\n self.connection = None\n self.log_info('was stopped.')\n\n def on_response(self, ch, method, props, body):\n try:\n message_id = uuid.UUID(props.correlation_id)\n self.log_info('receive callback for \"{0}\". body: {1}', message_id, body)\n\n resp = json.loads(body)\n error = resp.get('error')\n date = resp.get('date')\n\n # TODO: по хорошему MessageRpcClient не должен знать о сущностях в БД\n # и сюда надо пробрасывать делегат\n is_ok = False\n with db_session:\n m = MesaageEntity.get(message_id=message_id)\n if m:\n if m.state_id != 'Sent':\n u_date = isoformat_to_datetime(date)\n if error:\n m.to_error_state(error_message=error, update_date=u_date)\n else:\n m.to_accepted_state(update_date=u_date)\n is_ok = True\n else:\n self.log_info('message \"{0}\" not found', message_id)\n self.channel.basic_nack(delivery_tag=method.delivery_tag)\n\n if is_ok:\n if not self.no_ack:\n self.channel.basic_ack(delivery_tag=method.delivery_tag)\n self.response_received = True\n except Exception as ex:\n if self.channel and self.channel.is_open:\n self.channel.basic_nack(delivery_tag=method.delivery_tag)\n raise CallbackProcessingError(ex)\n\n def send_message(self, message_id, is_test=None):\n try:\n self.log_prefix = '{0} - '.format(message_id)\n if isinstance(message_id, str):\n message_id = uuid.UUID(message_id)\n self.log_info('parse \"message_id\" from str to uuid', message_id)\n\n self._open_connection()\n self._open_channel()\n self._declare_callback_queue()\n self._main_queue_bind()\n\n self.channel.basic_consume(consumer_callback=self.on_response, \n no_ack=self.no_ack,\n queue=self.callback_queue_name)\n\n msg_dict = {}\n with db_session:\n m = MesaageEntity[message_id]\n if m.state_id == 'Sent':\n raise ValueError('message [{0}] - is already processed'.format(message_id))\n elif m.state_id == 'Processing':\n raise ValueError('message [{0}] - was is already sended to message broker'.format(message_id))\n elif m.state_id in ['Error', 'Created']:\n m.to_processing()\n\n msg_dict['recipient_type'] = m.recipient_type\n msg_dict['recipients'] = m.recipient\n msg_dict['subject'] = m.title\n msg_dict['message'] = m.text\n if is_test:\n msg_dict['is_test'] = True\n body_str = json.dumps(msg_dict)\n self.channel.basic_publish(exchange=self.exchange_name,\n routing_key=self.routing_key,\n properties=pika.BasicProperties(\n reply_to=self.callback_queue_name,\n correlation_id=str(message_id)\n ),\n body=body_str)\n self.log_info('publish. sended data: {1}', message_id, body_str)\n\n _cc = 0\n while not self.response_received:\n self.log_info('wait callback...{0}', str(_cc) if _cc > 0 else '')\n _cc += 1\n if _cc > 1:\n time.sleep(0.05)\n self.connection.process_data_events(time_limit=None)\n\n except MessageRpcClientError as rpc_err:\n raise rpc_err\n except Exception as e:\n raise MessageRpcClientError('send_message({0}) error:\\n{1}'.format(message_id, str(e)), e)\n finally:\n try:\n self._stop()\n except:\n pass\n","sub_path":"notification-service/src/message_rpc_client.py","file_name":"message_rpc_client.py","file_ext":"py","file_size_in_byte":11782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"336333908","text":"from livewires import games, color\r\nimport pygame\r\nimport random\r\nfrom flags import FLAGS\r\n\r\n\r\nclass RepairKit(games.Sprite):\r\n \"\"\" repair kit for the player \"\"\"\r\n\r\n FLAG = FLAGS[\"F_KIT\"]\r\n\r\n image = games.load_image(\"textures\\\\kit.png\",\r\n transparent = False)\r\n\r\n #kit parameters\r\n LIFE_TIME = games.screen.fps*8\r\n VALUE = 30\r\n\r\n def __init__(self):\r\n #random initial position\r\n x = random.randint(20, games.screen.width - 20)\r\n y = random.randint(20, games.screen.height - 20)\r\n super(RepairKit, self).__init__(image = self.image,\r\n x = x,\r\n y = y)\r\n self.lifetime = RepairKit.LIFE_TIME\r\n self.value = RepairKit.VALUE\r\n\r\n def update(self):\r\n \"\"\" executed once per frame \"\"\"\r\n\r\n if self.lifetime > 0:\r\n self.lifetime -= 1\r\n else:\r\n self.destroy()\r\n\r\n def collide(self):\r\n \"\"\" repair kit destruction \"\"\"\r\n self.destroy()","sub_path":"repair_kit.py","file_name":"repair_kit.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"542150823","text":"import unittest\n\n\ndef factorial(N):\n if N == 0 or N ==1: return 1\n ans = 2\n for i in range(N, 2, -1):\n ans *= i\n return ans\n\n\ndef permutate(word):\n if word == \"\":\n return [\"\"]\n\n else:\n result = []\n letter = word[0]\n\n for w in permutate(word[1:]): # for every word in the result from f(n-1)\n for i in range(len(w) + 1): # insert letter at all positions of the word\n result.append(w[0:i] + letter + w[i:])\n\n return result\n\n\nclass MyTestCase(unittest.TestCase):\n\n def setUp(self):\n self.data = [ \"A\", \"JOY\", \"VOICE\", \"IMPORTED\"]\n\n def test_result_length(self):\n for word in self.data:\n result = permutate(word)\n self.assertEqual(len(result), factorial(len(word)))\n\n def test_word_length(self):\n for word in self.data:\n wlen = len(word)\n\n for per in permutate(word):\n self.assertTrue(len(per), wlen)\n\n for ch in per:\n self.assertTrue(ch in word)\n\n ## Letters must be unique for this test to pass\n def test_no_duplicates(self):\n for word in self.data:\n dict = {}\n\n for per in permutate(word):\n self.assertTrue( per not in dict)\n dict[per] = 1\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"class/Homework/6/hw6_task1_tester.py","file_name":"hw6_task1_tester.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"166196139","text":"from lxml import html\r\nimport requests\r\nimport mysql.connector\r\nimport string\r\n\r\na='http://www.realitica.com/?cur_page='\r\n\r\n\r\n\r\n\r\ncnx = mysql.connector.connect(user='asdadsad', password='wqewqeqe',\r\n host='localhost', port='3312',\r\n database='asdadsad')\r\n\r\n\r\n\r\nb = [\"Hrvatska\",\"Crna+Gora\",\"Srbija\",\"Bosna+i+Hercegovina\"]\r\nb1 = ['&for=Prodaja&pState=','&for=DuziNajam&pState=']\r\n\r\nfor counter in range(0,4):\r\n\r\n for counter1 in range(0,2):\r\n zemlja=b1[counter1] + (b[counter])\r\n\r\n print (zemlja)\r\n\r\n\r\n for x in range(0,5):\r\n\r\n c = a + str(x)\r\n c = c + zemlja\r\n print (c)\r\n\r\n\r\n page = requests.get(c)\r\n\r\n\r\n\r\n tree = html.fromstring(page.text)\r\n\r\n\r\n links = tree.xpath('//div[@class=\"thumb_div\"]/a/@href')\r\n\r\n for j in range(0,len(links)):\r\n new = requests.get(links[j])\r\n tree1 = html.fromstring(new.text)\r\n\r\n vrsta = tree1.xpath('//strong[text()=\"Vrsta\"]')\r\n opis = tree1.xpath('//strong[text()=\"Opis\"]')\r\n\r\n naslovi = tree1.xpath('//h3/text()')\r\n lokacija = tree1.xpath('//strong[text()=\"Lokacija\"]')\r\n podrucje = tree1.xpath('//strong[contains(text(),\"Podru\")]')\r\n adresa = tree1.xpath('//strong[text()=\"Adresa\"]')\r\n\r\n cijena = tree1.xpath('//strong[(text()=\"Cijena\") or (text()=\"Cena\")]')\r\n godinaizgradnje = tree1.xpath('//strong[text()=\"Godina Gradnje\"]')\r\n spavacihsoba = tree1.xpath('//strong[contains(text(),\" Soba\")]')\r\n povrsina = tree1.xpath('//strong[contains(text(),\"Stambena Povr\")]')\r\n zemljiste = tree1.xpath('//strong[contains(text(),\"Zemlji\")]')\r\n datumunosa = tree1.xpath('//strong[(text()=\"Zadnja Promjena\") or (text()=\"Zadnja Promena\")]')\r\n oglasio = tree1.xpath('//div[@id=\"aboutAuthor\"]/a/text()')\r\n brojtel = tree1.xpath('//strong[text()=\"Mobitel\"]')\r\n\r\n\r\n slika = tree1.xpath('//a[@class=\"fancybox\"]/@href')\r\n\r\n\r\n\r\n for g in range(0, 1):\r\n\r\n opis[g] = opis[g].tail.encode('utf-8')[2:]\r\n vrsta[g] = vrsta[g].tail.encode('utf-8')[2:]\r\n if naslovi:\r\n naslovi[g] = naslovi[g].encode('utf-8')\r\n else:\r\n naslovi.append(\"\")\r\n print (naslovi[g])\r\n if lokacija:\r\n lokacija[g] = lokacija[g].tail.encode('utf-8')[2:]\r\n else:\r\n lokacija.append(\"\")\r\n if podrucje:\r\n podrucje[g] = podrucje[g].tail.encode('utf-8')[2:]\r\n else:\r\n naselje.append(\"\")\r\n if adresa:\r\n adresa[g] = adresa[g].tail.encode('utf-8')[2:]\r\n else:\r\n adresa.append(\"\")\r\n if cijena:\r\n cijena[g] = (cijena[g].tail.encode('utf-8')[2:])\r\n else:\r\n cijena.append(\"\")\r\n if godinaizgradnje:\r\n godinaizgradnje[g] = (godinaizgradnje[g].tail.encode('utf-8')[2:])\r\n else:\r\n godinaizgradnje.append(\"\")\r\n if spavacihsoba:\r\n spavacihsoba[g] = (spavacihsoba[g].tail.encode('utf-8')[2:])\r\n else:\r\n spavacihsoba.append(\"\")\r\n if povrsina:\r\n povrsina[g] = (povrsina[g].tail.encode('utf-8')[2:])\r\n else:\r\n povrsina.append(\"\")\r\n if zemljiste:\r\n zemljiste[g] = (zemljiste[g].tail.encode('utf-8')[2:])\r\n else:\r\n zemljiste.append(\"\")\r\n if datumunosa:\r\n datumunosa[g] = (datumunosa[g].tail.encode('utf-8')[2:])\r\n else:\r\n datumunosa.append(\"\")\r\n if oglasio:\r\n oglasio[g] = (oglasio[g].encode('utf-8'))\r\n else:\r\n oglasio.append(\"\")\r\n\r\n if brojtel:\r\n brojtel[g] = (brojtel[g].tail.encode('utf-8')[2:])\r\n else:\r\n brojtel.append(\"\")\r\n slika.append(\"\")\r\n slika.append(\"\")\r\n slika.append(\"\")\r\n slika.append(\"\")\r\n slika.append(\"\")\r\n\r\n if slika:\r\n\r\n for o in range(0,len(slika)):\r\n slika[o] = (slika[o].encode('utf-8'))\r\n\r\n\r\n\r\n\r\n cursor = cnx.cursor()\r\n\r\n if counter1 == 0:\r\n prodajailiizdavanje=\"Prodaja\"\r\n else:\r\n prodajailiizdavanje=\"Izdavanje\"\r\n\r\n\r\n cursor.execute(\"INSERT IGNORE INTO nekretnine (drzava,opis,vrsta,naslov,podrucje,lokacija,adresa,cijena,godinaizgradnje,spavacihsoba, \\\r\n povrsina,zemljiste,datumunosa,oglasio,brojtel,slika1,slika2,slika3,prodajaizdavanje) \\\r\n VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\", (b[counter], opis[g], vrsta[g],naslovi[g],podrucje[g],\r\n lokacija[g],adresa[g],cijena[g],\r\n godinaizgradnje[g],spavacihsoba[g],\r\n povrsina[g],zemljiste[g],datumunosa[g],\r\n oglasio[g],brojtel[g],slika[0],slika[1],\r\n slika[2], prodajailiizdavanje))\r\n cursor.fetchone()\r\n print(\"affected rows = {}\".format(cursor.rowcount))\r\n\r\n print('\\n')\r\n cursor.close()\r\n\r\ncursor = cnx.cursor()\r\ncursor.execute(\"update nekretnine set datumunosa = replace(datumunosa, ',', '')\")\r\ncursor.execute(\"update nekretnine set drzava = replace(drzava, '+', ' ')\")\r\ncursor.close()\r\ncnx.close()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"scrap_ads.py","file_name":"scrap_ads.py","file_ext":"py","file_size_in_byte":6711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"19621378","text":"import datetime\nimport sys\nimport torch\n\ndef printoneline(*argv):\n s = ''\n for arg in argv: s += str(arg) + ' '\n s = s[:-1]\n sys.stdout.write('\\r'+s)\n sys.stdout.flush()\n\ndef dt():\n return datetime.datetime.now().strftime('%H:%M:%S')\n\ndef freeze_model(model):\n# model.train(False)\n model.eval()\n for params in model.parameters():\n params.requires_grad = False\n\ndef unfreeze_model(model):\n for params in model.parameters():\n params.requires_grad = True\n\ndef KFold(n=6000, n_folds=10, shuffle=False):\n folds = []\n base = list(range(n))\n for i in range(n_folds):\n test = base[i*n//n_folds:(i+1)*n//n_folds]\n train = list(set(base)-set(test))\n folds.append([train,test])\n return folds\n\ndef save_model(model, model_ckpt_path, multigpu_mode=False):\n if multigpu_mode:\n model_state = model.module.state_dict()\n else:\n model_state = model.state_dict()\n torch.save(model_state, model_ckpt_path)\n \ndef load_model(model, model_ckpt_path, multigpu_mode, use_cuda=True):\n model_state_dict = torch.load(model_ckpt_path, map_location=lambda storage, loc: storage)\n model.load_state_dict(model_state_dict)\n if multigpu_mode:\n model = torch.nn.DataParallel(model)\n if use_cuda:\n model = model.cuda()\n return model","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"464129854","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\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-i686/egg/klog.py\n# Compiled at: 2011-12-03 15:03:14\nimport sys, time\nDEFAULT_FORMAT_STR = '%(info_fmt_start)s[%(time)s] %(logger)s > %(channel)s%(info_fmt_end)s %(msg_fmt_start)s%(level)s: %(msg)s%(msg_fmt_end)s'\n\nclass Output(object):\n \"\"\"Formats the log messages and outputs them.\n \n .. note::\n \n This is an abstract class and should not be instantaniated. Instead,\n subclasses should override the :method:`Output.log` method.\n \n Attributes:\n `formatstr` (str):\n The format string for the messages. It uses normal Python string\n formatting syntax with keyword arguments. The available keywords\n are:\n \n %(logger)s:\n The name of the logger.\n %(channel)s:\n The name of the channel.\n %(level)s:\n The name of the level.\n %(msg)s:\n The actual log message.\n %(time)s:\n The current time, as returned by :func:\n \"\"\"\n\n def __init__(self, formatstr=DEFAULT_FORMAT_STR):\n \"\"\"\n Args:\n `formatstr` (str):\n The format string for the messages. Defaults to\n DEFAULT_FORMAT_STR.\n \"\"\"\n self.formatstr = formatstr\n\n def log(self, logger, channel, level, msg):\n \"\"\"Logs a message. On the base class :class:`Output` this is just a\n stub method.\n \n Args:\n `logger` (:class:`Logger`):\n The logger that sent the message.\n `channel` (:class:`Channel`):\n The channel that collected the message.\n `level` (:class:`Level`):\n The level of the message.\n `msg` (str):\n The log message\n \"\"\"\n pass\n\n def format_msg(self, logger, channel, level, msg):\n \"\"\"Formats a message using the `formatstr` attribute.\n \n Args:\n `logger` (:class:`Logger`):\n The logger that sent the message.\n `channel` (:class:`Channel`):\n The channel that collected the message.\n `level` (:class:`Level`):\n The level of the message.\n `msg` (str):\n The log message.\n \n Returns:\n The formatted message.\n \"\"\"\n d = {'logger': logger.name, \n 'channel': channel.name, \n 'level': level.name, \n 'msg': msg, \n 'time': time.asctime(), \n 'info_fmt_start': level.info_fmt_start, \n 'info_fmt_end': level.info_fmt_end, \n 'msg_fmt_start': level.msg_fmt_start, \n 'msg_fmt_end': level.msg_fmt_end}\n return self.formatstr % d\n\n\nclass StreamOutput(Output):\n \"\"\"A subclass of :class:`Output` that sends output to a file-like\n object.\n \n Attributes:\n `formatstr` (str):\n The format string for the messages. See the documentation for\n :class:`Output` for information on its format.\n `stream` (file-like object):\n The object to send output to. It must have a `write()` method.\n `use_ansi_escapes` (bool):\n Whether to use ANSI escape codes to show visually formatted\n messages. Only really useful if the output stream is stdout.\n \n \"\"\"\n\n def __init__(self, stream=None, formatstr=DEFAULT_FORMAT_STR):\n \"\"\"\n \n Args:\n `stream` (file-like object):\n The object to send output to. It must have a `write()` method.\n `formatstr` (str):\n The format string for the messages. Defaults to\n DEFAULT_FORMAT_STR.\n `use_ansi_escapes` (bool):\n Whether to use ANSI escape codes to show visually formatted\n messages. Only really useful if the output stream is stdout.\n \n \"\"\"\n if stream is None:\n stream = sys.stdout\n self.formatstr = formatstr\n self.stream = stream\n return\n\n def log(self, logger, channel, level, msg):\n \"\"\"Logs a message.\n \n Args:\n `logger` (:class:`Logger`):\n The logger that sent the message.\n `channel` (:class:`Channel`):\n The channel that collected the message.\n `level` (:class:`Level`):\n The level of the message.\n `msg` (str):\n The log message.\n \"\"\"\n formatted = self.format_msg(logger, channel, level, msg)\n self.stream.write(formatted + '\\n')\n\n\nclass FileOutput(StreamOutput):\n\n def __init__(self, fname, formatstr=DEFAULT_FORMAT_STR):\n self.formatstr = formatstr\n self.stream = open(fname, 'w')\n\n def __del__(self):\n self.stream.close()\n\n\nclass Filter(object):\n\n def __init__(self):\n pass\n\n def allow(self, logger, channel, level, msg):\n return True\n\n\nclass LevelFilter(object):\n\n def __init__(self, minlevel=0.0, maxlevel=1.0):\n if isinstance(minlevel, str):\n minlevel = LevelManager.get(minlevel)\n if isinstance(minlevel, Level):\n minlevel = minlevel.priority\n if isinstance(maxlevel, str):\n maxlevel = LevelManager.get(maxlevel)\n if isinstance(maxlevel, Level):\n maxlevel = maxlevel.priority\n self.minlevel = minlevel\n self.maxlevel = maxlevel\n\n def allow(self, logger, channel, level, msg):\n return level.priority >= self.minlevel and level.priority <= self.maxlevel\n\n\nclass Channel(object):\n\n def __init__(self, name, outputs=None, filters=None):\n if outputs is None:\n outputs = [\n StreamOutput()]\n if filters is None:\n filters = []\n self.name = name\n self.outputs = outputs\n self.filters = filters\n return\n\n def add_output(self, output):\n self.outputs.append(output)\n\n def add_filter(self, filter):\n self.filters.append(filter)\n\n def log(self, logger, level, msg, channel=None):\n if channel is None:\n channel = self\n for filter in self.filters:\n if not filter.allow(logger, channel, level, msg):\n return\n\n for output in self.outputs:\n output.log(logger, channel, level, msg)\n\n return\n\n\nclass RedirectionChannel(Channel):\n\n def __init__(self, name, dest):\n self.name = name\n if isinstance(dest, str):\n dest = ChannelManager.get(dest)\n if dest is None:\n raise ValueError('Invalid channel')\n self.dest = dest\n return\n\n def log(self, logger, level, msg):\n self.dest.log(logger, level, msg, self)\n\n\nclass Level(object):\n\n def __init__(self, name, priority):\n self.name = name.upper()\n self.priority = priority\n self.info_fmt_start = ''\n self.info_fmt_end = ''\n self.msg_fmt_start = ''\n self.msg_fmt_end = ''\n\n\ndef set_ansi_colour(level, clr):\n level.msg_fmt_start = '\\x1b[3%dm' % clr\n level.msg_fmt_end = '\\x1b[m'\n return level\n\n\nclass ObjectManagerClass(object):\n\n def __init__(self):\n self.objects = {}\n\n def add(self, obj):\n self.objects[obj.name.lower()] = obj\n\n def get(self, name):\n return self.objects.get(name.lower(), None)\n\n\nChannelManager = ObjectManagerClass()\nChannelManager.add(Channel('main'))\nLevelManager = ObjectManagerClass()\nLevelManager.add(set_ansi_colour(Level('DEBUG', 0.1), 4))\nLevelManager.add(set_ansi_colour(Level('INFO', 0.3), 6))\nLevelManager.add(set_ansi_colour(Level('WARNING', 0.5), 3))\nLevelManager.add(set_ansi_colour(Level('ERROR', 0.8), 1))\nLevelManager.add(set_ansi_colour(Level('FATAL', 1.0), 5))\n\nclass Logger(object):\n\n def __init__(self, name):\n self.name = name\n\n def log(self, channel, level, msg):\n if isinstance(channel, str):\n channel = ChannelManager.get(channel)\n if channel is None:\n raise ValueError('Invalid channel')\n if isinstance(level, str):\n level = LevelManager.get(level)\n if level is None:\n raise ValueError('Invalid level')\n channel.log(self, level, msg)\n return","sub_path":"pycfiles/KLog-0.4.0-py2.6/klog.py","file_name":"klog.py","file_ext":"py","file_size_in_byte":7957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"524606016","text":"# -*- coding:utf8 -*-\nfrom django.conf import settings\nfrom django.conf.urls.defaults import *\nfrom django.views.generic.simple import direct_to_template\nfrom django.conf.urls.defaults import patterns, url\nfrom TripleMag.apps.mall.models import Category,CategoryFirst,CategorySecond,Product,mall_index,mall_ad\nfrom TripleMag.apps.management.models import notice_mall\nfrom TripleMag.apps.mall.views import *\nfrom TripleMag.apps.mall.forms import MallIndexForm,MallAdForm,NoticeMallForm\n\n\nurlpatterns = patterns('',\n url(r'mall_management/$', index,{'template_name':'mall/mall_base.html'},'mall_management_index'),\n url(r'^category_change/$',change_category,name = \"change_category\"),\n url(r'mall_management/category_index/$',category_index,{'template_name':'management/mall/mall_index_mag.html'},name='mall_category_index'),\n url(r'^mall_management/delete_category_1st/(?P.*)/$',delete_category,{'model':Category}),\n url(r'^mall_management/delete_category_2nd/(?P.*)/$',delete_category,{'model':CategoryFirst}),\n url(r'^mall_management/delete_category_3rd/(?P.*)/$',delete_category,{'model':CategorySecond}),\n #删除产品\n url(r'^mall_management/delete_product/(?P.*)/$',delete_category,{'model':Product}),\n #商城主页设置\n url(r'^mall_home_mag/(?P.*)$',mall_home_mag,{'model':mall_index,'form':MallIndexForm,'template_name':'management/mall/mall_home_mag.html'},name=\"mall_home_mag\"),\n #商城推广设置\n url(r'^mall_ad/(?P.*)$',mall_home_mag,{'model':mall_ad,'form':MallAdForm,'template_name':\"management/mall/mall_ad.html\"},name=\"mall_ad\"),\n #添加商城首页图片\n url(r'add_home_mag/$',add_home_mag,name=\"add_home_mag\"),\n #添加商城公告\n url(r'add_mall_notice/$',add_mall_notice,name=\"add_mall_notice\"),\n #添加商城推广\n url(r'add_mall_ad/$',add_mall_ad,name=\"add_mall_ad\"),\n \n #商城公告设置\n url(r'^mall_notice/(?P.*)$',mall_home_mag,{'model':notice_mall,'form':NoticeMallForm,'template_name':\"management/mall/mall_new_Announcement.html\"},name=\"mall_notice\"),\n url(r'^mall_management/product_list/$',product_list,{'template_name':'management/mall/product_list.html'},name='product_list'),\n url(r'mall_management/category/(?P\n\n\n
Play Tic Tac Toe!
\n\n
\n

Login Below!

\n User:
\n Pass:
\n \n

\n\n\n
\n

Register Below!

\n User:
\n Pass:
\n \n
\n'''\n\n def getNotFoundPage(self):\n return 'Status 404: Resource not found'\n\n def getNotLoginPage(self):\n return 'Not logged in Login'\n\n def getAccountPage(self, username, won, lost, join_game_id):\n join_game_link = \"\"\n if join_game_id != 0:\n join_game_link = \"Join an existing game\".format(join_game_id)\n\n logout = \"Log Out\"\n\n create_game = \"Create a new game\".format(username)\n page = self.getAccountPageStr()\n\n page = page.format(username, join_game_link, create_game, logout)\n #page = page.format(username, won, lost, join_game_link, create_game, logout)\n page = page.replace('...', '}', 3)\n page = page.replace('..', '{', 3)\n return page\n\n def getGamePage(self, gameId, user, u1, u2, win1, win2, nextTurn, gameBoard):\n\n pos = gameBoard.getPositions()\n links = [''] * 10\n for i in range(1, 10):\n if pos[i] == 'X':\n links[i] = 'X'\n elif pos[i] == 'O':\n links[i] = 'O'\n else:\n if user == u1 and nextTurn == 'O' or user == u2 and nextTurn == 'X':\n links[i] = '_'\n elif gameBoard.isBoardFull() == True or win1 == True or win2 == True:\n links[i] = '_'\n else:\n links[i] = \"?\".format(gameId, i)\n # if there is a winner, end the game and display message\n\n\n\n\n page = self.getGamePageStrHead()\n\n account = \"Go back to account screen.\"\n page = page.format(gameId, links[7] , links[8], links[9], links[4], links[5], links[6], links[1], links[2], links[3], u1, u2, account)\n\n waitStr = self.getGamePageStrWait()\n winStr = self.getGamePageStrWin()\n loseStr = self.getGamePageStrLose()\n tieStr = self.getGamePageStrTie()\n\n if user == u1 and nextTurn == 'O' or user == u2 and nextTurn == 'X':\n page = page + waitStr\n\n if win1 == True and win2 == False:\n winStr = winStr.format(u1)\n loseStr = loseStr.format(u2)\n page = page + winStr + loseStr\n\n elif win1 == False and win2 == True:\n winStr = winStr.format(u2)\n loseStr = loseStr.format(u1)\n page = page + winStr + loseStr\n\n elif gameBoard.isBoardFull() == True and win1 == False and win2 == False:\n page = page + tieStr\n\n page = page + self.getGamePageStrTail()\n\n page = page.replace('...', '}')\n page = page.replace('..', '{')\n\n return page\n\n def getGamePageStrHead(self):\n return '''\n\n\n\n \n \n \n Playing Tic Tac Toe!\n\n\n\n
\n\n\n\n\n
Tic Tac Toe Game
\n
Game ID: {}
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
{}{}{}
{}{}{}
{}{}{}
\n
\n\n\n\n

User 1: {}

\n

User 2: {}

\n\n

{}

\n\n\n'''\n\n def getGamePageStrWait(self):\n return '

Waiting for opponent\\'s move

'\n\n def getGamePageStrWin(self):\n return '
{} wins!
'\n\n def getGamePageStrLose(self):\n return '
{} loses!
'\n\n def getGamePageStrTie(self):\n return '
The game is a tie!
'\n\n\n\n def getGamePageStrTail(self):\n return ''\n\n def getAccountPageStr(self):\n return '''\n\n\n\n \n \n \n Player's Account\n\n\n\n\n
\n\n
Tic Tac Toe Lobby


\n\n

User Info

\n\n\n

Account: {}


\n\n

Play Now!

\n\n

{}

\n

{}

\n
\n

{}

\n\n\n\n'''\n","sub_path":"HtmlUtils.py","file_name":"HtmlUtils.py","file_ext":"py","file_size_in_byte":7004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"444905561","text":"class Joueur:\r\n \"\"\"Classe définissant un joueur de roulette caractérisé par :\r\n - son pseudo ;\r\n - son porte monnaie ;\r\n - un numéro misé\r\n - une somme misée \"\"\"\r\n\r\n \r\n def __init__(self, pseudo, porte_monnaie, numero_mise, somme_misee):\r\n \"\"\"Constructeur de notre classe\"\"\"\r\n self.pseudo = pseudo\r\n self.porte_monnaie = porte_monnaie\r\n self.numero_mise = numero_mise\r\n self.somme_misee = somme_misee\r\n\r\n def nom_joueur(self, pseudo):\r\n \"\"\"Méthode permettant de vérifier que le nom du joueur n'est pas un chiffre et de l'afficher \"\"\"\r\n NomCorrect = False\r\n while NomCorrect == False :\r\n self.pseudo = input(\"Quel est votre nom ?\")\r\n #self.pseudo = 'Anonyme' if len(self.pseudo) == 0 else self.pseudo\r\n try:\r\n int(self.pseudo) != False\r\n except ValueError:\r\n print(\"Bienvenue {} sur la table de la Roulette du Zcasino !\".format(self.pseudo))\r\n NomCorrect = True\r\n else :\r\n print(\"Il y a une erreur, êtes vous certain de votre frappe ?\")\r\n\r\n\r\n\r\n def argent_joueur(self, porte_monnaie):\r\n \"\"\"Méthode permettant de vérifier que le joueur a de l'argent pour jouer\"\"\"\r\n Argent = False\r\n while Argent == False :\r\n self.porte_monnaie = input(\"\\nAvec quelle somme d'argent souhaitez vous jouer ? \")\r\n try:\r\n int(self.porte_monnaie) != False\r\n except ValueError:\r\n print(\"Il y a une erreur, êtes vous certain de votre frappe ?\")\r\n else :\r\n self.porte_monnaie = int(self.porte_monnaie)\r\n if self.porte_monnaie < 1 :\r\n print(\"Vous ne pouvez pas jouer sans argent !\")\r\n else :\r\n Argent = True\r\n\r\n def num_joueur(self, numero_mise):\r\n \"\"\"Méthode permettant de vérifier que le joueur a bien misé sur un numéro de la roulette\"\"\"\r\n Numero = False\r\n while Numero == False :\r\n self.numero_mise = input(\"\\nSur quel numéro souhaitez vous miser (entre 0 et 49) ? : \")\r\n try:\r\n int(self.numero_mise) != False\r\n except ValueError:\r\n print(\"Il y a une erreur, êtes vous certain de votre frappe ?\")\r\n else :\r\n self.numero_mise = int(self.numero_mise)\r\n if self.numero_mise < 0 or self.numero_mise > 49:\r\n print(\"Le numéro choisi n'existe pas, veuillez en choisir un autre !\")\r\n else :\r\n Numero = True\r\n \r\n def mise_joueur(self, somme_misee):\r\n \"\"\" Methode permettant de vérifier que le joueur mise l'argent qu'il a dans son porte monnaie \"\"\"\r\n Mise = False\r\n while Mise == False :\r\n self.somme_misee = input(\"\\nQuelle somme souhaitez vous miser sur ce numéro ? : \")\r\n try:\r\n int(self.somme_misee) != False\r\n except ValueError :\r\n print(\"Etes vous certain de votre frappe ?\")\r\n else :\r\n self.somme_misee = int(self.somme_misee)\r\n if self.somme_misee < 0:\r\n print(\"Vous ne pouvez pas miser un nombre négatif !\")\r\n elif self.somme_misee > self.porte_monnaie:\r\n print(\"Vous n'avez pas assez d'argent !\")\r\n else :\r\n Mise = True\r\n\r\n\r\n","sub_path":"ZCasino/ZCasino_Orienté Objet/ZCasino_joueur.py","file_name":"ZCasino_joueur.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"266618182","text":"#!/usr/bin/env python\n\"\"\"\nS-curves have 7 phases\n- increase acceleration\n- constant acceleration\n- decrease acceleration\n- constant velocity\n- increase deceleration\n- constant deceleration\n- decrease deceleration\n\ncase 1\n - accel\n v = v_s + acc * t\n e = 0.5 * acc * t * t + v_s * t + s\ncase 2\n - accel cruise\n e = 0.5 * acc * a_t * a_t + v_s * a_t + s + v_c * c_t\ncase 3\n - accel then decel\n e = 0.5 * acc * a_t * a_t + v_s * a_t + s - 0.5 * dec * d_t * d_t - v_e * d_t\n - accel cruise then decel\n\ndon't enforce max accel\n\nfor polynomial paths\nhttp://www.springer.com/cda/content/document/cda_downloaddocument/9783540856283-c1.pdf?SGWID=0-0-45-615213-p173839603\n\"\"\"\n\nimport numpy\nimport pylab\n\n\napproximate = lambda v, t, e=0.001: abs(v - t) < e\n\n\ndef plot(ts, vs, xs, case, e, t, v_e):\n pylab.subplot(211)\n pylab.plot(ts, xs, color='b')\n pylab.scatter(ts, xs, color='b')\n pylab.axhline(e, color='b')\n pylab.axvline(t, color='k')\n xl = pylab.xlim()\n pylab.xlim(xl[0], xl[1]+0.5)\n yl = pylab.ylim()\n pylab.ylim(yl[0], yl[1]+0.5)\n pylab.title(\"Case %s: positon vs time\" % case)\n pylab.subplot(212)\n pylab.plot(ts, vs, color='g')\n pylab.scatter(ts, vs, color='g')\n pylab.axhline(v_e, color='g')\n pylab.axvline(t, color='k')\n xl = pylab.xlim()\n pylab.xlim(xl[0], xl[1]+0.5)\n yl = pylab.ylim()\n pylab.ylim(yl[0], yl[1]+0.5)\n pylab.title(\"Case %s: velocity vs time\" % case)\n pylab.show()\n\n\ndef test(\n s=0.0, e=3.0, t=2.0, dt=0.1,\n v_s=0., v_e=1., a_s=0., a_e=0.,\n a_max=10.0, d_max=10.0, v_max=10.0,\n order=3):\n xs, ts, vs, case = compute_motion_profile(\n s, e, t, dt, v_s, v_e, a_s, a_e, a_max, d_max, v_max,\n order)\n #xs = numpy.cumsum(vs * dt)\n plot(ts, vs, xs, case, e, t, v_e)\n\n\ndef polynomial_3(s, e, v_s, v_e, t):\n a0 = s\n a1 = v_s\n a2 = (\n (-3 * (s - e) - (2 * v_s + v_e) * t) /\n (t * t))\n a3 = (\n (2 * (s - e) + (v_s + v_e) * t) /\n (t * t * t))\n return lambda dt: a0 + a1 * dt + a2 * dt ** 2. + a3 * dt ** 3.\n\n\ndef polynomial_5(s, e, v_s, v_e, a_s, a_e, t):\n a0 = s\n a1 = v_s\n a2 = a_s * 0.5\n a3 = (\n (20 * (e - s) - (8 * v_e + 12 * v_s) * t - (3 * a_e - a_s) * t ** 2.) /\n (2. * t ** 3.))\n a4 = (\n (\n -30 * (e - s) + (14 * v_e + 16 * v_s) * t +\n (3 * a_e - 2 * a_s) * t ** 2.) /\n (2. * t ** 4.))\n a5 = (\n (12 * (e - s) - 6 * (v_e + v_s) * t + (a_e - a_s) * t ** 2.) /\n (2 * t ** 5.))\n return lambda dt: (\n a0 + a1 * dt + a2 * dt ** 2. + a3 * dt ** 3. +\n a4 * dt ** 4. + a5 * dt ** 5.)\n\n\ndef compute_point_velocities(pts, ts, v_s, v_e):\n # TODO not sure if this works for vs[0] != 0 and vs[-1] != 0\n ss = [v_s]\n # first compute point-to-point slopes\n for i in xrange(1, len(pts) - 1):\n ss.append((pts[i] - pts[i - 1]) / (ts[i] - ts[i - 1]))\n ss.append(v_e)\n # then compute velocities\n vs = []\n for i in xrange(len(ss) - 1):\n if numpy.sign(ss[i]) == numpy.sign(ss[i + 1]):\n vs.append(0.5 * (ss[i] + ss[i + 1]))\n else:\n vs.append(0.)\n vs[0] = v_s\n vs.append(v_e)\n return vs\n\n\ndef compute_motion_profile(\n s=0.0, e=3.0, t=2.0, dt=0.1,\n v_s=0., v_e=1., a_s=0., a_e=0.,\n a_max=10.0, d_max=10.0, v_max=10.0,\n order=5):\n n = int(numpy.ceil(t / float(dt)))\n #d = abs(e - s)\n\n ts = numpy.linspace(0, t, n)\n if order == 3:\n p = polynomial_3(s, e, v_s, v_e, t)\n elif order == 5:\n p = polynomial_5(s, e, v_s, v_e, a_s, a_e, t)\n pts = [p(tp) for tp in ts]\n vs = compute_point_velocities(pts, ts, v_s, v_e)\n #vs[0] = v_s\n #vs[-1] = v_e\n return pts, ts, vs, -1\n\n\ndef compute_motion_profile_old(\n s=0.0, e=3.0, t=2.0, dt=0.1,\n v_s=0., v_e=1.,\n a_max=10.0, d_max=10.0, v_max=10.0):\n \"\"\"\n Compute a motion profile\n\n Args:\n ------\n s : starting position\n e : ending position\n t : time to complete movement\n dt : time resolution of movement\n v_s : starting velocity\n v_e : ending velocity\n a_max : maximum acceleration\n d_max : maximum deceleration\n v_max : maximum velocity\n \"\"\"\n n = int(numpy.ceil(t / float(dt)))\n d = abs(e - s)\n v_avg = d / t\n\n ts = numpy.linspace(0, t, n)\n case = None\n acc = abs(v_e - v_s) / t # TODO cap acceleration\n if acc > a_max:\n raise Exception(\n \"Movement requires acceleration[%s] over max [%s]\"\n % (acc, a_max))\n\n # case 1: accel\n print(\"case 1?\")\n ep = 0.5 * acc * t * t + v_s * t + s\n print(\"ep, e: %s, %s\" % (ep, e))\n if approximate(ep, e):\n case = 1\n vs = numpy.linspace(v_s, v_e, n)\n return ts, vs, case\n\n if v_s == v_e and s != e:\n # accel then decel\n raise NotImplementedError\n # case 2: accel cruise\n print(\"case 2?\")\n acc_t = (e - s - v_e * t) / (0.5 * abs(v_e - v_s) + v_s - v_e)\n print(\"acc_t: %s\" % acc_t)\n if acc_t > 0.:\n acc = abs(v_e - v_s) / acc_t\n c_t = t - acc_t\n if c_t > 0:\n ep = c_t * v_e + 0.5 * acc * acc_t * acc_t + v_s * acc_t + s\n if c_t > 0 and approximate(ep, e):\n case = 2\n vs = numpy.ones_like(ts) * v_e\n am = ts < acc_t\n vs[am] = numpy.linspace(v_s, v_e, sum(am))\n return ts, vs, case\n\n # case 3: accel then decel, accel cruise then decel\n raise NotImplementedError\n\n\npylab.ion()\ntest(s=0.0, e=0.5, t=1.0, v_e=1.0, order=3) # case 3\npylab.figure()\ntest(s=0.0, e=0.5, t=1.0, v_e=1.0, order=5) # case 3\npylab.figure()\ntest(s=0.0, e=2.0, t=2.0, v_e=1.0, order=3) # case 2\npylab.figure()\ntest(s=0.0, e=2.0, t=2.0, v_e=1.0, order=5) # case 2\npylab.ioff()\npylab.show()\n","sub_path":"tests/motion_control.py","file_name":"motion_control.py","file_ext":"py","file_size_in_byte":5872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"117745280","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 21 20:21:47 2017\n\n@author: meyavuz\n\"\"\"\n\nclass Node(object):\n \n def __init__(self, key=None, left=None, right=None, parent=None, height=None):\n self.key = key\n self.left = left\n self.right = right\n self.parent = parent\n self.height = height\n\n def __repr__(self):\n# return 'Node: key:{}, left:{}, right:{}, parent:{}'.format(self.key, self.left, self.right, self.parent)\n return 'k:{}'.format(self.key)\n\n#class Tree(object):\nclass BST(object):\n \n def __init__(self, arr=None):\n self.arr = arr\n \ndef CreateSampleTree():\n# /* 6\n# / \\\n# 10 2\n# / \\ / \\\n# 1 3 7 12\n# 10 and 2 are swapped\n# */ \n # Swapped BST\n root = Node(6, \n Node(10, Node(1), Node(3)), \n Node(2, Node(7), Node(12)) )\n \n# # Okay BST\n# root = Node(6, \n# Node(2, Node(1), Node(3)), \n# Node(10, Node(7), Node(12)) )\n \n return root\n\ndef InOrderTRAVERSE(root):\n\n if root.left:\n InOrderTRAVERSE(root.left)\n \n print('{}, '.format(root.key), end='')\n \n if root.right:\n root = InOrderTRAVERSE(root.right)\n \n\ndef FindSwappedNodes(root, prev, first, second):\n\n if first and second:\n \n first.key, second.key = second.key, first.key\n\n \n if root.left:\n prev, first, second = FindSwappedNodes(root.left, prev, first, second)\n \n \n if (prev and root.key < prev.key):\n print('Problematic prev: {}'.format(prev))\n if first and not second:\n second = root\n if not first:\n first = prev\n \n \n \n print('current: {}\\t prev: {}'.format(root.key, prev))\n prev = root\n \n if root.right:\n# prev = root\n prev, first, second = FindSwappedNodes(root.right, prev, first, second)\n \n\n return prev, first, second\n\ndef main():\n\n root = CreateSampleTree()\n print('Original BST InOrderTraversal:')\n InOrderTRAVERSE(root)\n print('\\n')\n\n prev, first, second = FindSwappedNodes(root, None, None, None)\n \n print('\\nFirst : {}'.format(first))\n print('Second: {}'.format(second))\n\n print('After swapping BST InOrderTraversal:')\n InOrderTRAVERSE(root)\n\n\nif __name__ == '__main__':\n main()","sub_path":"mulakat/EPI15_BinarySearchTrees/swapnodesofBST2.py","file_name":"swapnodesofBST2.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"123866169","text":"from expand import expand\nimport heapq\n\n\n# PEP8 naming convention?\nclass OrderedPath:\n\n # list of locations\n def __init__(self):\n self.loc = []\n\n # add_loc :\n # need to add location `start` to an ordered list\n def add_loc(self, traveled, precedence):\n return heapq.heappush(self.loc, (traveled, precedence))\n\n # rem_loc :\n # need to move location (by popping end of list) to `visited list`\n def rem_loc(self):\n return heapq.heappop(self.loc)\n\n # list_not_empty : list -> boolean\n # if the list is empty, return true\n def list_not_empty(self):\n return len(self.loc) > 0\n\n\ndef a_star_search(dis_map, time_map, start, end):\n # steps:\n # from start, calculate all adjacent locations' cost :\n # f(n) = time_to(n) + dis(n)\n\n # initialize:\n path = [] # list of strings ONLY\n time_to_next_loc = {}\n time_to_next_loc[start] = 0\n loc_ordered = OrderedPath()\n loc_ordered.add_loc(0, [start]) # precedence = 0, and travel = START\n visited_list = set() # UNORDERED, but doesn't matter\n\n # function:\n # while not empty, do things\n # NOTE: loc_ordered is a list of paths\n while loc_ordered.list_not_empty() == True:\n # add removed to list of removed\n just_removed = loc_ordered.rem_loc()\n\n # if latest removed was not visited before, add to list of visited\n if just_removed[-1][-1] not in visited_list:\n visited_list.add(just_removed[-1][-1])\n\n # if latest removed is the endpoint, this is the final path\n if just_removed[-1][-1] == end:\n path = just_removed[-1]\n return path\n\n else:\n # for each adjacent location, add a time and distance (cost) measure\n for loc in expand(just_removed[-1][-1], time_map):\n\n # g(n)\n gn = time_map[just_removed[-1][-1]][loc] + \\\n time_to_next_loc[just_removed[-1][-1]]\n\n # h(n)\n hn = dis_map[loc][end]\n\n # f(n)\n fn = gn + hn\n\n # add shortest to ordered list\n if loc not in time_to_next_loc.keys() or time_to_next_loc[loc] > gn:\n time_to_next_loc[loc] = gn\n append_loc = just_removed[-1].copy()\n append_loc.append(loc)\n loc_ordered.add_loc(fn, append_loc)\n return path\n","sub_path":"Q2/MSAI 348 - Introduction to AI/HW/3-a-star-search/student_code.py","file_name":"student_code.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"414404392","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 6 22:12:07 2018\n\n@author: Think\n\"\"\"\n\nclass Solution:\n def setZeroes(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: void Do not return anything, modify matrix in-place instead.\n \"\"\"\n m = len(matrix)\n n = len(matrix[0])\n if m == 0:\n return\n for i in range(m):\n for j in range(n):\n if matrix[i][j] == 0:\n for k in range(n):\n if matrix[i][k] != 0:\n matrix[i][k] = 'o'\n for k in range(m):\n if matrix[k][j] != 0:\n matrix[k][j] = 'o'\n \n for i in range(m):\n for j in range(n): \n if matrix[i][j] == 'o':\n matrix[i][j] = 0\n \nif __name__ == '__main__':\n matrix = [[1,1,0],[1,1,1],[1,0,1]]\n matrix = [[0]]\n matrix = [[0,0,0,5],[4,3,1,4],[0,1,1,4],[1,2,1,3],[0,0,1,1]]\n Solution().setZeroes(matrix)\n print(matrix)","sub_path":"73.Set Matrix Zeroes.py","file_name":"73.Set Matrix Zeroes.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"375874391","text":"from django.conf.urls.defaults import patterns, url\nfrom django.contrib.auth.decorators import login_required\nfrom riot import views\n\n\nurlpatterns = patterns('riot.views',\n url(r'^(?P[a-z0-9-]+)$', views.EventView.as_view(),\n name='riot-event'),\n url(r'^(?P[a-z0-9-]+)/preregister$',\n views.PreregistrationView.as_view(),\n name='riot-preregister'),\n url(r'^(?P[a-z0-9-]+)/preregister/success$',\n views.PreregisterSuccessView.as_view(),\n name='riot-preregister-success'),\n url(r'^(?P[a-z0-9-]+)/register$',\n views.RegistrationView.as_view(),\n name='riot-register'),\n url(r'^(?P[a-z0-9-]+)/tournament-numbers$',\n views.TournamentNumbersView.as_view(),\n name='riot-tournament-numbers'),\n url(r'^(?P[a-z0-9-]+)/equipment-numbers$',\n views.EquipmentNumbersView.as_view(),\n name='riot-equipment-numbers'),\n url(r'^(?P[a-z0-9-]+)/volunteers$',\n login_required(views.VolunteerListView.as_view()),\n name='riot-equipment-numbers'),\n url(r'^$', views.LatestEventView.as_view()),\n)\n","sub_path":"riot/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"510213616","text":"import re\n\n\ndef main():\n data = {}\n WorldValues = []\n Rules = []\n tophalf = []\n Weights = []\n values = []\n ValueDict = []\n\n\n file = input(\"Please enter file name:\")\n openfile = open(file, \"r\")\n openfile = (re.split(r'\\n\\n', openfile.read()))\n CrispValues(Rules, openfile, data, WorldValues)\n GetMembership(WorldValues, values, openfile, ValueDict)\n GetFormula(openfile, ValueDict, tophalf, Weights)\n print(\"The values at the top of the final equation are \" + str(tophalf))\n print(\"The values on the bottom of the final equation are \" + str(Weights))\n\n\ndef GetFormula(openfile, ValueDict, tophalf, Weights):\n RuleList = openfile[1]\n Rules = RuleList.split(\"\\n\")\n for i in range(0, len(Rules)):\n SplitRules = Rules[i].split(\" \")\n conditions = {SplitRules[4]: SplitRules[6], SplitRules[9]: SplitRules[11]}\n output = {SplitRules[14]: SplitRules[17]}\n RulesDict = {\"Rule\": SplitRules[1], \"Conditions\": conditions, \"Operator\": SplitRules[7],\n \"output_name\": SplitRules[14], \"Output\": SplitRules[17]}\n\n PotentialWs = []\n w1 = 0\n for Entry in ValueDict:\n if SplitRules[7] == 'and':\n if Entry['name'] == SplitRules[4]:\n #Check if equals 0\n if Entry['Fuzzy Values'][SplitRules[6]] > 0:\n PotentialWs.append(Entry['Fuzzy Values'][SplitRules[6]])\n else:\n pass\n elif Entry['name'] == SplitRules[9]:\n #Check if equals 0\n if Entry['Fuzzy Values'][SplitRules[11]] > 0:\n PotentialWs.append(Entry['Fuzzy Values'][SplitRules[11]])\n else:\n pass\n if len(PotentialWs) > 1:\n w1 = min(PotentialWs)\n else:\n pass\n\n\n\n elif SplitRules[7] == 'or':\n if Entry['name'] == SplitRules[4]:\n #Check if equals 0\n if Entry['Fuzzy Values'][SplitRules[6]] > 0:\n PotentialWs.append(Entry['Fuzzy Values'][SplitRules[6]])\n else:\n pass\n elif Entry['name'] == SplitRules[9]:\n #Check if equals 0\n if Entry['Fuzzy Values'][SplitRules[11]] > 0:\n PotentialWs.append(Entry['Fuzzy Values'][SplitRules[11]])\n else:\n pass\n if len(PotentialWs) > 0:\n w1 = max(PotentialWs)\n variable = 0\n counter = 0\n MembershipName = []\n MembershipTuples = []\n for i in range(2, len(openfile) - 1, 2):\n x = openfile[i].strip()\n MembershipName.append(x)\n y = openfile[i + 1].split(\"\\n\")\n MembershipTuples.append(y)\n\n Membership = dict(zip(MembershipName, MembershipTuples))\n while counter < w1:\n counter = 0\n for val in (Membership[SplitRules[14]]):\n if SplitRules[17] in val:\n goon = val.split(\" \")\n a = goon[1]\n b = goon[2]\n Alpha = goon[3]\n Beta = goon[4]\n e1 = curve(a, b, Alpha, Beta, 'name')\n counter = e1.membershipOf(variable)\n variable += 0.01\n wz = variable * w1\n if wz != 0:\n tophalf.append(wz)\n if w1 != 0:\n Weights.append(w1)\n return tophalf, Weights\n\ndef GetMembership(WorldValues, values, openfile, ValueDict):\n for entry in WorldValues:\n values.append(entry['name'])\n\n MembershipName = []\n MembershipTuples = []\n for i in range(2, len(openfile) - 1, 2):\n x = openfile[i].strip()\n MembershipName.append(x)\n y = openfile[i + 1].split(\"\\n\")\n MembershipTuples.append(y)\n\n Membership = dict(zip(MembershipName, MembershipTuples))\n for j in range(0, len(WorldValues)):\n x = WorldValues[j]\n var = x['name']\n Value = x['value']\n Membervals = {}\n for i in range(0, len(Membership)):\n tuple = (Membership[var])\n z = tuple[i].split(\" \")\n a = int(z[1])\n b = int(z[2])\n Alpha = int(z[3])\n Beta = int(z[4])\n e1 = curve(a, b, Alpha, Beta, 'name')\n Membervals[z[0]] = e1.membershipOf(Value)\n ValueDict.append(dict({\"name\": var, \"Fuzzy Values\": Membervals}))\n # print(ValueDict)\n return ValueDict\n\n\ndef CrispValues(Rules, openfile, data, WorldValues):\n RuleList = openfile[1]\n Rules = RuleList.split(\"\\n\")\n\n # Name of rulebase\n ruleBaseName = openfile[0]\n # Get crisp values\n RealWorldValues = openfile[len(openfile) - 1]\n\n RealWorldValues = RealWorldValues.split(\"\\n\")\n\n for x in range(0, len(RealWorldValues)):\n y = RealWorldValues[x].split(\" = \")\n if y is not None:\n WorldValues.append(dict({\"name\": y[0], \"value\": y[1]}))\n\n data[\"CrispValues\"] = WorldValues\n return Rules, data, WorldValues\n\n\nclass curve:\n name = \"\"\n\n def __init__(self, a, b, alpha, beta, name):\n self.a = int(a)\n self.b = int(b)\n self.alpha = int(alpha)\n self.beta = int(beta)\n self.name = name\n\n def CurveName(self):\n return self.name\n\n def membershipOf( self, value ):\n\n value = int(value)\n\n if(value < (self.a - self.alpha)):\n return 0\n elif(value in range (self.a - self.alpha, self.a)):\n return (value - self.a + self.alpha) / self.alpha\n elif(value in range(self.a,self.b)):\n return 1\n elif(value in range(self.b, self.b+self.beta)):\n return (self.b + self.beta - value) / self.beta\n elif(value > (self.b + self.beta)):\n return 0\n\n return\n\n\nif __name__ == '__main__':\n main()","sub_path":"GetFormula.py","file_name":"GetFormula.py","file_ext":"py","file_size_in_byte":6032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"270379477","text":"\r\ndef create_model(neurons=1, dropout=[0, 0 ], window_size=2,data_size=1,optimizer='nadam'):\r\n \r\n batch_size = 1\r\n Input_Layer = Input(shape=( window_size, data_size ))\r\n drop1 = Dropout(dropout[0])(Input_Layer)\r\n lstm = LSTM(neurons,kernel_initializer='glorot_normal')(drop1)\r\n drop2 = Dropout(dropout[1])(lstm)\r\n dense = Dense(1)((drop2))\r\n model = Model (inputs = Input_Layer, outputs = dense) \r\n model.compile(loss='mse', optimizer=optimizer, metrics=[tf.keras.metrics.RootMeanSquaredError()])\r\n \r\n return model\r\n\r\n\r\ndef test_models(mode = 'basic'):\r\n\r\n model_types = {'basic':['M','T','H'],\r\n 'advanced':['MH','MTH']}\r\n\r\n data_names = {'H':'total.npy', 'T':'TWEET_DATA.npy','M':'METEO_DATA.npy'}\r\n params = {'H':[8,[0,0],4,2], 'T':[90,[0.1,0],4,226],'M':[60,[0,0],4,104]}\r\n settings = params[model_type]\r\n window_size = settings[2]\r\n epochs = 50\r\n for forecast_horizon in range(1,4):\r\n for model_type in model_types:\r\n \r\n series_x = np.load(os.path.join(head_path, data_names[model_type]))\r\n series_y = np.load(os.path.join(head_path,'HEALTH_DATA.npy'))\r\n truth = np.load(os.path.join(head_path,'HEALTH_DATA.npy'))\r\n truth = truth[forecast_horizon:]\r\n series_x = series_x[:-forecast_horizon] \r\n series_y =series_y[forecast_horizon:]\r\n \r\n directory = r'/content/drive/MyDrive/Final Thesis Fragkozidis Georgios/C:/Users/skote/Desktop/New Method/Final Method'\r\n \r\n for test_set in range(0,10):\r\n model = create_model(settings[0],settings[1],settings[2],settings[3])\r\n X, y = sliding_window(series_x,window_size), sliding_window(series_y,window_size)\r\n train = list()\r\n val = list()\r\n X_train, y_train, X_test, y_test = get_test_partition(X, y, test_set)\r\n \r\n for i in range(epochs):\r\n \r\n if np.size(X_train[0]):\r\n history = model.fit(X_train[0], y_train[0][:,-1,-1],shuffle=True,batch_size=1, epochs=1, verbose=0)\r\n predict = model.predict(X_test)\r\n model.reset_states()\r\n if np.size(X_train[2]):\r\n history = model.fit(X_train[2], y_train[2][:,-1,-1],shuffle=True,batch_size=1, epochs=1, verbose=0)\r\n model.reset_states()\r\n if i==49:\r\n np.save(os.path.join(directory,'Results', model_type +'_'+ str(forecast_horizon)+'_'+str(2010+test_set) ),predict[-52:])\r\n np.save(os.path.join(directory,'Results', 'Truth_'+ str(forecast_horizon)+'_'+str(2010+test_set) ),y_test[-52:,-1,-1])\r\n print(model_type+'_'+str(forecast_horizon)+'_'+str(2010+test_set))\r\n print(mean_squared_error(predict[-52:,-1],y_test[-52:,-1,-1]))\r\n #plot_cases(predict,y_test, truth,forecast_horizon,window_size, test_set, directory, model_type)\r\n #plot_learning(train,val)\r\n \r\n val.append(mean_squared_error(predict[-52:,-1],y_test[-52:,-1,-1]))\r\n train.append((history.history['loss'][0]))#,history.history['root_mean_squared_error'][0] ))\r\n \r\n model.reset_states()\r\n model.save(os.path.join(directory,'Models',model_type+str(forecast_horizon)+str(test_set)))\r\n\r\ntest_models()\r\n\r\nfrom keras.layers import Dense, TimeDistributed\r\n\r\n\r\ndef create_model(neurons=1, dropout=[0, 0 ], window_size=2,data_size=1,optimizer='nadam'):\r\n batch_size = 1\r\n Input_Layer = Input(shape=( window_size, data_size ))\r\n lstm = LSTM(neurons,return_sequences=False,kernel_initializer='glorot_normal')(Input_Layer)\r\n drop2 = Dropout(dropout[1])(lstm)\r\n dense = Dense(1)((drop2))\r\n model = Model (inputs = Input_Layer, outputs = dense) \r\n \r\n model.compile(loss='mse', optimizer=optimizer, metrics=[tf.keras.metrics.RootMeanSquaredError()])\r\n return model\r\n\r\n\r\ndef merge_models(model1, model2):\r\n \r\n w1 = model1.get_weights()\r\n w2 = model2.get_weights()\r\n \r\n m1 = create_model(60,[0,0],4,104) #M model\r\n m2 = create_model(8,[0,0],4,2) #T model\r\n \r\n m1.set_weights(w1)\r\n m2.set_weights(w2)\r\n \r\n \r\n\r\n for layer in m1.layers[:]:\r\n layer.trainable = False\r\n\r\n for layer in model2.layers[:]:\r\n layer.trainable = True \r\n #if hasattr(layer, 'rate'):\r\n # layer.rate = 0 \r\n m1.compile(optimizer='nadam', loss = 'mse',metrics=['mse']) \r\n m2.compile(optimizer='nadam', loss = 'mse',metrics=['mse'])\r\n input_data = [m1.input,model2.input]\r\n concat = concatenate([(m1.layers[-2].output), model2.layers[-2].output])\r\n drop = Dropout(0)(concat)\r\n dense = Dense(1)(drop)\r\n merged = Model(inputs=input_data, outputs=[dense])\r\n merged.compile(optimizer='nadam', loss = 'mse',metrics=['mse']) \r\n\r\n return merged\r\n\r\n\r\ndef final_model(model1,model2):\r\n mh = model1\r\n \r\n w2 = model2.get_weights()\r\n t = create_model(90,[0.1,0],4,226)\r\n t.set_weights(w2)\r\n for layer in mh.layers[:]:\r\n layer.trainable=True\r\n for layer in t.layers[:]:\r\n layer.trainable=True \r\n t.compile(optimizer='nadam', loss = 'mse',metrics=['mse'])\r\n input_data = [mh.input,t.input]\r\n concat = concatenate([ Dropout(0.1)(mh.layers[-2].output), Dropout(0.2)(t.layers[-2].output)])\r\n drop = Dropout(0)(concat)\r\n dense = Dense(1)(drop)\r\n merged = Model(inputs=input_data, outputs=[dense])\r\n merged.compile(optimizer='nadam', loss = 'mse',metrics=['mse']) \r\n\r\n return merged\r\ndef test_models():\r\n \r\n window_size = 4 \r\n merged_models = ['MTH']\r\n model_types = ['M','H','T']\r\n data_names = {'H':'total.npy', 'T':'TWEET_DATA.npy','M':'METEO_DATA.npy'}\r\n\r\n epochs = 50\r\n for forecast_horizon in range(3,4):\r\n for model_type in merged_models:\r\n truth = np.load(os.path.join(head_path,'HEALTH_DATA.npy'))\r\n truth = truth[forecast_horizon:]\r\n series_x1 = np.load(os.path.join(head_path, data_names['M']))\r\n series_x2 = np.load(os.path.join(head_path, data_names['H']))\r\n series_x3 = np.load(os.path.join(head_path, data_names['T']))\r\n series_x3[0:36] = series_x3[52:36+52]\r\n series_y = np.load(os.path.join(head_path,'HEALTH_DATA.npy'))\r\n scaler,series_x1,_ = scale(series_x1,series_x1)\r\n scaler,series_x2,_ = scale(series_x2,series_x2)\r\n scaler,series_x3,_ = scale(series_x3,series_x3)\r\n series_x1 = series_x1[:-forecast_horizon] \r\n series_x2 = series_x2[:-forecast_horizon] \r\n series_x3 = series_x3[:-forecast_horizon] \r\n series_y = series_y[forecast_horizon:]\r\n \r\n directory = r'/content/drive/MyDrive/Final Thesis Fragkozidis Georgios/C:/Users/skote/Desktop/New Method/Final Method'\r\n for test_set in range(8,10):\r\n if model_type=='MH':\r\n model1 = tf.keras.models.load_model(os.path.join(directory,'Models','M'+str(forecast_horizon)+str(test_set)))\r\n model2 = tf.keras.models.load_model(os.path.join(directory,'Models','H'+str(forecast_horizon)+str(test_set)))\r\n y = sliding_window(series_y,window_size)\r\n X1 = sliding_window(series_x1,window_size)\r\n X2 = sliding_window(series_x2,window_size) \r\n X_train1, y_train, X_test1, y_test = get_test_partition(X1, y, test_set)\r\n X_train2, y_train, X_test2, y_test = get_test_partition(X2, y, test_set)\r\n if model_type=='MTH':\r\n model1 = tf.keras.models.load_model(os.path.join(directory,'Models','MH'+str(forecast_horizon)+str(test_set)))\r\n model2 = tf.keras.models.load_model(os.path.join(directory,'Models','T'+str(forecast_horizon)+str(test_set)))\r\n X3 = sliding_window(series_x3,window_size) \r\n X_train3, y_train, X_test3, y_test = get_test_partition(X3, y, test_set)\r\n model = final_model(model1, model2)\r\n else:\r\n model = merge_models(model1, model2)\r\n train = list()\r\n val = list()\r\n for i in range(epochs):\r\n if model_type=='MTH':\r\n if np.size(X_train1[0]):\r\n history = model.fit([[X_train1[0],X_train2[0]],X_train3[0]], y_train[0][:,-1,-1],shuffle=True,batch_size=1, epochs=1, verbose=0)\r\n predict = model.predict([[X_test1,X_test2],X_test3])\r\n if np.size(X_train1[2]):\r\n history = model.fit([[X_train1[2],X_train2[2]],X_train3[2]], y_train[2][:,-1,-1],shuffle=True,batch_size=1, epochs=1, verbose=0)\r\n model.reset_states()\r\n #model.reset_states()\r\n val.append(mean_squared_error(predict[-52:,-1],y_test[-52:,-1,-1]))\r\n train.append((history.history['loss'][0]))#,history.history['val_root_mean_squared_error'][0])) \r\n else:\r\n if np.size(X_train1[0]):\r\n history = model.fit([X_train1[0],X_train2[0]], y_train[0][:,-1,-1],shuffle=True,batch_size=1, epochs=1, verbose=0)\r\n predict = model.predict([X_test1,X_test2])\r\n if np.size(X_train1[2]):\r\n history = model.fit([X_train1[2],X_train2[2]], y_train[2][:,-1,-1],shuffle=True,batch_size=1, epochs=1, verbose=0)\r\n model.reset_states()\r\n \r\n #model.reset_states()\r\n val.append(mean_squared_error(predict[-52:,-1],y_test[-52:,-1,-1]))\r\n train.append((history.history['loss'][0]))#,history.history['val_root_mean_squared_error'][0])) \r\n if i==(epochs-1):\r\n model.save(os.path.join(directory,'Models',model_type+str(forecast_horizon)+str(test_set)))\r\n np.save(os.path.join(directory,'Results', model_type +'_'+ str(forecast_horizon)+'_'+str(2010+test_set) ),predict)\r\n print(mean_squared_error(predict[-52:,-1],y_test[-52:,-1,-1]))\r\n plot_cases(predict,y_test, truth,forecast_horizon,window_size, test_set, directory, model_type)\r\n plot_learning(train,val)\r\ntest_models()","sub_path":"model_testing.py","file_name":"model_testing.py","file_ext":"py","file_size_in_byte":9651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"612459737","text":"import os\r\nimport torch\r\nfrom torch.utils.data import TensorDataset\r\n\r\n\r\nclass DataProcessor:\r\n \"\"\"Base class for processor converters \"\"\"\r\n def __init__(self,\r\n data_dir,\r\n logger,\r\n prefix='',\r\n truncate_label=False,\r\n **kwargs):\r\n self.logger = logger\r\n self.data_dir = data_dir\r\n self.prefix = prefix\r\n self.truncate_label = truncate_label\r\n\r\n for key, value in kwargs.items():\r\n setattr(self, key, value)\r\n\r\n def get_train_examples(self, data_path):\r\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\r\n return self.create_examples(self.read_data(data_path), 'train')\r\n\r\n def get_dev_examples(self, data_path):\r\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\r\n return self.create_examples(self.read_data(data_path), 'dev')\r\n\r\n def get_test_examples(self, data_path):\r\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\r\n return self.create_examples(self.read_data(data_path), 'test')\r\n\r\n\r\n def get_labels(self):\r\n \"\"\"Gets the list of labels for this processor set.\"\"\"\r\n return None\r\n\r\n def get_batch_keys(self):\r\n '''\r\n batch keys should be a list of (input_ids, attention_mask, *,*,*, labels) tuples...\r\n '''\r\n raise NotImplementedError\r\n\r\n def convert_to_features(self, **kwargs):\r\n raise NotImplementedError()\r\n\r\n def create_examples(self, **kwargs):\r\n raise NotImplementedError()\r\n\r\n def read_data(self, input_file):\r\n raise NotImplementedError()\r\n\r\n def collate_fn(self, batch):\r\n\r\n \"\"\"\r\n batch should be a list of (input_ids, attention_mask, *,*,*, labels) tuples...\r\n Returns a padded tensor of sequences sorted from longest to shortest,\r\n \"\"\"\r\n batch = list(map(torch.stack, zip(*batch)))\r\n max_seq_len = torch.max(torch.sum(batch[1], 1)).item()\r\n for i in range(len(batch) - 1):\r\n if batch[i].size()[1] > max_seq_len:\r\n batch[i] = batch[i][:, :max_seq_len]\r\n if self.truncate_label:\r\n batch[-1] = batch[-1][:, :max_seq_len]\r\n return batch\r\n\r\n def convert_to_tensors(self, features):\r\n # In this method we'll make the assumption that all `features` in the batch\r\n # have the same attributes.\r\n # So we will look at the first element as a proxy for what attributes exist\r\n # on the whole batch.\r\n first = features[0]\r\n # Special handling for labels.\r\n # Ensure that tensor is created with the correct type\r\n # (it should be automatically the case, but let's make sure of it.)\r\n if hasattr(first, \"label\") and first.label is not None:\r\n if type(first.label) is int:\r\n labels = torch.tensor([f.label for f in features], dtype=torch.long)\r\n else:\r\n labels = torch.tensor([f.label for f in features], dtype=torch.float)\r\n batch = {\"labels\": labels}\r\n elif hasattr(first, \"label_ids\") and first.label_ids is not None:\r\n if type(first.label_ids[0]) is int:\r\n labels = torch.tensor([f.label_ids for f in features], dtype=torch.long)\r\n else:\r\n labels = torch.tensor([f.label_ids for f in features], dtype=torch.float)\r\n batch = {\"labels\": labels}\r\n else:\r\n batch = {}\r\n # Handling of all other possible attributes.\r\n # Again, we will use the first element to figure out which key/values are not None for this model.\r\n for k, v in vars(first).items():\r\n if k not in (\"label\", \"label_ids\") and v is not None and not isinstance(v, str):\r\n batch[k] = torch.tensor([getattr(f, k) for f in features], dtype=torch.long)\r\n return batch\r\n\r\n def load_from_cache(self, max_seq_length, data_name, mode):\r\n '''\r\n load feature cache\r\n '''\r\n # Load processor features from cache or dataset file\r\n cached_features_file = f'cached_{mode}_{self.prefix}_{max_seq_length}'\r\n cached_features_file = os.path.join(self.data_dir, cached_features_file)\r\n\r\n if os.path.exists(cached_features_file):\r\n self.logger.info(\"Loading features from cached file %s\", cached_features_file)\r\n features = torch.load(cached_features_file)\r\n else:\r\n self.logger.info(\"Creating features from dataset file at %s\", str(self.data_dir))\r\n label_list = self.get_labels()\r\n if mode == 'train':\r\n examples = self.get_train_examples(os.path.join(self.data_dir, data_name))\r\n elif mode == 'dev':\r\n examples = self.get_dev_examples(os.path.join(self.data_dir, data_name))\r\n else:\r\n examples = self.get_test_examples(os.path.join(self.data_dir, data_name))\r\n features = self.convert_to_features(examples=examples, label_list=label_list, max_seq_length=max_seq_length)\r\n self.logger.info(\"Saving features into cached file %s\", cached_features_file)\r\n torch.save(features, cached_features_file)\r\n return features\r\n\r\n def create_dataset(self, max_seq_length, data_name, mode):\r\n '''\r\n dataset\r\n '''\r\n features = self.load_from_cache(max_seq_length=max_seq_length, data_name=data_name, mode=mode)\r\n inputs = self.convert_to_tensors(features)\r\n inputs_keys = self.get_batch_keys()\r\n dataset = TensorDataset(*[inputs[key] for key in inputs_keys if inputs[key] is not None])\r\n return dataset\r\n\r\n def print_examples(self, **kwargs):\r\n '''\r\n 打印一些样本信息\r\n '''\r\n inputs = {}\r\n for key, value in kwargs.items():\r\n if key not in inputs and value is not None:\r\n inputs[key] = value\r\n self.logger.info(\"*** Example ***\")\r\n for key, value in inputs.items():\r\n if isinstance(value, (float, int)):\r\n value = str(value)\r\n elif isinstance(value, list):\r\n value = \" \".join([str(x) for x in value])\r\n elif isinstance(value, str):\r\n value = value\r\n else:\r\n raise ValueError(\"'value' value type: expected one of (float,int,str,list)\")\r\n self.logger.info(\"%s: %s\" % (str(key), value))\r\n","sub_path":"torchblocks/processor/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":6472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"546296127","text":"__author__ = 'KoicsD'\n\n\nclass PrimeFactor():\n @staticmethod\n def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\n @staticmethod\n def generate(n):\n primes = []\n if n > 1:\n primes_to_check = [j for j in range(2, int(n ** 0.5) + 1) if PrimeFactor.generate(j)[0] == j]\n for i in primes_to_check:\n while n % i == 0:\n primes.append(i)\n n //= i\n if len(primes) == 0:\n primes.append(n)\n return primes\n","sub_path":"prime_factors/prime_factor_rec.py","file_name":"prime_factor_rec.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"79904167","text":"from sys import stdin\ninput = stdin.readline\n\nN = int(input())\ncnt = 0\nprime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]\na = [2, 3, 5, 7, 11]\nfor _ in range(N):\n n = (int(input())*2)+1\n if n < 9:\n cnt += 1\n continue\n if n < 38:\n if n in prime:\n cnt += 1\n continue\n for i in a:\n d = n - 1\n ch = False\n while d % 2 == 0:\n if pow(i, d, n) == n - 1:\n ch = True\n d //= 2\n tmp = pow(i, d, n)\n if tmp == 1 or tmp == n-1:\n ch = True\n if not ch:\n break\n else:\n cnt += 1\n\nprint(cnt)","sub_path":"210510/5615.py","file_name":"5615.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"429869256","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nProject Euler Problem 30\n=======================\n\nSurprisingly there are only three numbers that can be written as the sum\nof fourth powers of their digits:\n\n 1634 = 1^4 + 6^4 + 3^4 + 4^4\n 8208 = 8^4 + 2^4 + 0^4 + 8^4\n 9474 = 9^4 + 4^4 + 7^4 + 4^4\n\nAs 1 = 1^4 is not a sum it is not included.\n\nThe sum of these numbers is 1634 + 8208 + 9474 = 19316.\n\nFind the sum of all the numbers that can be written as the sum of fifth\npowers of their digits.\n\n\"\"\"\n\n\ndef main():\n nice_nums = set()\n for i in range(2, 1000000):\n tot = 0\n for c in str(i):\n tot += int(c) ** 5\n if tot == i:\n nice_nums.add(i)\n\n return sum(nice_nums)\n\n\nif __name__ == \"__main__\":\n import ntpath\n import time\n from common.shared_functions import verify_solution\n\n problem_number = int(ntpath.basename(__file__).replace(\"euler\", \"\").replace(\".py\", \"\"))\n print(\"Retrieving my answer to Euler Problem {0} ...\".format(problem_number))\n\n ts = time.time()\n my_answer = main()\n te = time.time()\n\n print(\"My answer: {1}\".format(problem_number, my_answer))\n\n verification_type = verify_solution(problem_number, my_answer)\n print(\"Verification: {0}\".format(verification_type.name))\n print(\"Took {0} seconds.\".format(te - ts))\n","sub_path":"project-euler/solvers/euler030.py","file_name":"euler030.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"652206957","text":"\nimport os\nimport sys\nimport logging\nimport warnings\nimport json\nfrom collections import defaultdict, Counter\ntry:\n import yaml\nexcept ImportError:\n print(\"Your python installation must have pyyaml installed.\")\n sys.exit()\ntry:\n import pokecat\nexcept ImportError:\n print(\"Your python installation must have pokecat installed.\")\n sys.exit()\n\n\nsets = []\noutfile = \"pbrpokemondb.json\"\n\nexisting_ids = {}\ngenders_per_species = defaultdict(set)\n\nillegal_chars = r\"[\\]^`|<>_{}\"\n\nname_replacements = {\"ᴹ\": \"M\", \"ɴ\": \"N\", \"×\": \"x\", \"’\": \"'\", \"”\": \"\\\"\", \"ᵖ\": \"P\", \"ᵏ\": \"K\", \" \": \" \", \"ᴾ\": \"P\"}\n\nallowed_characters = [\"\\u2640\", \"\\u2642\", \"â\", \"É\"]\n\nfor dir, _, files in os.walk(\".\"):\n for file in files:\n if not (file.endswith(\".yaml\") or file.endswith(\".yml\")) or file == outfile or file.startswith(\"_\"):\n continue\n filepath = os.path.join(dir, file)\n with open(filepath, \"r\", encoding=\"utf-8\") as f:\n try:\n contents = list(yaml.load_all(f, Loader=yaml.FullLoader))\n for pokeset in contents:\n if not pokeset:\n print(\"Skipping empty pokeset in {}\".format(filepath))\n continue\n identifier = \"{}:{} {}\".format(filepath, pokeset.get(\"species\"), pokeset.get(\"setname\"))\n with warnings.catch_warnings(record=True) as w:\n if \"ingamename\" in pokeset:\n fixed_ingamename = pokeset[\"ingamename\"].encode(\"ascii\", \"replace\").decode()\n for char in illegal_chars:\n fixed_ingamename = fixed_ingamename.replace(char, \"?\")\n temp = \"\"\n for i, char in enumerate(pokeset[\"ingamename\"]):\n if char in allowed_characters:\n temp += char\n elif char in name_replacements:\n temp += name_replacements[char]\n else:\n temp += fixed_ingamename[i]\n fixed_ingamename = temp\n if pokeset[\"ingamename\"] != fixed_ingamename:\n print(\"Changed ingamename: {} -> {} to avoid encoding issues\"\n .format(pokeset[\"ingamename\"], fixed_ingamename))\n pokeset[\"ingamename\"] = fixed_ingamename\n try:\n pokeset = pokecat.populate_pokeset(pokeset, skip_ev_check=True)\n except ValueError as ex:\n print(\"{}> ERROR: {}\".format(identifier, str(ex).encode(\"ascii\", \"replace\").decode()))\n else:\n for warning in w:\n text = str(warning.message).encode(\"ascii\", \"replace\").decode()\n if text != \"Set is shiny, but not hidden, which means it is publicly visible. Is this intended?\" and text != \"Set is shiny, but also biddable, which means it can be used in token matches. Is this intended?\" and not text.startswith(\"Sum of EV must not be larger than\") and \"is guaranteed to occupy multiple slots (possible stallmate due to PP-bug)\" not in text:\n print(\"{}> WARNING: {}\".format(identifier, text))\n genders_this_species = genders_per_species[pokeset[\"species\"][\"id\"]]\n genders_this_species |= set(pokeset[\"gender\"])\n if None in genders_this_species and len(genders_this_species) > 1:\n print(\"{}> ERROR: Starting with this set, that species now has both genderless and genderful sets! \"\n \"Stick to either genderless or genderful per species or PBR might crash!\"\n .format(identifier))\n continue # Crash risk, so do NOT add this pokeset\n id = (pokeset[\"species\"][\"id\"], pokeset[\"setname\"])\n if id in existing_ids:\n prev_identifier = existing_ids[id]\n print(\"{}> ERROR: combination of species {} ({}) and setname {} already exists ({}), but must be unique!\"\n .format(identifier, id[0], pokeset[\"species\"][\"name\"], id[1], prev_identifier))\n else:\n existing_ids[id] = identifier\n sets += [pokeset]\n except yaml.YAMLError as e:\n print(\"Error reading file: {}/{}: {}\".format(dir, file, str(e).encode(\"ascii\", \"replace\").decode()))\n except:\n print(\"Error reading file: {}/{}\".format(dir, file))\n raise\n\nprint(\"Writing compiled sets to {}...\".format(outfile))\nwith open(outfile, \"w+\", encoding=\"utf-8\") as f:\n json.dump(sets, f, indent=\" \", sort_keys=True)\n\n\ngroup_tags_file = \"group_tags.json\"\ngroup_tags = {}\nrunmons = Counter()\nanime = Counter()\npwt = Counter()\nfor set in sets:\n tags = set['tags']\n if 'runmon' in tags:\n trainer_tag =\"setname+\" + set['setname']\n runmons[trainer_tag] += 1\n if 'anime' in tags:\n trainer_tag = \"setname+\" + set['setname']\n anime[trainer_tag] += 1\n if 'in-game' in tags:\n trainer_tag = list(filter(lambda tag: 'PWT' in tag, tags))\n if trainer_tag:\n pwt_set = trainer_tag[0]\n pwt[pwt_set] += 1\n\ngroup_tags['pwt_versus_tags'] = [elem for (elem, cnt) in pwt.items() if cnt >= 4]\ngroup_tags['pwt_versus_tags'] += [elem for (elem, cnt) in runmons.items() if cnt >= 4]\n\nprint(\"Writing group tag data to {}...\".format(group_tags_file))\nwith open(group_tags_file, \"w+\", encoding=\"utf-8\") as f:\n json.dump(group_tags, f, sort_keys=True, ensure_ascii=False)\n","sub_path":"compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":6082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"523094157","text":"from timeit import timeit\n\nimport numpy as np\nfrom numpy.random import rand\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm\n\nfrom utils import covar, sd\n\n\ndef compute_correlation_matrix_loop(x):\n feature_dim = x.shape[1]\n z = np.zeros((feature_dim, feature_dim))\n for i in range(feature_dim):\n for j in range(feature_dim):\n z[i][j] = covar(x, (i, j)) / (sd(x, i) * sd(x, j))\n return z\n\n\ndef compute_correlation_matrix_ops(x):\n num_vectors = x.shape[0]\n y = np.subtract(x, np.divide(np.matmul(np.ones((num_vectors, num_vectors)), x), num_vectors))\n vcv = np.divide(np.matmul(np.transpose(y), y), num_vectors)\n d = np.linalg.inv(np.sqrt(np.diag(np.diag(vcv))))\n corr_matrix = np.matmul(np.matmul(d, vcv), d)\n return corr_matrix\n\n\ndef comparison(size=None):\n if size is None:\n size = int(input('Up to what size matrix (integer greater than 1) would you like to compare? '))\n\n assert size > 1\n sizes = [i for i in range(2, size + 1)]\n loop_times = []\n mat_ops_times = []\n\n for i in tqdm(range(2, size + 1)):\n r = rand(i, i)\n\n loop_time = timeit(lambda: compute_correlation_matrix_loop(r), number=1)\n mat_ops_time = timeit(lambda: compute_correlation_matrix_ops(r), number=1)\n\n loop_times.append(loop_time)\n mat_ops_times.append(mat_ops_time)\n\n plt.xlabel('Matrix Size')\n plt.ylabel('Running Times')\n plt.plot(sizes, loop_times, label='Loop')\n plt.plot(sizes, mat_ops_times, label='Matrix Operations')\n plt.legend()\n plt.savefig('comparison-problem-02.png')\n plt.show()\n\n\nif __name__ == '__main__':\n comparison()\n","sub_path":"problem-02.py","file_name":"problem-02.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"147445428","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 18 17:05:10 2018\n\n@author: prasad\n@Roll No.: CMS1731\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import multivariate_normal\nfrom sklearn import preprocessing,datasets\n\ndata = pd.DataFrame(datasets.load_iris().data)\nrandomShuf = np.random.choice(np.arange(len(data)),len(data),replace=True)\nshuf = np.random.choice(3,len(data),replace=True)\np = data.shape[1]\nclusterNum = 3\nitrmax = 100\nmu = []\nPriorProb = []\ncluster = []\nPostProb = []\n\nfor i in np.arange(clusterNum):\n cluster1 = data.iloc[shuf == i]\n pi = len(cluster1) / len(data)\n PriorProb.append(pi)\n cluster.append(cluster1)\n mu = cluster1.mean(axis=0)\n CovMat = cluster1.cov()\n invCovMat = np.linalg.inv(CovMat)\n norm = []\n for j in np.arange(data.shape[0]):\n ex = np.exp(-(0.5*float(np.mat(data.iloc[j] - mu) * np.mat(invCovMat) * np.mat(data.iloc[j]-mu).T)))\n N = 1/(2*np.pi)**(p/2) * 1/(np.linalg.det(CovMat))**(1/2) * ex\n norm.append(N)\n PostProb.append(norm)\n\npi1 = len(data.iloc[shuf == 0]) / len(data)\npi2 = len(data.iloc[shuf == 1]) / len(data)\npi3 = len(data.iloc[shuf == 2]) / len(data)\nmu = [pi1,pi2,pi3]\n\nprobabilityMat = pd.DataFrame(PostProb).T\nitr = 0\nwhile(True):\n W = []\n for i in np.arange(data.shape[0]):\n tp = probabilityMat.iloc[i] * PriorProb\n w = []\n for j in np.arange(clusterNum):\n w.append(tp[j]/ sum(tp))\n W.append(w)\n \n ric = (pd.DataFrame(W))\n \n phi = []\n for i in np.arange(clusterNum):\n phi.append(sum(ric[i])/data.shape[0])\n \n newMuList = []\n for j in np.arange(ric.shape[1]):\n tpMu = [] \n for i in np.arange(p):\n tpMu.append(sum(ric[j] * data[i])/sum(ric[j]))\n newMuList.append(tpMu)\n \n newMu = pd.DataFrame(newMuList)\n \n SigmaList = []\n for j in np.arange(ric.shape[1]):\n sigma = 0\n for i in np.arange(len(data)):\n sigma = sigma + ric[j][i] * (np.mat(data.iloc[i] - newMu.iloc[j])).T * (np.mat(data.iloc[i] - newMu.iloc[j]))\n SigmaList.append(sigma/sum(ric[j]))\n \n PriorProb = phi\n CovMat = SigmaList.copy()\n PostProb = []\n for i in np.arange(clusterNum):\n PostProb.append(multivariate_normal.pdf(data,newMu.iloc[i],CovMat[i]))\n \n probabilityMat = pd.DataFrame(PostProb).T\n itr += 1\n print(itr)\n if abs(sum(mu) - sum(newMu)) < 0.0001:\n break\n if itr > itrmax:\n break\n mu = newMu","sub_path":"GMMC/GMM.py","file_name":"GMM.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"3490074","text":"from django.core.urlresolvers import reverse_lazy\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, redirect\nfrom django.views.generic import UpdateView, ListView, CreateView\nfrom apps.student.forms import StudentForm, UsersForm\nfrom apps.course.models import Student\nfrom django.contrib.auth.models import User\n\n# Create your views here.\n\n#views\n\nclass StudentView(ListView):\n model = Student\n template_name = 'user/view_student.html'\n\nstudent_view = StudentView.as_view()\n\n#views form\n\nclass StudentForm(CreateView):\n model = Student\n template_name = 'user/view_form_student.html'\n form_class = StudentForm\n second_form_class = UsersForm\n success_url = reverse_lazy('start:view_start')\n\n def get_context_data(self, **kwargs):\n context = super(StudentForm, self).get_context_data(**kwargs)\n if 'form' not in context:\n context['form'] = self.form_class(self.request.GET)\n if 'form2' not in context:\n context['form2'] = self.second_form_class(self.request.GET)\n return context\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object\n form = self.form_class(request.POST)\n form2 = self.second_form_class(request.POST)\n if form.is_valid() and form2.is_valid():\n student = form.save(commit=False)\n student.user = form2.save()\n student.save()\n return HttpResponseRedirect(self.get_success_url())\n else:\n return self.render_to_response(self.get_context_data(form=form, form2=form2))\n\nstudent_form = StudentForm.as_view()\n\n#views update\n\nclass StudentUpdate(UpdateView):\n model = Student\n second_model = User\n template_name = 'user/update_student.html'\n form_class = StudentForm\n second_form_class = UsersForm\n\n def get_context_data(self, **kwargs):\n context = super(StudentUpdate, self).get_context_data(**kwargs)\n pk = self.kwargs.get('pk', 0)\n student = self.model.objects.get(id=pk)\n user = self.second_model.objects.get(id=student.id)\n if 'form' not in context:\n context['form'] = self.form_class()\n if 'form2' not in context:\n context['form2'] = self.second_form_class(instance=user)\n context['id'] = pk\n return context\n\n\nstudent_update = StudentUpdate.as_view()\n\n#views delete\n\ndef student_delete(request, id_student):\n student = Student.objects.get(id=id_student)\n if request.method == 'POST':\n student.delete()\n return redirect('student:view_student')\n return render(request, 'user/delete_student.html', {'student': student})\n\n","sub_path":"apps/student/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"70877614","text":"'''\n MCTS solution to the AKQ game\n'''\n\n'''\n Software design:\n\n Player:\n\n Props:\n\n Range: {A,Q,K}\n\n Chips: number of big blinds\n\n Tree:\n\n Props:\n\n Root:\n\n Struct: - The current structure of the tree. { a: {b,c}, b: {c,d} ...\n\n Actions:\n\n addNode\n\n getNode\n\n getChildren\n\n Nodes:\n\n Properties:\n\n Pot: Size of the current pot\n\n Player: Player whos action it is\n\n Actions: Possible actions\n\n\n\n Solver:\n\n Props:\n\n Type: - Type of solver it is. MCTS ect...\n\n Tree: - The current tree\n\n Strategy - The current strategy implemented on the current tree\n\n'''\n\nimport random\nimport numpy as np\nfrom Util.node import InfoNode,PokerNode\nfrom Util.tree import InfoTree\n#from RL.MCTS.Model import MCTS\nimport random\nimport gym\nimport numpy as np\nfrom collections import deque\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\n\n\nclass DQNAgent:\n\n def __init__(self, state_size, action_size):\n\n self.state_size = state_size\n self.action_size = action_size\n self.memory = deque(maxlen=2000)\n self.gamma = 1 # discount rate\n self.epsilon = 1.0 # exploration rate\n self.epsilon_min = 0.01\n self.epsilon_decay = 0.995\n self.learning_rate = 0.1\n self.model = self._build_model()\n\n def _build_model(self):\n\n # Neural Net for Deep-Q learning Model\n model = Sequential()\n model.add(Dense(48, input_dim=self.state_size, activation='relu'))\n model.add(Dense(self.action_size, activation='linear'))\n model.compile(loss='mse',\n optimizer=Adam(lr=self.learning_rate))\n return model\n\n def remember(self, state, action, reward, next_state, done):\n\n self.memory.append((state, action, reward, next_state, done))\n\n def act(self, state,valid_actions):\n\n if np.random.rand() <= self.epsilon:\n\n random_valid_action = valid_actions[random.randrange(len(valid_actions))]\n\n return (random_valid_action,'random')\n\n act_values = self.model.predict(state)\n\n for i in range(self.action_size):\n\n if i not in valid_actions:\n\n act_values[0][i] = -100\n\n return (np.argmax(act_values[0]),'max') # returns action\n\n def replay(self, batch_size):\n\n minibatch = random.sample(self.memory, batch_size)\n\n for state, action, reward, next_state, done in minibatch:\n\n target = reward\n\n if not done:\n\n predict_next = self.model.predict(next_state)[0]\n\n predict_next[2] = -100\n predict_next[3] = -100\n\n target = (reward + self.gamma *\n np.amax(predict_next))\n\n target_f = self.model.predict(state)\n\n target_f[0][action] = target\n\n self.model.fit(state, target_f, epochs=1, verbose=0)\n\n if self.epsilon > self.epsilon_min:\n\n self.epsilon *= self.epsilon_decay\n\n def load(self, name):\n self.model.load_weights(name)\n\n def save(self, name):\n self.model.save_weights(name)\n\nclass ExtensiveFormMCTS(object):\n '''\n Outline of what a basic mcts algorith looks like for games of hidden info\n as outlined by David Silver and heinrich\n '''\n\n def __init__(self):\n\n pass\n\n def search(game):\n\n '''\n While within budget\n Sample initial game state\n simulate(s_o)\n end\n\n return policy\n '''\n pass\n\n def rollout(s):\n '''\n takes in a state\n gets action based off of a rollout policy - i.e random actions, ect...\n new state s' from G(s,a) - transition simulator\n return simulate(s')\n '''\n pass\n\n def simulate(s):\n '''\n Takes in a state\n\n if state.terminal == True:\n return reward\n\n Player = player(s)\n if Player.out_of_tree == True:\n return rollout(s)\n InfoState = information_function(s) maps state to info state\n if InfoState not in PlayerTree:\n Expand(PlayerTree,InfoState)\n a = rollout_policy\n Player.out_of_tree = True\n else:\n a = select(InfoState)\n s' = G(s,a)\n r = simulate(s')\n update(InfoState,a,r)\n return r\n '''\n\n\n pass\n\n def select_uct(u_i):\n '''\n select action that maximizes\n Q(u,a) + c sqrt( log(N(u))/N(u,a) )\n\n '''\n pass\n\n def update(u_i, a, r):\n '''\n N(u_i) += 1\n N(u,a) += 1\n Q(u,a) += (r - Q(u,a)) / N(u,a)\n '''\n pass\n\nclass AKQPlayer(object):\n\n def __init__(self,name,info_tree,starting_stack):\n\n self.name = name\n\n self.info_tree = info_tree\n\n self.policy = {}\n\n self.out_of_tree = False\n\n self.current_hand = None\n\n self.starting_stack = starting_stack\n\nclass AKQGameState(object):\n\n '''\n class used for simulating a simple AKQ poker game\n The game state needs to deal random cards to each player\n and to track the button\n '''\n\n def __init__(self,game_tree):\n\n self.player1 = None\n\n self.player2 = None\n\n self.iter_count = 0\n\n self.deck = [3,2,1]\n\n self.game_tree = game_tree # the full game tree for for the information trees to reference\n\n self.replay_data = []\n\n self.adaptive_constant = 0.8\n\n self.behavior_policy = {\n \"SB\": {},\n \"BB\":{}\n }\n\n self.init_game()\n\n def init_game(self):\n\n SB_tree = InfoTree() # info tree\n\n chance_node = PokerNode(player=\"chance\",SB_cip=0.0,BB_cip=0.0)\n\n SB_tree.set_root(chance_node)\n\n BB_tree = InfoTree() # info tree\n\n game_root = self.game_tree.get_root()\n\n BB_root_node = PokerNode(game_root.player,SB_cip=0,BB_cip=0)\n\n BB_tree.set_root(BB_root_node)\n\n self.player1 = AKQPlayer(name=\"SB\",info_tree=SB_tree,starting_stack=1)\n\n self.player2 = AKQPlayer(name=\"BB\",info_tree=BB_tree,starting_stack=1)\n\n self.player1.policy[0] = {}\n\n self.player2.policy[0] = {}\n\n for curr_node in self.game_tree.nodes:\n\n if curr_node.player == 'Leaf':\n continue\n\n actions = [list(node.action.keys())[0] for node in curr_node.children]\n\n self.behavior_policy[curr_node.player][curr_node.node_index] = {}\n\n for action in actions:\n\n self.behavior_policy[curr_node.player][curr_node.node_index][action] = {'A':0.0,'K':0.0,'Q':0.0}\n\n def deal_hand(self):\n\n return random.choice(self.deck)\n\n def get_hand_string(self,hand):\n\n if hand == 3:\n return \"A\"\n\n elif hand == 2:\n return \"K\"\n\n else:\n return \"Q\"\n\n def get_hero_villian(self,s):\n\n '''\n Take in the name of the owner of the current node and returns hero,villian\n :param current_player:\n :return: []\n '''\n\n if s.parent.player == \"SB\":\n\n return [self.player1,self.player2]\n\n else:\n\n return [self.player2,self.player1]\n\n def get_hero_villian_cip(self, s):\n\n if s.parent.player == \"SB\":\n\n return [s.SB_cip, s.BB_cip]\n\n else:\n return [s.BB_cip, s.SB_cip]\n\n def get_info_state(self,current_player, s):\n\n '''\n\n info state for the AKG game is (actions,hand)\n actions are all previous actions to this node\n\n For the AKQ I dont think we need to keep track of\n actions so the info stat is only going to have\n the additional hand value\n\n Append\n :param s:\n :return:\n\n '''\n\n if s.parent == None:\n # this is a root node and the parent will be chance\n\n NewInfoNode = InfoNode(current_player.current_hand, player=s.player,action=s.action, parent=current_player.info_tree.get_root(),\n SB_cip=s.SB_cip, BB_cip=s.BB_cip,is_leaf=s.is_leaf)\n\n return NewInfoNode\n\n # need to make a copy of the parent cannot pass as reference\n\n new_parent = PokerNode(s.parent.player,parent=s.parent.parent,SB_cip=s.parent.SB_cip,BB_cip=s.parent.BB_cip,action=s.parent.action)\n\n NewInfoNode = InfoNode(current_player.current_hand,player=s.player ,action=s.action, parent=new_parent,\n SB_cip=s.SB_cip, BB_cip=s.BB_cip,is_leaf=s.is_leaf)\n\n return NewInfoNode\n\n def get_new_state(self,s,a):\n\n node_children = s.children\n\n for child in node_children:\n\n if child.action == a:\n\n return child\n\n else:\n continue\n\n # we should not reach this line of code\n # the function should always be able to return a new state\n\n raise Exception(\"get_new_state was not able to find a child with the given action\")\n\n def get_child_info(self,u_i,a):\n\n for child in u_i.children:\n if u_i.action == a:\n return child\n\n # should not reach this location\n\n raise Exception(\"g_child_info parent does not have child with action: \" + str(a))\n\n def reward(self,s):\n\n '''\n\n Takes in a leaf node and returns the reward to each player\n :param s:\n :return:\n\n '''\n\n r = {\"SB\":0,\"BB\":0}\n\n hero, villian = self.get_hero_villian(s)\n\n hero_cip, villian_cip = self.get_hero_villian_cip(s)\n\n current_pot = 2.0 + s.SB_cip + s.BB_cip\n\n action_type = list(s.action.keys())[0]\n\n if action_type == \"fold\":\n # the parent folded so the current player gets the pot\n r[hero.name] = hero.starting_stack - hero_cip\n\n r[villian.name] = current_pot + (villian.starting_stack - villian_cip)\n\n\n elif action_type == \"check\":\n\n # evaluate winner\n if (hero.current_hand > villian.current_hand):\n # SB wins\n r[hero.name] = current_pot + (hero.starting_stack - hero_cip)\n\n r[villian.name] = villian.starting_stack - villian_cip\n\n else:\n\n r[villian.name] = current_pot + (villian.starting_stack - villian_cip)\n\n r[hero.name] = hero.starting_stack - hero_cip\n\n\n elif action_type == \"call\": # same as check?\n\n # evaluate winner\n if (hero.current_hand > villian.current_hand):\n # SB wins\n r[hero.name] = current_pot + (hero.starting_stack - hero_cip)\n\n r[villian.name] = villian.starting_stack - villian_cip\n\n else:\n\n r[villian.name] = current_pot + (villian.starting_stack - villian_cip)\n\n r[hero.name] = hero.starting_stack - hero_cip\n\n return r\n\n def rollout(self,s):\n\n '''\n takes in a state\n gets action based off of a rollout policy - i.e random actions, ect...\n new state s' from G(s,a) - transition simulator\n return simulate(s')\n '''\n\n new_action = self.rollout_policy(s)\n\n new_state = self.get_new_state(s,new_action)\n\n return self.simulate(new_state) # recursive call\n\n def rollout_policy(self,s):\n\n '''\n\n Get a new action for the player based off the rollout policy\n :param s:\n :return:\n\n '''\n\n # for now just going to use a random rollout policy\n\n #possible_actions = [child.action for child in s.children]\n\n # just return the child node\n\n try:\n\n return random.choice(s.children).action\n\n except Exception as e:\n print(\"Error at rollout_policy: \" + str(e))\n\n def select_uct(self,u_i):\n\n '''\n select action that maximizes\n\n if random U [0,1] < mu\n\n Q(u,a) + c sqrt( log(N(u))/N(u,a) )\n\n else\n policy = N(u,a) / N(u)\n return a ~ p\n '''\n\n N_U = u_i.visit_count\n\n if (np.random.random() < self.adaptive_constant):\n\n if N_U == 0:\n print(\"Visit count = 0!\")\n\n current_max_action = None\n\n current_max = -1\n\n current_player = self.player1 if u_i.player == \"SB\" else self.player2\n\n info_policy = current_player.policy[u_i.node_index]\n\n for action in info_policy.keys():\n\n child_ev_value = info_policy[action]['ev']\n\n child_visit_count = info_policy[action]['count']\n\n score = 0\n\n if child_visit_count == 0:\n\n score = current_max + 1000\n\n else:\n score = child_ev_value + 1.5*np.sqrt(np.log(N_U)/child_visit_count)\n\n if score > current_max:\n\n current_max = score\n\n current_max_action = action\n\n if current_max_action == \"check\" or current_max_action == \"fold\":\n return {current_max_action: 0}\n else:\n return {current_max_action: 1}\n\n else:\n\n current_player = self.player1 if u_i.player == \"SB\" else self.player2\n\n action_p = []\n\n actions = []\n\n for action in current_player.policy[u_i.node_index].keys():\n\n n_a_count = current_player.policy[u_i.node_index][action]['count']\n\n action_p.append(float(n_a_count/N_U))\n\n actions.append(action)\n\n choose_action = np.random.choice(actions,1,p=action_p)[0]\n\n\n if choose_action == \"check\" or choose_action == \"fold\":\n\n return {choose_action: 0}\n else:\n return {choose_action: 1}\n\n def simulate(self,s):\n\n self.iter_count += 1\n\n '''\n\n Takes in a state\n\n if state.terminal == True:\n return reward\n\n Player = player(s)\n if Player.out_of_tree == True:\n return rollout(s)\n InfoState = information_function(s) maps state to info state\n if InfoState not in PlayerTree:\n Expand(PlayerTree,InfoState)\n a = rollout_policy\n Player.out_of_tree = True\n else:\n a = select(InfoState)\n s' = G(s,a)\n r = simulate(s')\n update(InfoState,a,r)\n return r\n\n '''\n\n if s.is_leaf == True:\n\n return self.reward(s)\n\n current_player = self.player1 if s.player == \"SB\" else self.player2\n\n if current_player.out_of_tree == True:\n\n return self.rollout(s)\n\n infostate = self.get_info_state(current_player,s)\n\n action = None\n\n action_select_type = \"uct\"\n\n if not current_player.info_tree.node_in_tree(infostate):\n\n current_player.info_tree.add_node(infostate)\n\n action = self.rollout_policy(s)\n\n action_select_type = \"rollout\"\n\n current_player.out_of_tree = True\n\n current_player.policy[infostate.node_index] = {}\n\n for child in s.children:\n\n new_action = list(child.action.keys())[0]\n\n current_player.policy[infostate.node_index][new_action] = {}\n\n current_player.policy[infostate.node_index][new_action]['count'] = 0\n\n current_player.policy[infostate.node_index][new_action]['ev'] = 0\n\n else:\n\n infostate = current_player.info_tree.get_tree_node(infostate)\n\n action = self.select_uct(infostate)\n\n\n\n next_state = self.get_new_state(s,action)\n\n ###############\n # REPLAY DATA\n ###############\n\n action_type = list(action.keys())[0]\n\n r = self.simulate(next_state)\n\n replay_data = [current_player.name,s.node_index,self.get_hand_string(current_player.current_hand),action_type,r[current_player.name]]\n\n self.replay_data.append(replay_data)\n\n self.update(current_player,s,infostate,action,r)\n\n return r\n\n def update(self,current_player,s,u_i, a, r):\n\n '''\n N(u_i) += 1\n N(u,a) += 1\n Q(u,a) += (r - Q(u,a)) / N(u,a)\n '''\n\n u_i.visit_count += 1\n\n player_reward = r[current_player.name]\n\n action_type = list(a.keys())[0]\n\n current_player.policy[u_i.node_index][action_type]['count'] += 1\n\n current_count = current_player.policy[u_i.node_index][action_type]['count']\n\n current_ev = current_player.policy[u_i.node_index][action_type]['ev']\n\n update = (player_reward - current_ev)/current_count\n\n current_player.policy[u_i.node_index][action_type]['ev'] += update\n\n # update policy simply N(u,a) / N(u)\n\n string_hand = self.get_hand_string(u_i.player_hand)\n\n for action in list(current_player.policy[u_i.node_index].keys()):\n\n N_U_A = current_player.policy[u_i.node_index][action]['count']\n\n self.behavior_policy[current_player.name][s.node_index][action][string_hand] = N_U_A / float(u_i.visit_count)\n\n def run(self,num_iterations):\n\n for i in range(num_iterations):\n\n #self.iter_count = i\n\n self.deck = [3,2,1] # reshuffle the cards yo\n\n self.player1.out_of_tree = False\n\n self.player2.out_of_tree = False\n\n # deals cards to each player\n\n sb_card = self.deal_hand()\n\n self.player1.current_hand = sb_card\n\n self.deck.remove(sb_card)\n\n bb_card = self.deal_hand()\n\n self.player2.current_hand = bb_card\n\n s0 = self.game_tree.get_root()\n\n self.simulate(s0)\n\n\n return [self.player1.policy,self.player2.policy]\n\n\n\n\n\n\n\n","sub_path":"Poker/mcts_akq.py","file_name":"mcts_akq.py","file_ext":"py","file_size_in_byte":18137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"490296015","text":"import torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom copy import deepcopy\nfrom CNN import CNN\n\nclass VanillaCNN(CNN):\n def __init__(self, hidden_size, input_size, output_size, device):\n\n super().__init__(hidden_size, input_size, output_size, device)\n\n @classmethod\n def from_existing_model(cls, m, new_hidden_size):\n\n model = cls(new_hidden_size, m.input_size, m.output_size, m.device)\n\n model.size_dictionary = deepcopy(m.size_dictionary)\n\n model.task_post_training_weights = deepcopy(m.task_post_training_weights)\n\n model.copy_weights_expanding(m)\n\n return model\n\n\n def train_model(self, args, train_loader, task_number, **kwargs):\n\n # Set the module in \"training mode\"\n # This is necessary because some network layers behave differently when training vs testing.\n # Dropout, for example, is used to zero/mask certain weights during TRAINING to prevent overfitting.\n # However, during TESTING (e.g. model.eval()) we do not want this to happen.\n self.train()\n\n self.reinitialize_output_weights()\n\n # Set the optimization algorithm for the model- in this case, Stochastic Gradient Descent with/without\n # momentum (depends on the value of args.momentum- default is 0.0, so no momentum by default).\n #\n # ARGUMENTS (in order):\n # params (iterable) - iterable of parameters to optimize or dicts defining parameter groups\n # lr (float) - learning rate\n # momentum (float, optional) - momentum factor (default: 0)\n #\n # NOTE on params:\n # model.parameters() returns an iterator over a list of the model parameters in the same order in\n # which they appear in the network when traversed input -> output\n # (e.g.\n # [weights b/w input and first hidden layer,\n # bias b/w input and hidden layer 1,\n # ... ,\n # weights between last hidden layer and output,\n # bias b/w hidden layer and output]\n # )\n optimizer = optim.SGD(self.parameters(), lr=args.lr, momentum=args.momentum) # can use filter and requires_grad=False to freeze part of the network...\n #optimizer = optim.Adadelta(self.parameters())\n\n\n for epoch in range(1, args.epochs + 1):\n\n running_loss = 0.0\n\n # Enumerate will keep an automatic loop counter and store it in batch_idx.\n # The (data, target) pair returned by DataLoader train_loader each iteration consists\n # of an MNIST image data sample and an associated label classifying it as a digit 0-9.\n #\n # The image data for the batch is represented as a 4D torch tensor (see train_loader definition in main())\n # with dimensions (batch size, 1, 28, 28)- containing a normalized floating point value for the color of\n # each pixel in each image in the batch (MNIST images are 28 x 28 pixels).\n #\n # The target is represented as a torch tensor containing the digit classification labels for\n # the training data as follows:\n # [ 3, 4, 2, 9, 7] represents ground truth labels for a 3, a 4, a 2, a 9, and a 7.\n # NOTE:\n # The indices are converted to one-hot label representations inside of the loss function:\n # [[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],\n # [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]]\n # represents labels for a 5 and a 2, because 1's are at index 5 and 2 in rows 0 and 1, respectively.\n #\n # SOURCE:\n # https://discuss.pytorch.org/t/why-does-the-minimal-pytorch-tutorial-not-have-mnist-images-be-onehot-for-logistic-regression/12562/6\n for batch_idx, (data, target) in enumerate(train_loader, 0):\n\n # The data needs to be wrapped in another tensor to work with our network,\n # otherwise it is not of the appropriate dimensions... I believe these two statements effectively add\n # a dimension.\n #\n # For an explanation of the meaning of these statements, see:\n # https://stackoverflow.com/a/42482819/9454504\n #\n # This code was used here in another experiment:\n # https://github.com/kuc2477/pytorch-ewc/blob/4a75734ef091e91a83ce82cab8b272be61af3ab6/train.py#L35\n\n #todo remove?\n #data_size = len(data)\n\n # todo remove from CNN?\n # data = data.view(data_size, -1)\n\n # wrap data and target in variables- again, from the following experiment:\n # https://github.com/kuc2477/pytorch-ewc/blob/4a75734ef091e91a83ce82cab8b272be61af3ab6/train.py#L50\n #\n # .to(device):\n # set the device (CPU or GPU) to be used with data and target to device variable (defined in main())\n\n # todo may not need to wrap in variables - just to move to GPU if necessary\n data, target = Variable(data).to(self.device), Variable(target).to(self.device)\n\n #print(target) # todo remove- for debugging\n\n # Gradients are automatically accumulated- therefore, they need to be zeroed out before the next backward\n # pass through the network so that they are replaced by newly computed gradients at later training iterations,\n # rather than SUMMED with those future gradients. The reasoning behind this approach and the need to zero\n # gradients manually with each training minibatch is presented here in more detail:\n # https://discuss.pytorch.org/t/why-do-we-need-to-set-the-gradients-manually-to-zero-in-pytorch/4903/9\n #\n # From PyTorch examples:\n # Before the backward pass, use the optimizer object to zero all of the\n # gradients for the variables it will update (which are the learnable\n # weights of the model). This is because by default, gradients are\n # accumulated in buffers( i.e, not overwritten) whenever .backward()\n # is called.\n optimizer.zero_grad()\n\n # forward pass: compute predicted output by passing data to the network\n # NOTE: we have overridden forward() in class Net above, so this will call model.forward()\n output = self(data)\n\n # Define the training loss function for the model to be cross entropy loss based on predicted values\n # and ground truth labels. This loss function only takes into account loss on the most recent task.\n #\n # NOTE: torch.nn.CrossEntropyLoss combines torch.nn.LogSoftmax() and torch.nn.NLLLoss() in one single class.\n # apply the loss function to the predictions/labels for this batch to compute loss\n loss = F.cross_entropy(output, target)\n\n # Backward pass: compute gradient of the loss with respect to model\n # parameters\n loss.backward()\n\n # Simplified abstraction provided by PyTorch which uses a single statement to update all model parameters\n # according to gradients (with respect to the last loss function on which .backward() was called and\n # optimization function's update rule.\n # In the case of SGD (without momentum), essentially executes the following:\n #\n # with torch.no_grad():\n # for param in model.parameters():\n # param -= learning_rate * param.grad\n optimizer.step()\n\n running_loss += loss.item()\n\n # Each time the batch index is a multiple of the specified progress display interval (args.log_interval),\n # print a message indicating progress AND which network (model) is reporting values.\n if batch_idx % args.log_interval == args.log_interval - 1:\n print('{} Task: {} Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n 'NoReg',\n task_number,\n epoch,\n batch_idx * len(data),\n args.train_dataset_size,\n 100. * batch_idx / len(train_loader),\n running_loss / args.log_interval\n ))\n running_loss = 0.0\n\n\n # update the model size dictionary\n self.update_size_dict(task_number)\n\n self.save_theta_stars(task_number)\n","sub_path":"VanillaCNN.py","file_name":"VanillaCNN.py","file_ext":"py","file_size_in_byte":9313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"238354293","text":"import argparse ##importing argparse\nparser=argparse.ArgumentParser()\nparser.add_argument(\"-v\", \"--verbosity\", help=\"increase output verbosity\", action=\"count\", default=0) ##Acts as a flag. If you type python3 arg2.py verbose, it assumse verbose is true, otherwise false\n## inside here, you can use action=\"count\" such that -v acts like a flag, -v =1, -vv =2 and so on, and no -v means None, except when we fix bug now we need default=0\n## can also set it up such that the type of -v is an int, then put in 'choices=[0,1,2]' to limit what can be input, error message for all other numbers though\nparser.add_argument(\"square\", type=int, help=\"Display a square of a given number\")\nargs=parser.parse_args()\nanswer=args.square**2\n\n##bugfix, replace == with >= for the count part of -v to work correctly\nif args.verbosity >= 2: ##display something when --verbosity is specified, nothing if not, if no argument is given this doesn't run\n print(\"the square of {} equals {}\".format(args.square, answer))\nelif args.verbosity >= 1:\n print(\"{}^2 == {}\".format(args.square, answer))\nelse:\n print(answer)","sub_path":"arg2.py","file_name":"arg2.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"586032550","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# YuQi created\n__mtime__ = '2017/4/17'\nclass Solution(object):\n def swap(self,nums,i,j):\n nums[i],nums[j] = nums[j],nums[i]\n\n def firstMissingPositive(self, nums):\n for i in range(len(nums)):\n if nums[i] <= 0 or nums[i] > len(nums):\n continue\n if nums[i] == i+1:\n continue\n while nums[i] != (i+1) and nums[i] <= len(nums) and nums[i] >0 and nums[i] != nums[nums[i]-1]:\n self.swap(nums,i,nums[i]-1)\n for i in range(len(nums)):\n if nums[i] != i+1:\n return i+1\n return len(nums)+1\n\nso = Solution()\na = [3,-4,-1,1]\nres = so.firstMissingPositive(a)\nprint(res)\n","sub_path":"41-55/41. First Missing Positive.py","file_name":"41. First Missing Positive.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"164052357","text":"import json\nfrom collections import OrderedDict\n\nfrom .h import * # noqa\nfrom .messages import *\n\n\ndef addMdnPanels(doc):\n if not doc.md.includeMdnPanels:\n return\n\n try:\n filename = doc.md.vshortname + \".json\"\n datafile = doc.dataFile.fetch(\"mdn\", filename, str=True)\n except OSError:\n try:\n filename = doc.md.shortname + \".json\"\n datafile = doc.dataFile.fetch(\"mdn\", filename, str=True)\n except OSError:\n if doc.md.includeMdnPanels == \"maybe\":\n # if \"maybe\", failure is fine, don't complain\n pass\n else:\n die(\n f\"Couldn't find the MDN data for '{doc.md.vshortname}' nor '{doc.md.shortname}'.\"\n )\n return\n try:\n data = json.loads(datafile, object_pairs_hook=OrderedDict)\n except Exception as e:\n die(f\"Couldn't load MDN Spec Links data for this spec.\\n{e}\")\n return\n\n panels = panelsFromData(doc, data)\n if panels:\n doc.extraScripts[\n \"script-mdn-anno\"\n ] = \"\"\"\n document.body.addEventListener(\"click\", (e) => {\n if(e.target.closest(\".mdn-anno-btn\")) {\n e.target.closest(\".mdn-anno\").classList.toggle(\"wrapped\");\n }\n });\n \"\"\" # noqa\n doc.extraStyles[\n \"style-mdn-anno\"\n ] = \"\"\"\n @media (max-width: 767px) { .mdn-anno { opacity: .1 } }\n .mdn-anno { font: 1em sans-serif; padding: 0.3em; position: absolute; z-index: 8; right: 0.3em; background: #EEE; color: black; box-shadow: 0 0 3px #999; overflow: hidden; border-collapse: initial; border-spacing: initial; min-width: 9em; max-width: min-content; white-space: nowrap; word-wrap: normal; hyphens: none}\n .mdn-anno:not(.wrapped) { opacity: 1}\n .mdn-anno:hover { z-index: 9 }\n .mdn-anno.wrapped { min-width: 0 }\n .mdn-anno.wrapped > :not(button) { display: none; }\n .mdn-anno > .mdn-anno-btn { cursor: pointer; border: none; color: #000; background: transparent; margin: -8px; float: right; padding: 10px 8px 8px 8px; outline: none; }\n .mdn-anno > .mdn-anno-btn > .less-than-two-engines-flag { color: red; padding-right: 2px; }\n .mdn-anno > .mdn-anno-btn > .all-engines-flag { color: green; padding-right: 2px; }\n .mdn-anno > .mdn-anno-btn > span { color: #fff; background-color: #000; font-weight: normal; font-family: zillaslab, Palatino, \"Palatino Linotype\", serif; padding: 2px 3px 0px 3px; line-height: 1.3em; vertical-align: top; }\n .mdn-anno > .feature { margin-top: 20px; }\n .mdn-anno > .feature:not(:first-of-type) { border-top: 1px solid #999; margin-top: 6px; padding-top: 2px; }\n .mdn-anno > .feature > .less-than-two-engines-text { color: red }\n .mdn-anno > .feature > .all-engines-text { color: green }\n .mdn-anno > .feature > p { font-size: .75em; margin-top: 6px; margin-bottom: 0; }\n .mdn-anno > .feature > p + p { margin-top: 3px; }\n .mdn-anno > .feature > .support { display: block; font-size: 0.6em; margin: 0; padding: 0; margin-top: 2px }\n .mdn-anno > .feature > .support + div { padding-top: 0.5em; }\n .mdn-anno > .feature > .support > hr { display: block; border: none; border-top: 1px dotted #999; padding: 3px 0px 0px 0px; margin: 2px 3px 0px 3px; }\n .mdn-anno > .feature > .support > hr::before { content: \"\"; }\n .mdn-anno > .feature > .support > span { padding: 0.2em 0; display: block; display: table; }\n .mdn-anno > .feature > .support > span.no { color: #CCCCCC; filter: grayscale(100%); }\n .mdn-anno > .feature > .support > span.no::before { opacity: 0.5; }\n .mdn-anno > .feature > .support > span:first-of-type { padding-top: 0.5em; }\n .mdn-anno > .feature > .support > span > span { padding: 0 0.5em; display: table-cell; }\n .mdn-anno > .feature > .support > span > span:first-child { width: 100%; }\n .mdn-anno > .feature > .support > span > span:last-child { width: 100%; white-space: pre; padding: 0; }\n .mdn-anno > .feature > .support > span::before { content: ' '; display: table-cell; min-width: 1.5em; height: 1.5em; background: no-repeat center center; background-size: contain; text-align: right; font-size: 0.75em; font-weight: bold; }\n .mdn-anno > .feature > .support > .chrome_android::before { background-image: url(https://resources.whatwg.org/browser-logos/chrome.svg); }\n .mdn-anno > .feature > .support > .firefox_android::before { background-image: url(https://resources.whatwg.org/browser-logos/firefox.png); }\n .mdn-anno > .feature > .support > .chrome::before { background-image: url(https://resources.whatwg.org/browser-logos/chrome.svg); }\n .mdn-anno > .feature > .support > .edge_blink::before { background-image: url(https://resources.whatwg.org/browser-logos/edge.svg); }\n .mdn-anno > .feature > .support > .edge::before { background-image: url(https://resources.whatwg.org/browser-logos/edge_legacy.svg); }\n .mdn-anno > .feature > .support > .firefox::before { background-image: url(https://resources.whatwg.org/browser-logos/firefox.png); }\n .mdn-anno > .feature > .support > .ie::before { background-image: url(https://resources.whatwg.org/browser-logos/ie.png); }\n .mdn-anno > .feature > .support > .safari_ios::before { background-image: url(https://resources.whatwg.org/browser-logos/safari-ios.svg); }\n .mdn-anno > .feature > .support > .nodejs::before { background-image: url(https://nodejs.org/static/images/favicons/favicon.ico); }\n .mdn-anno > .feature > .support > .opera_android::before { background-image: url(https://resources.whatwg.org/browser-logos/opera.svg); }\n .mdn-anno > .feature > .support > .opera::before { background-image: url(https://resources.whatwg.org/browser-logos/opera.svg); }\n .mdn-anno > .feature > .support > .safari::before { background-image: url(https://resources.whatwg.org/browser-logos/safari.png); }\n .mdn-anno > .feature > .support > .samsunginternet_android::before { background-image: url(https://resources.whatwg.org/browser-logos/samsung.svg); }\n .mdn-anno > .feature > .support > .webview_android::before { background-image: url(https://resources.whatwg.org/browser-logos/android-webview.png); }\n .name-slug-mismatch { color: red }\n .caniuse-status:hover { z-index: 9; }\n\n /* dt, li, .issue, .note, and .example are \"position: relative\", so to put annotation at right margin, must move to right of containing block */\n .h-entry:not(.status-LS) dt > .mdn-anno, .h-entry:not(.status-LS) li > .mdn-anno, .h-entry:not(.status-LS) .issue > .mdn-anno, .h-entry:not(.status-LS) .note > .mdn-anno, .h-entry:not(.status-LS) .example > .mdn-anno { right: -6.7em; }\n .h-entry p + .mdn-anno { margin-top: 0; }\n h2 + .mdn-anno.after { margin: -48px 0 0 0; }\n h3 + .mdn-anno.after { margin: -46px 0 0 0; }\n h4 + .mdn-anno.after { margin: -42px 0 0 0; }\n h5 + .mdn-anno.after { margin: -40px 0 0 0; }\n h6 + .mdn-anno.after { margin: -40px 0 0 0; }\n \"\"\" # noqa\n\n\ndef createAnno(className, mdnButton, featureDivs):\n return E.div({\"class\": className}, mdnButton, featureDivs)\n\n\ndef panelsFromData(doc, data):\n mdnBaseUrl = \"https://developer.mozilla.org/en-US/docs/Web/\"\n\n browsersProvidingCurrentEngines = [\"firefox\", \"safari\", \"chrome\"]\n browsersWithBorrowedEngines = [\"opera\", \"edge_blink\"]\n browsersWithRetiredEngines = [\"edge\", \"ie\"]\n browsersForMobileDevices = [\n \"firefox_android\",\n \"safari_ios\",\n \"chrome_android\",\n \"webview_android\",\n \"samsunginternet_android\",\n \"opera_android\",\n ]\n\n # BCD/mdn-spec-links shortnames to full names\n nameFromCodeName = {\n \"chrome\": \"Chrome\",\n \"chrome_android\": \"Chrome for Android\",\n \"edge\": \"Edge (Legacy)\",\n \"edge_blink\": \"Edge\",\n \"firefox\": \"Firefox\",\n \"firefox_android\": \"Firefox for Android\",\n \"ie\": \"IE\",\n \"nodejs\": \"Node.js\",\n \"opera\": \"Opera\",\n \"opera_android\": \"Opera Mobile\",\n \"safari\": \"Safari\",\n \"samsunginternet_android\": \"Samsung Internet\",\n \"safari_ios\": \"iOS Safari\",\n \"webview_android\": \"Android WebView\",\n }\n\n panels = False\n for elementId, features in data.items():\n isAnnoForHeadingContent = False\n isAnnoForListItemOrTableContent = False\n lessThanTwoEngines = 0\n onlyTwoEngines = 0\n allEngines = 0\n featureDivs = []\n targetElement = find(f\"[id='{elementId}']\", doc)\n if targetElement is None:\n warn(\n f\"No '{elementId}' ID found, skipping MDN features that would target it.\"\n )\n continue\n\n panels = True\n if targetElement.tag in [\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"]:\n isAnnoForHeadingContent = True\n else:\n for ancestor in targetElement.iterancestors():\n if ancestor.tag in [\n \"body\",\n \"main\",\n \"article\",\n \"aside\",\n \"nav\",\n \"section\",\n \"header\",\n \"footer\",\n ]:\n break\n targetElement = ancestor\n if ancestor.tag in [\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"]:\n isAnnoForHeadingContent = True\n break\n if ancestor.tag in [\"td\", \"dt\", \"dd\", \"li\"]:\n isAnnoForListItemOrTableContent = True\n break\n if ancestor.tag in [\"pre\", \"xmp\", \"p\"]:\n break\n for feature in features:\n if \"engines\" in feature:\n engines = len(feature[\"engines\"])\n if engines < 2:\n lessThanTwoEngines = lessThanTwoEngines + 1\n elif engines == 2:\n onlyTwoEngines = onlyTwoEngines + 1\n elif engines >= len(browsersProvidingCurrentEngines):\n allEngines = allEngines + 1\n featureDivs.append(\n mdnPanelFor(\n feature,\n mdnBaseUrl,\n nameFromCodeName,\n browsersProvidingCurrentEngines,\n browsersWithBorrowedEngines,\n browsersWithRetiredEngines,\n browsersForMobileDevices,\n )\n )\n\n mdnButton = E.button({\"class\": \"mdn-anno-btn\"})\n if lessThanTwoEngines > 0:\n appendChild(\n mdnButton,\n E.b(\n {\n \"class\": \"less-than-two-engines-flag\",\n \"title\": \"This feature is in less than two current engines.\",\n },\n \"\\u26A0\",\n ),\n )\n elif allEngines > 0 and lessThanTwoEngines == 0 and onlyTwoEngines == 0:\n appendChild(\n mdnButton,\n E.b(\n {\n \"class\": \"all-engines-flag\",\n \"title\": \"This feature is in all current engines.\",\n },\n \"\\u2714\",\n ),\n )\n appendChild(mdnButton, E.span(\"MDN\"))\n\n className = \"mdn-anno wrapped\"\n if isAnnoForListItemOrTableContent:\n if targetElement.getchildren() and hasClass(\n targetElement.getchildren()[0], \"mdn-anno\"\n ):\n # If there's already an annotation at the point where we want\n # this, just re-use it (instead of creating another one).\n appendChild(targetElement.getchildren()[0], featureDivs)\n else:\n # For elements we're annotating inside a dt, dd, li, or td, we\n # prepend the annotation to the dt, dd, li, or td — because in\n # cases where we have a long table or list, all the annotations\n # for everything in it otherwise ends up being merged into a\n # single annotation way up at the top of the table or list.\n prependChild(\n targetElement, createAnno(className, mdnButton, featureDivs)\n )\n elif isAnnoForHeadingContent:\n className = \"mdn-anno wrapped after\"\n if (\n targetElement.getnext() is not None\n and targetElement.getnext().get(\"class\") == className\n ):\n # If there's already an annotation at the point where we want\n # this, just re-use it (instead of creating another one).\n appendChild(targetElement.getnext(), featureDivs)\n else:\n # For elements we're annotating inside an h1-h6 heading, we\n # insert the annotation as the next sibling of the heading.\n insertAfter(\n targetElement, createAnno(className, mdnButton, featureDivs)\n )\n else:\n if (\n targetElement.getprevious() is not None\n and targetElement.getprevious().get(\"class\") == className\n ):\n # If there's already an annotation at the point where we want\n # this, just re-use it (instead of creating another one) —\n # unless it's a class=after annotation (following a heading).\n appendChild(targetElement.getprevious(), featureDivs)\n else:\n # For elements we're annotating that aren't inside a table or\n # list or heading, we insert the annotation as the previous\n # sibling of whatever block-level element holds the element.\n insertBefore(\n targetElement, createAnno(className, mdnButton, featureDivs)\n )\n return panels\n\n\ndef addSupportRow(browserCodeName, nameFromCodeName, support, supportData):\n if browserCodeName not in support:\n return\n isEdgeLegacy = browserCodeName == \"edge\"\n isIE = browserCodeName == \"ie\"\n needsFlag = False\n versionAdded = None\n versionRemoved = None\n minVersion = None\n thisBrowserSupport = support[browserCodeName]\n if isinstance(thisBrowserSupport, dict):\n if \"version_added\" in thisBrowserSupport:\n versionAdded = thisBrowserSupport[\"version_added\"]\n if \"flags\" in thisBrowserSupport:\n needsFlag = True\n if (\n \"prefix\" in thisBrowserSupport\n or \"alternative_name\" in thisBrowserSupport\n or \"partial_implementation\" in thisBrowserSupport\n ):\n versionAdded = False\n if \"version_removed\" in thisBrowserSupport:\n versionRemoved = thisBrowserSupport[\"version_removed\"]\n if isinstance(thisBrowserSupport, list):\n for versionDetails in thisBrowserSupport:\n if \"version_removed\" in versionDetails:\n versionRemoved = versionDetails[\"version_removed\"]\n continue\n if \"version_added\" in versionDetails:\n if versionDetails[\"version_added\"] is False:\n versionAdded = False\n continue\n if versionDetails[\"version_added\"] is None:\n versionAdded = None\n continue\n if (\n \"prefix\" in versionDetails\n or \"alternative_name\" in versionDetails\n or \"partial_implementation\" in versionDetails\n ):\n continue\n if \"flags\" in thisBrowserSupport:\n needsFlag = True\n versionAdded = versionDetails[\"version_added\"]\n versionRemoved = None\n break\n statusCode = \"n\"\n if versionAdded is None:\n minVersion = \"?\"\n elif versionAdded is False:\n minVersion = \"None\"\n elif versionAdded is True:\n minVersion = \"Yes\"\n statusCode = \"y\"\n else:\n if versionRemoved is None:\n statusCode = \"y\"\n minVersion = versionAdded + \"+\"\n if isEdgeLegacy and versionAdded == \"18\":\n minVersion = \"18\"\n if isIE and versionAdded == \"11\":\n minVersion = \"11\"\n else:\n statusCode = \"n\"\n if versionAdded is not None:\n minVersion = versionAdded + \"\\u2013\" + versionRemoved\n else:\n minVersion = \"None\"\n browserFullName = nameFromCodeName[browserCodeName]\n appendChild(\n supportData,\n browserCompatSpan(\n browserCodeName, browserFullName, statusCode, minVersion, needsFlag\n ),\n )\n\n\ndef mdnPanelFor(\n feature,\n mdnBaseUrl,\n nameFromCodeName,\n browsersProvidingCurrentEngines,\n browsersWithBorrowedEngines,\n browsersWithRetiredEngines,\n browsersForMobileDevices,\n):\n featureDiv = E.div({\"class\": \"feature\"})\n if \"slug\" in feature:\n slug = feature[\"slug\"]\n displaySlug = slug.split(\"/\", 1)[1]\n title = feature.get(\"summary\", \"\")\n mdnURL = mdnBaseUrl + slug\n appendChild(\n featureDiv, E.p({}, E.a({\"href\": mdnURL, \"title\": title}, displaySlug))\n )\n if \"engines\" in feature:\n engines = len(feature[\"engines\"])\n enginesPara = None\n if engines == 0:\n enginesPara = E.p(\n {\"class\": \"less-than-two-engines-text\"}, \"In no current engines.\"\n )\n elif engines == 1:\n enginesPara = E.p(\n {\"class\": \"less-than-two-engines-text\"}, \"In only one current engine.\"\n )\n elif engines >= len(browsersProvidingCurrentEngines):\n enginesPara = E.p({\"class\": \"all-engines-text\"}, \"In all current engines.\")\n if enginesPara is not None:\n appendChild(featureDiv, enginesPara)\n supportData = E.div({\"class\": \"support\"})\n appendChild(featureDiv, supportData)\n support = feature[\"support\"]\n for browserCodeName in browsersProvidingCurrentEngines:\n addSupportRow(browserCodeName, nameFromCodeName, support, supportData)\n appendChild(supportData, E.hr())\n for browserCodeName in browsersWithBorrowedEngines:\n addSupportRow(browserCodeName, nameFromCodeName, support, supportData)\n appendChild(supportData, E.hr())\n for browserCodeName in browsersWithRetiredEngines:\n addSupportRow(browserCodeName, nameFromCodeName, support, supportData)\n appendChild(supportData, E.hr())\n for browserCodeName in browsersForMobileDevices:\n addSupportRow(browserCodeName, nameFromCodeName, support, supportData)\n if \"nodejs\" in support:\n appendChild(supportData, E.hr())\n addSupportRow(\"nodejs\", nameFromCodeName, support, supportData)\n return featureDiv\n\n\ndef browserCompatSpan(\n browserCodeName, browserFullName, statusCode, minVersion, needsFlag\n):\n # browserCodeName: e.g. \"chrome\"\n # browserFullName: e.g. \"Chrome for Android\"\n minVersionAttributes = {}\n flagSymbol = \"\"\n if needsFlag:\n flagSymbol = \"\\U0001f530 \"\n minVersionAttributes[\n \"title\"\n ] = \"Requires setting a user preference or runtime flag.\"\n statusClass = {\"y\": \"yes\", \"n\": \"no\"}[statusCode]\n outer = E.span({\"class\": browserCodeName + \" \" + statusClass})\n appendChild(outer, E.span({}, browserFullName))\n appendChild(outer, E.span(minVersionAttributes, flagSymbol + minVersion))\n return outer\n","sub_path":"bikeshed/mdnspeclinks.py","file_name":"mdnspeclinks.py","file_ext":"py","file_size_in_byte":20008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"134719451","text":"import numpy as np\nimport torch \nimport torch.nn as nn\nimport torchvision.transforms as transform\nfrom torch.autograd.gradcheck import zero_gradients\nfrom PIL import Image\nfrom torchvision.models import resnet50\nimport torch.utils.model_zoo as model_zoo\nimport requests\nimport os\nfrom io import BytesIO\nimport sys\n\nmodel = resnet50(pretrained = False)\nmodel.load_state_dict(torch.load('fgsm_model.pth'))\nmodel.eval()\n\nlabel_idx = []\nf_file = \"hw5_data/labels.csv\"\nwith open(f_file) as file:\n for line_id, line in enumerate(file):\n if line_id != 0:\n datas = line.split(',')\n label = datas[3]\n label_idx.append(int(label))\nlabel_idx = np.array(label_idx)\n\ndef threshhold(image, idx, trans_value):\n for i in range(len(image[0])):\n for j in range(len(image[0][i])):\n for k in range(len(image[0][i][j])):\n if idx[0][i][j][k] == 1:\n image[0][i][j][k] = trans_value * image[0][i][j][k].sign_()\n return image\n\ndef clip(image, minvalue, maxvalue):\n for i in range(len(image[0])):\n for j in range(len(image[0][i])):\n for k in range(len(image[0][i][j])):\n if image[0][i][j][k] < minvalue:\n image[0][i][j][k] = minvalue\n elif image[0][i][j][k] > maxvalue:\n image[0][i][j][k] = maxvalue\n return image\n\nimg_file_path = sys.argv[1]\noutput_file = sys.argv[2]\ncriterion = nn.CrossEntropyLoss()\nepsilon = 0.007\n\n\nfor i in range(200):\n \n img = Image.open(img_file_path + (\"%03d\" % i) + \".png\")\n trans = transform.Compose([transform.ToTensor()])\n image = trans(img)\n image = image.unsqueeze(0)\n\n image.requires_grad = True\n zero_gradients(image)\n\n output = model(image)\n \n rank = output.argsort(-1)[0]\n \n if label_idx[i] != rank[-1]:\n ori_label = label_idx[i]\n target_label = rank[-1]\n else:\n ori_label = rank[-1]\n target_label = rank[-2]\n \n target_label = [target_label]\n target_label = torch.tensor(target_label)\n \n ori_label = [ori_label]\n ori_label = torch.tensor(ori_label)\n# print(ori_label, target_label)\n\n loss1 = criterion(output, target_label)\n loss2 = criterion(output, ori_label)\n \n loss = loss2 - loss1\n loss.backward()\n \n deltaimage = image.grad.sign_()\n \n# deltaimage = image.grad.data\n# idx = abs(deltaimage) > 0.01\n# deltaimage = threshhold(deltaimage, idx, 0.01)\n \n \n image = image + deltaimage * epsilon\n \n# deltaimage = image.grad.sign_()\n# image = image + epsilon * deltaimage\n \n# image = image + epsilon * image.grad.sign_()\n image = clip(image, 0, 1)\n image_ad = transform.ToPILImage()(image[0])\n image_ad.save(output_file + (\"%03d\" % i) + \".png\")\n img.close()","sub_path":"hw5/hw5_fgsm.py","file_name":"hw5_fgsm.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"186407309","text":"from pyem import Em\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Instantiate an em\nmagnetization = np.array([1.,0,0])\nposition = np.array([0.,0,0])\nvelocity = np.array([0.,0,0])\ngyromagnetic_ratio = 1.0\nequilibrium_magnetization = 1.0\nem = Em(magnetization,position,velocity,gyromagnetic_ratio,equilibrium_magnetization)\n\n# Declare time step\ndelta_t = 0.01\nnum_steps = 500\n\n# Simulate precession and relaxation\nT1 = 1.0\nT2 = 1.0\nBz = 10.0\nmu = np.empty([num_steps+1,3])\nmu[0,:] = em.mu\nfor step_no in range(num_steps):\n em.precess_and_relax(T1,T2,Bz,delta_t)\n mu[step_no+1,:] = em.mu\nprint()\n\n# Plot\nt = delta_t*np.arange(num_steps+1)\nplt.plot(t,mu)\nplt.xlabel('Time (s)')\nplt.ylabel('Magnetization (a.u.)')\nplt.legend(('$\\mu_x$','$\\mu_y$','$\\mu_z$'))\nplt.savefig('free_precession_em_one.pdf')\n","sub_path":"notes/2019-11-28/free_precession_em_one.py","file_name":"free_precession_em_one.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"57645725","text":"from src.CameraBuffer import CameraBuffer\nfrom scipy import signal\nfrom src.Util import *\nfrom matplotlib import pyplot as plt\nimport cv2\n\n\nclass OutputController(object):\n def __init__(self, maxX, maxY, max_disp, timeRes, maxTimeSlot, cameraBuffer: CameraBuffer):\n self.maxX = maxX\n self.maxY = maxY\n self.max_disp = max_disp\n self.timeResolution = timeRes\n self.cameraBuffer = cameraBuffer\n self.maxTimeSlot = maxTimeSlot\n self.WMI = np.zeros((maxY, maxX, max_disp))\n # self.output = cv2.VideoWriter(\"output.avi\", cv2.VideoWriter_fourcc(*'DIVX'), 5, (maxX, maxY))\n self.image_idx=0\n self.visual = np.zeros((self.maxY,self.maxX))\n\n def refreshWMI(self, referenceEvent, candidateEvent: list):\n #print(\"event from the left Buffer: {}\".format(referenceEvent))#\n if True and len(candidateEvent) != 0 :\n tmp_e = candidateEvent[0]\n tmp_cost = 0\n\n for e in candidateEvent:\n dt = abs(referenceEvent[0] - e[0]) / self.timeResolution\n cost = Util.calculateMatchingCosts(dt, self.maxTimeSlot)\n #print(\"possible events for matching: {} \\n matching costs: {}\".format(\n # e, cost))\n disp = int(abs(referenceEvent[1] - e[1]))\n self.WMI[int(referenceEvent[2]), int(referenceEvent[1]), disp] = cost\n if(tmp_cost < cost):\n tmp_cost = cost\n tmp_e = e\n if False and len(candidateEvent) != 0:\n self.visualizeMatching(referenceEvent,tmp_e)\n\n def applyFilter(self, filter2d):\n for i in range(self.max_disp):\n self.WMI[:, :, i] = signal.convolve2d(self.WMI[:, :, i], filter2d, boundary='symm', mode='same', fillvalue=0)\n\n def visualizeMatching(self, referenceEvents, matchingEvent):\n self.visual = np.subtract(self.visual, 1)\n self.visual = self.visual.clip(min=0)\n self.visual[int(referenceEvents[2]),int(referenceEvents[1])] = 19\n self.visual[int(referenceEvents[2]),int(matchingEvent[1])] = 19\n plt.imshow(self.visual, cmap=\"gist_ncar_r\")\n plt.show()\n\n\n def evaluateAll(self):\n \n print(\"Process Start:\")\n print(self.cameraBuffer.leftBuffer.shape[0])\n print(str(self.cameraBuffer.leftBuffer.shape[0]) + \"event(s) in total.\")\n filterAvg = np.ones((2, 2), dtype=np.float) / 4\n #filtergauss = cv2.getGaussianKernel(3, 1.5)*cv2.getGaussianKernel(3, 1.5).transpose()\n print(\"filter kernel: {}\".format(filterAvg))\n for i in range(self.cameraBuffer.leftBuffer.shape[0]):\n candidateEvent = self.cameraBuffer.searchCorrespondingEventsOnRight(self.cameraBuffer.leftBuffer[i])\n self.refreshWMI(self.cameraBuffer.leftBuffer[i], candidateEvent)\n\n if i % 10000 == 0:\n #print(\"i: {}\".format(i))\n self.applyFilter(filterAvg)\n res = np.argmax(self.WMI[:,:,:], 2)\n print(res)\n \n # Calculate Depth Map\n # DepthMap = 3*20/res\n # print(\"depth map: \", DepthMap)\n \n plt.imshow(res, cmap=\"binary\") #res\n save_path = \"result_drone_2/\"\n title = save_path+format(self.image_idx, '03d') + \".png\" #str(i) + \".png\"\n self.image_idx += 1\n plt.clim(0, 30)\n plt.colorbar()\n plt.savefig(title)\n # plt.close()\n plt.show()\n\n if i% 100== 0:\n self.WMI = np.subtract(self.WMI, 9)\n self.WMI = self.WMI.clip(min=0)\n\n #if i % 1000 == 0:\n # res = np.argmax(self.WMI, 2)*10\n # self.output.write(res)\n\n\n # self.output.release()\n","sub_path":"src/OutputController.py","file_name":"OutputController.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"651380260","text":"\"\"\"\nThe in-pond data is very blocky - apply a bit of smoothing\nbefore it gets used in the dem\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom stompy.spatial import field\n\n## \nfn='../../sbsprp/SbayPondBathy2005/merged_ponds.tif'\nponds_dem=field.GdalGrid(fn)\n\n# limit it to the parts we're actually using\nponds_crop=ponds_dem.extract_tile(xxyy=(579160, 592550, 4141950, 4146580),\n res=2,interpolation='bilinear')\n# expand a bit\nponds_crop.fill_by_convolution(iterations=5,kernel_size=5)\n# Smooth it\nponds_crop.smooth_by_convolution(iterations=5)\n\n## \n \nplt.figure(2).clf()\nfig,ax=plt.subplots(num=2)\nponds_crop.plot(ax=ax,interpolation='nearest')\n\n## \n\n# And looks like we need to convert to m, too.\nponds_crop.F *= 0.3048\n\n## \nponds_crop.write_gdal('../sources/merged_ponds_2m_smoothed.tif')\n","sub_path":"smooth_ponds.py","file_name":"smooth_ponds.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"427951940","text":"tridays = {'monday','thursday','saturday'}\nsetdays = {'sunday','monday','tuesday','wednesday','thursday','friday','saturday'}\n\nflag = 0\ncount = len(tridays)\nprint (count)\nfor i in tridays:\n for j in setdays: \n if i == j: \n flag = flag+1\n # print(flag)\n else:\n flag = flag+0\n # print(flag)\nif flag == count:\n print (\"This is a subset\")\nelse:\n print (flag ,\"This is not a subset\")\n\n\n \n\n\n\n\n","sub_path":"submissions/sp_009_gayathri/week_12/day_4/session_2/check_subset.py","file_name":"check_subset.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"482924421","text":"import os\nimport cv2\nimport numpy as np\nimport configparser\nfrom werkzeug.utils import secure_filename\n\ndef get_conf(key, value):\n cf=configparser.ConfigParser()\n cf.read('webApp/util/config.ini')\n return cf.get(key, value)\n\ndef get_file_path(folder, filename):\n return os.path.join(folder, filename)\n\ndef allowed_file(filename):\n ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'mp4', 'avi', 'dat', '3gp', 'mov', 'rmvb'}\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\ndef save_file(file):\n if allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join('webApp/uploads', filename))\n return 1\n return 0\n\ndef toRGB(image):\n return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)\n\n\ndef rotate_bound(image, angle):\n # grab the dimensions of the image and then determine the\n # center\n (h, w) = image.shape[:2]\n (cX, cY) = (w // 2, h // 2)\n\n # grab the rotation matrix (applying the negative of the\n # angle to rotate clockwise), then grab the sine and cosine\n # (i.e., the rotation components of the matrix)\n M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)\n cos = np.abs(M[0, 0])\n sin = np.abs(M[0, 1])\n\n # compute the new bounding dimensions of the image\n nW = int((h * sin) + (w * cos))\n nH = int((h * cos) + (w * sin))\n\n # adjust the rotation matrix to take into account translation\n M[0, 2] += (nW / 2) - cX\n M[1, 2] += (nH / 2) - cY\n\n # perform the actual rotation and return the image\n return cv2.warpAffine(image, M, (nW, nH))\n\nif __name__ == '__main__':\n print('common function')","sub_path":"webApp/models/util/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"239920454","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/7/19 16:15\n# @Author : Suzhenyu\n# @File : AlexNet.py\n# @Email : suzhenyu@qiyi.com\n\nfrom keras.models import Sequential\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.convolutional import MaxPooling2D\nfrom keras.layers.core import Activation\nfrom keras.layers.core import Flatten\nfrom keras.layers.core import Dense\nfrom keras import backend as K\n\n\nclass LeNet:\n @staticmethod\n def build(FLAGS):\n # initialize the model\n model = Sequential()\n inputShape = (FLAGS.normal_size,FLAGS.normal_size,FLAGS.channels)\n model.add(Conv2D(20, (5, 5), padding=\"same\", input_shape=inputShape))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n # second set of CONV => RELU => POOL layers\n model.add(Conv2D(50, (5, 5), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n # first (and only) set of FC => RELU layers\n model.add(Flatten())\n model.add(Dense(500))\n model.add(Activation(\"relu\"))\n\n # softmax classifier\n model.add(Dense(FLAGS.classes))\n model.add(Activation(\"softmax\"))\n model.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n # return the constructed network architecture\n return model","sub_path":"src/netmodel/LeNet.py","file_name":"LeNet.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"56697221","text":"import math as mt\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom visual import *\n\n\n#Programma constantes\n#Positieve y-as is naar boven, positieve x-as is naar rechts (bewegingsrichting)\n\ng = 9.81\n\n#tijd\ndt = 0.01\nt_begin = 0\nt_eind = 20\nt = np.linspace(t_begin, t_eind, round(t_eind/dt+1))\n\n#robot constante eigenschappen\nT_max = 20 #Maximale koppel in Nm\narm_1 = 0.05 #Straal\nm = 1\nF_g = -g*m\n\n#Motor beweging voor constante vm_d\n\ntheta = np.empty(int(t_eind/dt+1))\n\n\nfor i in range(len(t)-1):\n\n while true:\n theta[i+1] = theta[i]+1\n s = mt.sin(theta)\n\n\n\nplt.plot(s,t)","sub_path":"Beweging_simulatie.py","file_name":"Beweging_simulatie.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"163427043","text":"import socket\r\nimport select\r\n\r\nIP_ADRESS = \"192.168.178.52\"\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\ns.bind((IP_ADRESS, 6969))\r\ns.listen(5)\r\n\r\nprint(\"Server up and running!\")\r\n\r\nsocket_list = [s]\r\nusers = {}\r\n\r\ndef receive_message(client_socket): \r\n try:\r\n messageLen = client_socket.recv(8).decode(\"utf-8\")\r\n message = client_socket.recv(int(messageLen))\r\n return message.decode(\"utf-8\")\r\n except:\r\n return False\r\n\r\ndef send_message(client_socket, content):\r\n try:\r\n msg = str(content)\r\n client_socket.send(bytes(f'{len(msg):<8}'+msg, \"utf-8\"))\r\n except:\r\n print(\"\")\r\n socket_list.remove(client_socket)\r\n\r\nwhile True:\r\n read_sockets, _, exception_sockets = select.select(socket_list, [], socket_list)\r\n\r\n for client in read_sockets:\r\n if client == s:\r\n clientsocket, address = s.accept()\r\n print(f\"Connection from {address} has been established.\")\r\n clientsocket.send(bytes(\"Connected!\", \"utf-8\"))\r\n username = clientsocket.recv(15)\r\n users[clientsocket] = username.decode(\"utf-8\")\r\n print(users[clientsocket])\r\n socket_list.append(clientsocket)\r\n\r\n else:\r\n msg = receive_message(client)\r\n if msg != False: \r\n print(users[client]+\" > \"+msg)\r\n for sentClient in socket_list:\r\n if sentClient != s:\r\n if sentClient != client:\r\n send_message(sentClient, users[client]+\" > \"+msg)\r\n\r\n for client in exception_sockets:\r\n socket_list.remove(client)\r\n\r\n del users[client]\r\n \r\n\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"240063431","text":"import tkinter as tk\nwindow = tk.Tk()\nwindow.title(\"收银员1.1\")\nwindow.geometry(\"500x400\")\n# row为行,column为列\nlab0 = tk.Label(window, text=\"XiangYang STORE APPS\\n -----------------------------------\", font=('Arial', 18))\nlab0.grid(row=0, column=1)\n# 标签\nlab1 = tk.Label(window, text=\"项目(item)\")\nlab1.grid(row=1)\nlab2 = tk.Label(window, text=\"价格(Unit Price)\")\nlab2.grid(row=2)\nlab3 = tk.Label(window, text=\"数量(Quantity)\")\nlab3.grid(row=3)\nlab4 = tk.Label(window, text=\"折扣(Disconut)\")\nlab4.grid(row=4)\n# 输入框\n# padx:设置控件周围水平方向空白区域保留大小\n# pady:设置控件周围垂直方向空白区域保留大小\n# 项目输入框\nitem1 = tk.Entry(window, borderwidth=5)\nitem1.grid(row=1, column=1, padx=10, pady=5)\n# 价格输入框\nitem2 = tk.Entry(window, borderwidth=5)\nitem2.grid(row=2, column=1, padx=10, pady=5)\n# 数量输入框\nitem3 = tk.Entry(window, borderwidth=5)\nitem3.grid(row=3, column=1, padx=10, pady=5)\n# 折扣输入框\nitem4 = tk.Entry(window, borderwidth=5, width=10)\nitem4.grid(row=4, column=1, padx=10, pady=5)\n# 总折扣价显示标签和框\nshowToalDiscountname = tk.Label(window, text=\"总折扣\")\nshowToalDiscountname.grid(row=6, column=0, padx=10, pady=10)\n# 总付款显示标签和框\nshowToalPaidname = tk.Label(window, text=\"总付款\")\nshowToalPaidname.grid(row=7, column=0, padx=10, pady=10)\ndef ClickMe():\n \"\"\"点击计算总折扣和总付款\"\"\"\n # 获取价格输入框中的数据并转为int型\n price = int(item2.get())\n # 获取数量输入框中的数据\n quantity = int(item3.get())\n # 获取折扣输入框中的数据\n discount = int(item4.get()) * 0.1\n # 计算总折扣\n TotalDiscount = (price - price * discount) * quantity\n # 计算总付款价\n TotalPaid = price * quantity - TotalDiscount\n # 显示总折扣结果\n showToalDiscountresult = tk.Label(window, text=TotalDiscount, foreground=\"#9932CC\", background=\"#ffb6c1\")\n showToalDiscountresult.grid(row=6, column=1, padx=10, pady=10)\n # 显示总付款结果\n showToalPaidresult = tk.Label(window, text=TotalPaid, foreground=\"#9932CC\", background=\"#ffb6c1\")\n showToalPaidresult.grid(row=7, column=1, padx=10, pady=10)\n\n\nbutt = tk.Button(window, text=\"处理(process)\", command=ClickMe)\nbutt.grid(row=5, column=1)\n# 循环显示\nwindow.mainloop()","sub_path":"xiangmu1/2.1收银员.py","file_name":"2.1收银员.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"492292306","text":"from __future__ import division\r\nimport os\r\nimport sys\r\nimport pygame\r\nfrom pygame.locals import *\r\n\r\n# from main.v00\r\nsubject = raw_input('Enter subject ID here: ')\r\nfilename = subject + '.csv'\r\nfilepath = os.path.join('data', filename)\r\nFILE = open(filepath, 'w')\r\nFILE.write('Subject: %s\\n' % subject)\r\n\r\n# from main.v01\r\npygame.init()\r\npygame.mixer.init()\r\npygame.event.set_grab(1)\r\nSCREEN = pygame.display.set_mode((800,600), 32) #, pygame.FULLSCREEN\r\nFONT = pygame.font.Font(None, 28)\r\nSCREEN.fill((86, 130, 160))\r\ntextimg = FONT.render('Hello World', 1, (0,0,0))\r\nSCREEN.blit(textimg, (10, 10))\r\npygame.display.flip()\r\nwait = True\r\nwhile wait:\r\n\tfor event in pygame.event.get():\r\n\t\tif (event.type == KEYDOWN and event.key == K_SPACE):\r\n\t\t\twait = False\r\n\r\n# new stuff\r\n# load two images from jpg files in ./img/\r\nimage1 = pygame.image.load(os.path.join('img', 'A.jpg'))\r\nimage2 = pygame.image.load(os.path.join('img', 'B.jpg'))\r\n\r\n# draw a blank screen, put image1 on it, update.\r\nSCREEN.fill((86, 130, 160))\r\nSCREEN.blit(image1, (50,50))\r\npygame.display.flip()\r\n\r\n# wait for 300 msec\r\npygame.time.wait(300)\r\n\r\n# draw a blank screen\r\nSCREEN.fill((86, 130, 160))\r\npygame.display.flip()\r\n\r\n# wait 200 msec\r\npygame.time.wait(200)\r\n\r\n# draw screen containing image2\r\nSCREEN.fill((86, 130, 160))\r\nSCREEN.blit(image2, (50,50))\r\npygame.display.flip()\r\n\r\n# wait 300 msec\r\npygame.time.wait(300)\r\n\r\n# draw blank screen\r\nSCREEN.fill((86, 130, 160))\r\npygame.display.flip()\r\n\r\nprint('thank you for your participation!')\r\nFILE.close()\r\nsys.exit(0)\r\n","sub_path":"tutorial/main.v02.py","file_name":"main.v02.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"339584559","text":"from wallace.db.base.attrs import DataType\nfrom wallace.db.base.errors import DoesNotExist, ValidationError\nfrom wallace.db.base.model import Base, Model\n\n\nclass _PKBase(Base):\n def __new__(cls, name, bases, dct):\n the_class = super(_PKBase, cls).__new__(cls, name, bases, dct)\n the_class._cbs_primary_key_fields = cls._get_pk_fields(bases, dct)\n\n if cls._is_proper_model(bases):\n if not the_class._cbs_primary_key_fields:\n raise TypeError('no primary keys set')\n\n return the_class\n\n @staticmethod\n def _get_pk_fields(bases, dct):\n pk_fields = set()\n\n for base in bases: # support model inheritance\n for key in getattr(base, '_cbs_primary_key_fields', []):\n pk_fields.add(key)\n\n for key, val in dct.iteritems():\n if isinstance(val, DataType) and val.is_pk:\n pk_fields.add(key)\n elif key in pk_fields: # catch any superclass pk fields\n pk_fields.remove(key) # overridden here by a non-pk one\n\n return tuple(pk_fields)\n\n @staticmethod\n def _is_proper_model(bases):\n # Model hierarchy:\n # -> ->\n # RelationalModel -> Model -> object\n # ergo, the hierarchy cardinality for any proper model subclass\n # will be at least 4\n\n base_tree = []\n while bases:\n base_tree.append(bases)\n bases = map(lambda b: list(b.__bases__), bases)\n bases = sum(bases, [])\n\n return len(base_tree) > 3\n\n\ndef throw_null_pk_field_error(attr):\n msg = 'primary key field \"%s\" cannot be null' % attr\n raise ValidationError(msg)\n\n\nclass RelationalModel(Model):\n\n __metaclass__ = _PKBase\n\n @classmethod\n def fetch(cls, **kwargs):\n inst = cls.construct(new=False, **kwargs)\n inst.pull()\n return inst\n\n\n def pull(self):\n self._validate_pk()\n return super(RelationalModel, self).pull()\n\n def push(self, *a, **kw):\n self._validate_pk()\n return super(RelationalModel, self).push(*a, **kw)\n\n def _validate_pk(self, silent=False):\n for attr in self._cbs_primary_key_fields:\n if getattr(self, attr, None) is None:\n if silent:\n return False\n throw_null_pk_field_error(attr)\n return True\n\n\n @property\n def primary_key(self):\n # The primary key CURRENTLY stored in the db.\n # If a pk field is changed, this will continue to return the old\n # value so updates can find the row.\n\n if self.is_new:\n raise DoesNotExist('new model')\n\n pk = {}\n for attr in self._cbs_primary_key_fields:\n try:\n pk[attr] = self._cbs_db_data[attr]\n except KeyError:\n throw_null_pk_field_error(attr)\n return pk\n","sub_path":"wallace/db/base/relational.py","file_name":"relational.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"570624365","text":"import os\nimport re\nfrom . import CommandLineHandler\nfrom . import BookKeeping\n\n\nclass Managing:\n\n def __init__(self, source_path_is, content_replace_keywords_with, dump_file_name_is, content_file_name_is, script_file_name_is, base_file_name_is='base.html', data_file_is=''):\n self._dump_file_name = dump_file_name_is\n self._data_file_name = data_file_is\n self._content_file_name = content_file_name_is\n self._script_file_name = script_file_name_is\n self._base_file_name = base_file_name_is\n self._path = source_path_is\n self._content_populator = content_replace_keywords_with\n self._book_keeping = BookKeeping.BookKeeping(time_stamp_directory_path=self.get_project_path())\n self._command_line_handler = CommandLineHandler.CommandLineHandler(self.merge_and_dump, self.get_dump_file_name())\n\n def get_data_file_name(self):\n return self._data_file_name\n\n def get_data_file_path(self):\n if self._data_file_name != '':\n return os.path.join(self._path, self._data_file_name)\n else:\n return ''\n\n def get_dump_file_name(self):\n return self._dump_file_name\n\n def get_dump_file_path(self):\n return os.path.join(self._path, self._dump_file_name)\n\n def get_content_file_name(self):\n return self._content_file_name\n\n def get_content_file_path(self):\n return os.path.join(self._path, self._content_file_name)\n\n def get_script_file_name(self):\n return self._script_file_name\n\n def get_script_file_path(self):\n return os.path.join(self._path, self._script_file_name)\n\n def get_base_file_name(self):\n return self._base_file_name\n\n def get_base_file_path(self):\n return os.path.join(self._path, self._base_file_name)\n\n def get_project_path(self):\n return self._path\n\n def execute_as_main(self, parent_manage_script_is):\n self._command_line_handler.main_exec_interface(\n parent_manage_script=parent_manage_script_is,\n book_keeping=self._book_keeping,\n dump_file_path=self.get_dump_file_path(),\n content_file_path=self.get_content_file_path(),\n script_file_path=self.get_script_file_path(),\n base_file_path=self.get_base_file_path(),\n data_file_path=self.get_data_file_path()\n )\n\n def execute_as_module(self):\n self._command_line_handler.sub_exec_interface(\n book_keeping=self._book_keeping,\n dump_file_path=self.get_dump_file_path(),\n content_file_path=self.get_content_file_path(),\n script_file_path=self.get_script_file_path(),\n base_file_path=self.get_base_file_path(),\n data_file_path=self.get_data_file_path()\n )\n\n def merge_and_dump(self):\n with open(self.get_content_file_path(), 'r') as content, open(self.get_base_file_path(), 'r') as base:\n base_structure = re.split('({{[\\s\\w]*}})', base.read())\n contents_structure = re.split('({{[\\s\\w]*}})', content.read())\n\n configurations = {}\n configurations['title'] = ''\n configurations['style'] = ''\n configurations['hasLeft'] = False\n configurations['hasBody'] = False\n configurations['hasRight'] = False\n configurations['left_content_left_tag'] = ''\n configurations['left_content_right_tag'] = ''\n configurations['right_content_left_tag'] = ''\n configurations['right_content_right_tag'] = ''\n\n self._content_populator(configurations, base_structure, contents_structure, self.get_project_path())\n self.replaceBaseWithContent(configurations, base_structure, contents_structure)\n with open(self.get_dump_file_path(), 'w') as target:\n target.write(''.join(base_structure))\n self._book_keeping.updateTimeStamp(\n dump_file_path=self.get_dump_file_path(),\n content_file_path=self.get_content_file_path(),\n script_file_path=self.get_script_file_path(),\n base_file_path=self.get_base_file_path(),\n data_file_path=self.get_data_file_path()\n )\n\n def replaceBaseWithContent(self, configurations, base_structure, contents_structure):\n\n\n base_structure[base_structure.index('{{PAGE_TITLE}}')] = configurations['title']\n base_structure[base_structure.index('{{STYLE}}')] = configurations['style']\n\n left_content_marking = base_structure.index('{{LEFT_CONTENT}}')\n if configurations['hasLeft']:\n left_content_start_idx = contents_structure.index('{{LEFT_CONTENT_START}}')\n contents_structure[left_content_start_idx] = ''\n left_content_end_idx = contents_structure.index('{{LEFT_CONTENT_END}}')\n contents_structure[left_content_end_idx] = ''\n base_structure[left_content_marking:left_content_marking + 1] = [configurations['left_content_left_tag']] + contents_structure[left_content_start_idx:left_content_end_idx + 1] + [configurations['left_content_right_tag']]\n else:\n base_structure[left_content_marking] = ''\n\n body_content_marking = base_structure.index('{{BODY_CONTENT}}')\n if configurations['hasBody']:\n body_content_start_idx = contents_structure.index('{{BODY_CONTENT_START}}')\n contents_structure[body_content_start_idx] = ''\n body_content_end_idx = contents_structure.index('{{BODY_CONTENT_END}}')\n contents_structure[body_content_end_idx] = ''\n base_structure[body_content_marking:body_content_marking + 1] = contents_structure[body_content_start_idx:body_content_end_idx + 1]\n else:\n base_structure[body_content_marking] = ''\n\n right_content_marking = base_structure.index('{{RIGHT_CONTENT}}')\n if configurations['hasRight']:\n right_content_start_idx = contents_structure.index('{{RIGHT_CONTENT_START}}')\n contents_structure[right_content_start_idx] = ''\n right_content_end_idx = contents_structure.index('{{RIGHT_CONTENT_END}}')\n contents_structure[right_content_end_idx] = ''\n base_structure[right_content_marking:right_content_marking + 1] = [configurations['right_content_left_tag']] + contents_structure[right_content_start_idx:right_content_end_idx + 1] + [configurations['right_content_right_tag']]\n else:\n base_structure[right_content_marking] = ''","sub_path":"Sources/utils/Managing.py","file_name":"Managing.py","file_ext":"py","file_size_in_byte":6529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"516256541","text":"from models.token import separators\r\nimport re\r\n\r\nclass Scanner():\r\n def __init__(self):\r\n pass\r\n\r\n def is_identifier(self,token):\r\n return re.match(r'^[a-zA-Z]([a-zA-Z]|[0-9]|_){,256}$', token) is not None\r\n\r\n\r\n def is_constant(self,token):\r\n return re.match(r'^(0|[+-]?([0-9]*[.])?[0-9]+|[\\+\\-]?[1-9][0-9]*)$|^\\'\\\\.\\'$|^\\'.\\'$|^\\\".*\\\"$', token) is not None\r\n\r\n\r\n def is_escaped_quotation_mark(self,line, index):\r\n if index == 0:\r\n return False\r\n elif line[index - 1] == '\\\\':\r\n return True\r\n else:\r\n return False\r\n\r\n\r\n def get_string(self,line, index):\r\n token = ''\r\n number_of_quotation_mark = 0\r\n\r\n while index < len(line) and number_of_quotation_mark < 2:\r\n if line[index] == '\"' and not self.is_escaped_quotation_mark(line, index):\r\n number_of_quotation_mark += 1\r\n token += line[index]\r\n index += 1\r\n\r\n return token, index\r\n\r\n def get_char(self,line, index):\r\n token = ''\r\n number_of_apostrophes = 0\r\n\r\n while index < len(line) and number_of_apostrophes < 2:\r\n if line[index] == '\\'' and not self.is_escaped_quotation_mark(line, index):\r\n number_of_apostrophes += 1\r\n token += line[index]\r\n index += 1\r\n\r\n return token, index\r\n\r\n\r\n def token_generator(self,line, line_index):\r\n tokens = []\r\n token = ''\r\n index = 0\r\n while index < len(line):\r\n if line[index] == '\"':\r\n if token:\r\n tokens.append(token)\r\n token, index = self.get_string(line, index)\r\n if token[-1] != '\"':\r\n raise Exception(\r\n \"Syntax error, string is not closed! at line \" + str(line_index) + \" position \" + str(index) + \"\\n\")\r\n tokens.append(token)\r\n token = ''\r\n elif line[index] == '\\'':\r\n if token:\r\n tokens.append(token)\r\n token, index = self.get_char(line, index)\r\n if token[-1] != '\\'':\r\n raise Exception(\r\n \"Syntax error, character is not closed! at line \" + str(line_index) + \" position \" + str(index) + \"\\n\")\r\n tokens.append(token)\r\n token = ''\r\n elif line[index] in separators:\r\n if token:\r\n tokens.append(token)\r\n tokens.append(line[index])\r\n index += 1\r\n token = ''\r\n else:\r\n token += line[index]\r\n index += 1\r\n if token:\r\n tokens.append(token)\r\n return tokens\r\n","sub_path":"lab3/models/Scanner.py","file_name":"Scanner.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"22247814","text":"def counting_rectangles(X, Y):\n rects = 0\n for m in range(1, X + 1):\n for n in range(1, Y + 1):\n rects += (X - m + 1) * (Y - n + 1)\n return rects\n\n\ndef solution():\n closestAreaRects = 0\n closestArea = 0\n target = 2 * 10e5\n for x in range(1, 100):\n for y in range(1, 100):\n rects = counting_rectangles(x, y)\n if abs(closestAreaRects - target) > abs(rects - target):\n closestArea = x * y\n closestAreaRects = rects\n if rects > target:\n break\n return closestArea\n\n\ndef solution2():\n for x in range(1, 100):\n for y in range(1, 100):\n t = counting_rectangles(x, y)\n if 1999000 <= t <= 2100000:\n return x * y\n\n\nprint(solution2())\n# 2772\n","sub_path":"competitiveprogramming-python/src/com/mounacheikhna/euler/85.Counting rectangles.py","file_name":"85.Counting rectangles.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"535245082","text":"# import selenium drivers\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nimport os\nimport pandas as pd\nfrom datetime import datetime\nfrom wordcloud import WordCloud, STOPWORDS\nimport matplotlib.pyplot as plt\nfrom nltk.tokenize import word_tokenize\nfrom time import time\n\n\nclass NewsScraper():\n '''Class to scrape news articles from \"www.energy.gov\"\n '''\n\n def __init__(self, webdriver_path: str, headless: bool, num_pages: int, save_path: str, url: str, delay: int):\n '''\n Parameters\n ----------\n webdriver_path: str, path to chrome webdriver\n headless: bool, whther to run the scraper headlessly\n num_pages: int, number of pages to scrape\n save_path: str, dataset save location (include file name)\n url: str, url to start scraping from\n delay: int, number of seconds to wait for page to load\n '''\n # check parameter types\n if type(webdriver_path) != str or type(headless) != bool or type(num_pages) != int or type(save_path) != str or type(url) != str or type(delay) != int:\n print(\"Type Error: Invalid type in arguements\")\n exit(0)\n if not os.path.exists(webdriver_path):\n print('Webdriver not found')\n exit(0)\n\n self.webdriver_path = webdriver_path\n self.headless = headless\n self.num_pages = num_pages\n self.save_path = save_path\n self.url = url\n self.delay = delay\n\n def init_record(self) -> dict:\n return {'article_date': None, 'article_title': None, 'article_description': '', 'article_url': None}\n\n def wait_for_element(self, classname: str) -> bool:\n try:\n element_present = EC.presence_of_element_located(\n (By.CSS_SELECTOR, classname))\n WebDriverWait(self.driver, self.delay).until(element_present)\n except TimeoutException:\n print(\"Timed out waiting for element\")\n return False\n return True\n\n def get_news_urls(self, page: int) -> list:\n if not self.wait_for_element('.search-result-title'):\n return []\n articles = self.driver.find_elements_by_css_selector(\n '.search-result-title')\n articles = [a.get_property('href') for a in articles]\n print(f'Page: {page+1} Num articles: {len(articles)}')\n return articles\n\n def make_url_clickable(self, url: str) -> str:\n return f'{url}'\n\n def get_record(self, article: str) -> dict:\n record = self.init_record()\n if not self.wait_for_element('.page-hero-date'):\n return record\n\n date = self.driver.find_element_by_css_selector('.page-hero-date').text\n record['article_date'] = datetime.strptime(\n date, '%B %d, %Y').strftime('%Y-%m-%d')\n record['article_title'] = self.driver.find_element_by_css_selector(\n '.page-title').text\n record['article_url'] = article\n desc = self.driver.find_element_by_css_selector(\n 'div.block.block-layout-builder.block-inline-blockbasic')\n record['article_description'] += desc.find_element_by_tag_name(\n 'p').text\n return record\n\n def save_data(self, data: list) -> None:\n df = pd.DataFrame(data)\n df.style.format(self.make_url_clickable, subset=['article_url'])\n df.to_excel(self.save_path, index=False)\n print('Data saved successfully.')\n\n def scrape(self) -> None:\n start = time()\n options = Options()\n if self.headless:\n options.add_argument('--headless')\n self.driver = webdriver.Chrome(self.webdriver_path, options=options)\n\n data = []\n\n try:\n # For each page\n self.driver.get(self.url)\n for i in range(self.num_pages):\n cur_url = self.driver.current_url\n articles = self.get_news_urls(i)\n # For each article\n for article in articles:\n # Open article\n self.driver.get(article)\n\n # Get details\n data.append(self.get_record(article))\n\n self.driver.get(cur_url)\n if not self.wait_for_element('li.pagination-item.pagination-next'):\n break\n self.driver.find_element_by_css_selector(\n 'li.pagination-item.pagination-next').click()\n if self.driver.current_url == cur_url:\n print('No more articles found')\n break\n finally:\n # Close the webdriver\n self.driver.quit()\n\n print(f'Total articles scraped: {len(data)}')\n self.save_data(data)\n print(f'Time elapsed: {(time()-start): .2f} seconds')\n\n\ndef create_word_cloud(save_path):\n df = pd.read_excel(save_path)\n text = ''\n for news in df.article_description.tolist():\n tokens = word_tokenize(str(news))\n for i in range(len(tokens)):\n tokens[i] = tokens[i].lower()\n text += ' '.join(tokens) + ' '\n\n wordcloud = WordCloud(width=2000, height=2000,\n stopwords=set(STOPWORDS)).generate(text)\n\n # plot the WordCloud image\n plt.figure(figsize=(10, 7))\n plt.imshow(wordcloud)\n plt.axis(\"off\")\n plt.tight_layout(pad=0)\n plt.show()\n\n\nif __name__ == '__main__':\n # Constants and Parameters\n URL = 'https://www.energy.gov/listings/energy-news'\n DRIVER_PATH = os.getcwd() + '/chromedriver'\n SAVE_PATH = './energygov_selenium.xlsx'\n HEADLESS = True\n NUM_PAGES = 10\n DELAY = 2\n\n ns = NewsScraper(DRIVER_PATH, HEADLESS, NUM_PAGES, SAVE_PATH, URL, DELAY)\n ns.scrape()\n\n # Comment this if you don't want to plot wordcloud\n create_word_cloud(SAVE_PATH)\n","sub_path":"Company/MindWorksGlobal/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"59348227","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport vkapi\n\n#topics = [{'id':val1, 'title':val2}]\n\nclass topics():\n @staticmethod\n def getAllTopics(token, group_id):#tested\n assert (type(token) is str)\n assert (type(group_id) is int)\n\n return topics.getNewTopics(token, None, group_id)\n\n @staticmethod\n def getNewTopics(token, last_topic_id, group_id):#tested\n assert (type(token) is str)\n assert (type(last_topic_id) is int) or (last_topic_id is None)\n assert (type(group_id) is int)\n\n params = {}\n params['group_id'] = group_id\n params['offset'] = 0\n params['count'] = 100\n\n topics = []\n offset = params['count']\n\n while True:\n data = vkapi.board.getTopics(token, params)['items']\n\n if len(data) == 0:\n break\n\n data.sort(reverse=True, key=lambda x: x['id']) # Самые свежие(большие) id должны быть наверху\n ids = map(lambda x: x['id'], data)\n\n if last_topic_id in ids:\n last_post_key = ids.index(last_topic_id)\n topics += data[0:last_post_key]\n break\n else:\n topics += data\n\n params['offset'] += offset\n\n accepted_keys = ['id', 'created_by', 'title']\n\n for topic in topics:\n keys = topic.keys()\n for key in keys:\n if key not in accepted_keys:\n topic.pop(key, None)\n\n return topics","sub_path":"vkparser/topics.py","file_name":"topics.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"126593212","text":"import typing # noqa: F401\n\nfrom kubernetes import client # noqa: F401\nfrom kuber import kube_api as _kube_api # noqa: F401\n\nfrom kuber import definitions as _kuber_definitions # noqa: F401\nfrom kuber import _types # noqa: F401\nfrom kuber.v1_26.meta_v1 import Condition # noqa: F401\nfrom kuber.v1_26.meta_v1 import DeleteOptions # noqa: F401\nfrom kuber.v1_26.meta_v1 import LabelSelector # noqa: F401\nfrom kuber.v1_26.meta_v1 import ListMeta # noqa: F401\nfrom kuber.v1_26.meta_v1 import ObjectMeta # noqa: F401\nfrom kuber.v1_26.meta_v1 import Status # noqa: F401\nfrom kuber.v1_26.meta_v1 import StatusDetails # noqa: F401\n\n\nclass Eviction(_kuber_definitions.Resource):\n \"\"\"\n Eviction evicts a pod from its node subject to certain\n policies and safety constraints. This is a subresource of\n Pod. A request to cause such an eviction is created by\n POSTing to .../pods//evictions.\n \"\"\"\n\n def __init__(\n self,\n delete_options: typing.Optional[\"DeleteOptions\"] = None,\n metadata: typing.Optional[\"ObjectMeta\"] = None,\n ):\n \"\"\"Create Eviction instance.\"\"\"\n super(Eviction, self).__init__(api_version=\"policy/v1\", kind=\"Eviction\")\n self._properties = {\n \"deleteOptions\": delete_options\n if delete_options is not None\n else DeleteOptions(),\n \"metadata\": metadata if metadata is not None else ObjectMeta(),\n }\n self._types = {\n \"apiVersion\": (str, None),\n \"deleteOptions\": (DeleteOptions, None),\n \"kind\": (str, None),\n \"metadata\": (ObjectMeta, None),\n }\n\n @property\n def delete_options(self) -> \"DeleteOptions\":\n \"\"\"\n DeleteOptions may be provided\n \"\"\"\n return typing.cast(\n \"DeleteOptions\",\n self._properties.get(\"deleteOptions\"),\n )\n\n @delete_options.setter\n def delete_options(self, value: typing.Union[\"DeleteOptions\", dict]):\n \"\"\"\n DeleteOptions may be provided\n \"\"\"\n if isinstance(value, dict):\n value = typing.cast(\n DeleteOptions,\n DeleteOptions().from_dict(value),\n )\n self._properties[\"deleteOptions\"] = value\n\n @property\n def metadata(self) -> \"ObjectMeta\":\n \"\"\"\n ObjectMeta describes the pod that is being evicted.\n \"\"\"\n return typing.cast(\n \"ObjectMeta\",\n self._properties.get(\"metadata\"),\n )\n\n @metadata.setter\n def metadata(self, value: typing.Union[\"ObjectMeta\", dict]):\n \"\"\"\n ObjectMeta describes the pod that is being evicted.\n \"\"\"\n if isinstance(value, dict):\n value = typing.cast(\n ObjectMeta,\n ObjectMeta().from_dict(value),\n )\n self._properties[\"metadata\"] = value\n\n def create_resource(self, namespace: typing.Optional[\"str\"] = None):\n \"\"\"\n Creates the Eviction in the currently\n configured Kubernetes cluster.\n \"\"\"\n names = [\"create_namespaced_eviction\", \"create_eviction\"]\n\n _kube_api.execute(\n action=\"create\",\n resource=self,\n names=names,\n namespace=namespace,\n api_client=None,\n api_args={\"body\": self.to_dict()},\n )\n\n def replace_resource(self, namespace: typing.Optional[\"str\"] = None):\n \"\"\"\n Replaces the Eviction in the currently\n configured Kubernetes cluster.\n \"\"\"\n names = [\"replace_namespaced_eviction\", \"replace_eviction\"]\n\n _kube_api.execute(\n action=\"replace\",\n resource=self,\n names=names,\n namespace=namespace,\n api_client=None,\n api_args={\"body\": self.to_dict(), \"name\": self.metadata.name},\n )\n\n def patch_resource(self, namespace: typing.Optional[\"str\"] = None):\n \"\"\"\n Patches the Eviction in the currently\n configured Kubernetes cluster.\n \"\"\"\n names = [\"patch_namespaced_eviction\", \"patch_eviction\"]\n\n _kube_api.execute(\n action=\"patch\",\n resource=self,\n names=names,\n namespace=namespace,\n api_client=None,\n api_args={\"body\": self.to_dict(), \"name\": self.metadata.name},\n )\n\n def get_resource_status(self, namespace: typing.Optional[\"str\"] = None):\n \"\"\"This resource does not have a status.\"\"\"\n pass\n\n def read_resource(self, namespace: typing.Optional[str] = None):\n \"\"\"\n Reads the Eviction from the currently configured\n Kubernetes cluster and returns the low-level definition object.\n \"\"\"\n names = [\n \"read_namespaced_eviction\",\n \"read_eviction\",\n ]\n return _kube_api.execute(\n action=\"read\",\n resource=self,\n names=names,\n namespace=namespace,\n api_client=None,\n api_args={\"name\": self.metadata.name},\n )\n\n def delete_resource(\n self,\n namespace: typing.Optional[str] = None,\n propagation_policy: str = \"Foreground\",\n grace_period_seconds: int = 10,\n ):\n \"\"\"\n Deletes the Eviction from the currently configured\n Kubernetes cluster.\n \"\"\"\n names = [\n \"delete_namespaced_eviction\",\n \"delete_eviction\",\n ]\n\n body = client.V1DeleteOptions(\n propagation_policy=propagation_policy,\n grace_period_seconds=grace_period_seconds,\n )\n\n _kube_api.execute(\n action=\"delete\",\n resource=self,\n names=names,\n namespace=namespace,\n api_client=None,\n api_args={\"name\": self.metadata.name, \"body\": body},\n )\n\n @staticmethod\n def get_resource_api(\n api_client: typing.Optional[client.ApiClient] = None, **kwargs\n ) -> \"client.PolicyV1Api\":\n \"\"\"\n Returns an instance of the kubernetes API client associated with\n this object.\n \"\"\"\n if api_client:\n kwargs[\"apl_client\"] = api_client\n return client.PolicyV1Api(**kwargs)\n\n def __enter__(self) -> \"Eviction\":\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n return False\n\n\nclass PodDisruptionBudget(_kuber_definitions.Resource):\n \"\"\"\n PodDisruptionBudget is an object to define the max\n disruption that can be caused to a collection of pods\n \"\"\"\n\n def __init__(\n self,\n metadata: typing.Optional[\"ObjectMeta\"] = None,\n spec: typing.Optional[\"PodDisruptionBudgetSpec\"] = None,\n status: typing.Optional[\"PodDisruptionBudgetStatus\"] = None,\n ):\n \"\"\"Create PodDisruptionBudget instance.\"\"\"\n super(PodDisruptionBudget, self).__init__(\n api_version=\"policy/v1\", kind=\"PodDisruptionBudget\"\n )\n self._properties = {\n \"metadata\": metadata if metadata is not None else ObjectMeta(),\n \"spec\": spec if spec is not None else PodDisruptionBudgetSpec(),\n \"status\": status if status is not None else PodDisruptionBudgetStatus(),\n }\n self._types = {\n \"apiVersion\": (str, None),\n \"kind\": (str, None),\n \"metadata\": (ObjectMeta, None),\n \"spec\": (PodDisruptionBudgetSpec, None),\n \"status\": (PodDisruptionBudgetStatus, None),\n }\n\n @property\n def metadata(self) -> \"ObjectMeta\":\n \"\"\"\n Standard object's metadata. More info:\n https://git.k8s.io/community/contributors/devel/sig-\n architecture/api-conventions.md#metadata\n \"\"\"\n return typing.cast(\n \"ObjectMeta\",\n self._properties.get(\"metadata\"),\n )\n\n @metadata.setter\n def metadata(self, value: typing.Union[\"ObjectMeta\", dict]):\n \"\"\"\n Standard object's metadata. More info:\n https://git.k8s.io/community/contributors/devel/sig-\n architecture/api-conventions.md#metadata\n \"\"\"\n if isinstance(value, dict):\n value = typing.cast(\n ObjectMeta,\n ObjectMeta().from_dict(value),\n )\n self._properties[\"metadata\"] = value\n\n @property\n def spec(self) -> \"PodDisruptionBudgetSpec\":\n \"\"\"\n Specification of the desired behavior of the\n PodDisruptionBudget.\n \"\"\"\n return typing.cast(\n \"PodDisruptionBudgetSpec\",\n self._properties.get(\"spec\"),\n )\n\n @spec.setter\n def spec(self, value: typing.Union[\"PodDisruptionBudgetSpec\", dict]):\n \"\"\"\n Specification of the desired behavior of the\n PodDisruptionBudget.\n \"\"\"\n if isinstance(value, dict):\n value = typing.cast(\n PodDisruptionBudgetSpec,\n PodDisruptionBudgetSpec().from_dict(value),\n )\n self._properties[\"spec\"] = value\n\n @property\n def status(self) -> \"PodDisruptionBudgetStatus\":\n \"\"\"\n Most recently observed status of the PodDisruptionBudget.\n \"\"\"\n return typing.cast(\n \"PodDisruptionBudgetStatus\",\n self._properties.get(\"status\"),\n )\n\n @status.setter\n def status(self, value: typing.Union[\"PodDisruptionBudgetStatus\", dict]):\n \"\"\"\n Most recently observed status of the PodDisruptionBudget.\n \"\"\"\n if isinstance(value, dict):\n value = typing.cast(\n PodDisruptionBudgetStatus,\n PodDisruptionBudgetStatus().from_dict(value),\n )\n self._properties[\"status\"] = value\n\n def create_resource(\n self, namespace: typing.Optional[\"str\"] = None\n ) -> \"PodDisruptionBudgetStatus\":\n \"\"\"\n Creates the PodDisruptionBudget in the currently\n configured Kubernetes cluster and returns the status information\n returned by the Kubernetes API after the create is complete.\n \"\"\"\n names = [\n \"create_namespaced_pod_disruption_budget\",\n \"create_pod_disruption_budget\",\n ]\n\n response = _kube_api.execute(\n action=\"create\",\n resource=self,\n names=names,\n namespace=namespace,\n api_client=None,\n api_args={\"body\": self.to_dict()},\n )\n\n output = PodDisruptionBudgetStatus()\n if response is not None:\n output.from_dict(_kube_api.to_kuber_dict(response.status))\n return output\n\n def replace_resource(\n self, namespace: typing.Optional[\"str\"] = None\n ) -> \"PodDisruptionBudgetStatus\":\n \"\"\"\n Replaces the PodDisruptionBudget in the currently\n configured Kubernetes cluster and returns the status information\n returned by the Kubernetes API after the replace is complete.\n \"\"\"\n names = [\n \"replace_namespaced_pod_disruption_budget\",\n \"replace_pod_disruption_budget\",\n ]\n\n response = _kube_api.execute(\n action=\"replace\",\n resource=self,\n names=names,\n namespace=namespace,\n api_client=None,\n api_args={\"body\": self.to_dict(), \"name\": self.metadata.name},\n )\n\n output = PodDisruptionBudgetStatus()\n if response is not None:\n output.from_dict(_kube_api.to_kuber_dict(response.status))\n return output\n\n def patch_resource(\n self, namespace: typing.Optional[\"str\"] = None\n ) -> \"PodDisruptionBudgetStatus\":\n \"\"\"\n Patches the PodDisruptionBudget in the currently\n configured Kubernetes cluster and returns the status information\n returned by the Kubernetes API after the replace is complete.\n \"\"\"\n names = [\n \"patch_namespaced_pod_disruption_budget\",\n \"patch_pod_disruption_budget\",\n ]\n\n response = _kube_api.execute(\n action=\"patch\",\n resource=self,\n names=names,\n namespace=namespace,\n api_client=None,\n api_args={\"body\": self.to_dict(), \"name\": self.metadata.name},\n )\n\n output = PodDisruptionBudgetStatus()\n if response is not None:\n output.from_dict(_kube_api.to_kuber_dict(response.status))\n return output\n\n def get_resource_status(\n self, namespace: typing.Optional[\"str\"] = None\n ) -> \"PodDisruptionBudgetStatus\":\n \"\"\"\n Returns status information about the given resource within the cluster.\n \"\"\"\n names = [\n \"read_namespaced_pod_disruption_budget\",\n \"read_pod_disruption_budget\",\n ]\n\n response = _kube_api.execute(\n action=\"read\",\n resource=self,\n names=names,\n namespace=namespace,\n api_client=None,\n api_args={\"name\": self.metadata.name},\n )\n\n output = PodDisruptionBudgetStatus()\n if response is not None:\n output.from_dict(_kube_api.to_kuber_dict(response.status))\n return output\n\n def read_resource(self, namespace: typing.Optional[str] = None):\n \"\"\"\n Reads the PodDisruptionBudget from the currently configured\n Kubernetes cluster and returns the low-level definition object.\n \"\"\"\n names = [\n \"read_namespaced_pod_disruption_budget\",\n \"read_pod_disruption_budget\",\n ]\n return _kube_api.execute(\n action=\"read\",\n resource=self,\n names=names,\n namespace=namespace,\n api_client=None,\n api_args={\"name\": self.metadata.name},\n )\n\n def delete_resource(\n self,\n namespace: typing.Optional[str] = None,\n propagation_policy: str = \"Foreground\",\n grace_period_seconds: int = 10,\n ):\n \"\"\"\n Deletes the PodDisruptionBudget from the currently configured\n Kubernetes cluster.\n \"\"\"\n names = [\n \"delete_namespaced_pod_disruption_budget\",\n \"delete_pod_disruption_budget\",\n ]\n\n body = client.V1DeleteOptions(\n propagation_policy=propagation_policy,\n grace_period_seconds=grace_period_seconds,\n )\n\n _kube_api.execute(\n action=\"delete\",\n resource=self,\n names=names,\n namespace=namespace,\n api_client=None,\n api_args={\"name\": self.metadata.name, \"body\": body},\n )\n\n @staticmethod\n def get_resource_api(\n api_client: typing.Optional[client.ApiClient] = None, **kwargs\n ) -> \"client.PolicyV1Api\":\n \"\"\"\n Returns an instance of the kubernetes API client associated with\n this object.\n \"\"\"\n if api_client:\n kwargs[\"apl_client\"] = api_client\n return client.PolicyV1Api(**kwargs)\n\n def __enter__(self) -> \"PodDisruptionBudget\":\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n return False\n\n\nclass PodDisruptionBudgetList(_kuber_definitions.Collection):\n \"\"\"\n PodDisruptionBudgetList is a collection of\n PodDisruptionBudgets.\n \"\"\"\n\n def __init__(\n self,\n items: typing.Optional[typing.List[\"PodDisruptionBudget\"]] = None,\n metadata: typing.Optional[\"ListMeta\"] = None,\n ):\n \"\"\"Create PodDisruptionBudgetList instance.\"\"\"\n super(PodDisruptionBudgetList, self).__init__(\n api_version=\"policy/v1\", kind=\"PodDisruptionBudgetList\"\n )\n self._properties = {\n \"items\": items if items is not None else [],\n \"metadata\": metadata if metadata is not None else ListMeta(),\n }\n self._types = {\n \"apiVersion\": (str, None),\n \"items\": (list, PodDisruptionBudget),\n \"kind\": (str, None),\n \"metadata\": (ListMeta, None),\n }\n\n @property\n def items(self) -> typing.List[\"PodDisruptionBudget\"]:\n \"\"\"\n Items is a list of PodDisruptionBudgets\n \"\"\"\n return typing.cast(\n typing.List[\"PodDisruptionBudget\"],\n self._properties.get(\"items\"),\n )\n\n @items.setter\n def items(\n self, value: typing.Union[typing.List[\"PodDisruptionBudget\"], typing.List[dict]]\n ):\n \"\"\"\n Items is a list of PodDisruptionBudgets\n \"\"\"\n cleaned: typing.List[PodDisruptionBudget] = []\n for item in value:\n if isinstance(item, dict):\n item = typing.cast(\n PodDisruptionBudget,\n PodDisruptionBudget().from_dict(item),\n )\n cleaned.append(typing.cast(PodDisruptionBudget, item))\n self._properties[\"items\"] = cleaned\n\n @property\n def metadata(self) -> \"ListMeta\":\n \"\"\"\n Standard object's metadata. More info:\n https://git.k8s.io/community/contributors/devel/sig-\n architecture/api-conventions.md#metadata\n \"\"\"\n return typing.cast(\n \"ListMeta\",\n self._properties.get(\"metadata\"),\n )\n\n @metadata.setter\n def metadata(self, value: typing.Union[\"ListMeta\", dict]):\n \"\"\"\n Standard object's metadata. More info:\n https://git.k8s.io/community/contributors/devel/sig-\n architecture/api-conventions.md#metadata\n \"\"\"\n if isinstance(value, dict):\n value = typing.cast(\n ListMeta,\n ListMeta().from_dict(value),\n )\n self._properties[\"metadata\"] = value\n\n @staticmethod\n def get_resource_api(\n api_client: typing.Optional[client.ApiClient] = None, **kwargs\n ) -> \"client.PolicyV1Api\":\n \"\"\"\n Returns an instance of the kubernetes API client associated with\n this object.\n \"\"\"\n if api_client:\n kwargs[\"apl_client\"] = api_client\n return client.PolicyV1Api(**kwargs)\n\n def __enter__(self) -> \"PodDisruptionBudgetList\":\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n return False\n\n\nclass PodDisruptionBudgetSpec(_kuber_definitions.Definition):\n \"\"\"\n PodDisruptionBudgetSpec is a description of a\n PodDisruptionBudget.\n \"\"\"\n\n def __init__(\n self,\n max_unavailable: typing.Optional[typing.Union[str, int, None]] = None,\n min_available: typing.Optional[typing.Union[str, int, None]] = None,\n selector: typing.Optional[\"LabelSelector\"] = None,\n unhealthy_pod_eviction_policy: typing.Optional[str] = None,\n ):\n \"\"\"Create PodDisruptionBudgetSpec instance.\"\"\"\n super(PodDisruptionBudgetSpec, self).__init__(\n api_version=\"policy/v1\", kind=\"PodDisruptionBudgetSpec\"\n )\n self._properties = {\n \"maxUnavailable\": max_unavailable if max_unavailable is not None else None,\n \"minAvailable\": min_available if min_available is not None else None,\n \"selector\": selector if selector is not None else LabelSelector(),\n \"unhealthyPodEvictionPolicy\": unhealthy_pod_eviction_policy\n if unhealthy_pod_eviction_policy is not None\n else \"\",\n }\n self._types = {\n \"maxUnavailable\": (_types.integer_or_string, None),\n \"minAvailable\": (_types.integer_or_string, None),\n \"selector\": (LabelSelector, None),\n \"unhealthyPodEvictionPolicy\": (str, None),\n }\n\n @property\n def max_unavailable(self) -> typing.Union[str, int, None]:\n \"\"\"\n An eviction is allowed if at most \"maxUnavailable\" pods\n selected by \"selector\" are unavailable after the eviction,\n i.e. even in absence of the evicted pod. For example, one\n can prevent all voluntary evictions by specifying 0. This is\n a mutually exclusive setting with \"minAvailable\".\n \"\"\"\n return typing.cast(\n typing.Union[str, int, None],\n self._properties.get(\"maxUnavailable\"),\n )\n\n @max_unavailable.setter\n def max_unavailable(self, value: typing.Union[str, int, None]):\n \"\"\"\n An eviction is allowed if at most \"maxUnavailable\" pods\n selected by \"selector\" are unavailable after the eviction,\n i.e. even in absence of the evicted pod. For example, one\n can prevent all voluntary evictions by specifying 0. This is\n a mutually exclusive setting with \"minAvailable\".\n \"\"\"\n self._properties[\"maxUnavailable\"] = _types.integer_or_string(value)\n\n @property\n def min_available(self) -> typing.Union[str, int, None]:\n \"\"\"\n An eviction is allowed if at least \"minAvailable\" pods\n selected by \"selector\" will still be available after the\n eviction, i.e. even in the absence of the evicted pod. So\n for example you can prevent all voluntary evictions by\n specifying \"100%\".\n \"\"\"\n return typing.cast(\n typing.Union[str, int, None],\n self._properties.get(\"minAvailable\"),\n )\n\n @min_available.setter\n def min_available(self, value: typing.Union[str, int, None]):\n \"\"\"\n An eviction is allowed if at least \"minAvailable\" pods\n selected by \"selector\" will still be available after the\n eviction, i.e. even in the absence of the evicted pod. So\n for example you can prevent all voluntary evictions by\n specifying \"100%\".\n \"\"\"\n self._properties[\"minAvailable\"] = _types.integer_or_string(value)\n\n @property\n def selector(self) -> \"LabelSelector\":\n \"\"\"\n Label query over pods whose evictions are managed by the\n disruption budget. A null selector will match no pods, while\n an empty ({}) selector will select all pods within the\n namespace.\n \"\"\"\n return typing.cast(\n \"LabelSelector\",\n self._properties.get(\"selector\"),\n )\n\n @selector.setter\n def selector(self, value: typing.Union[\"LabelSelector\", dict]):\n \"\"\"\n Label query over pods whose evictions are managed by the\n disruption budget. A null selector will match no pods, while\n an empty ({}) selector will select all pods within the\n namespace.\n \"\"\"\n if isinstance(value, dict):\n value = typing.cast(\n LabelSelector,\n LabelSelector().from_dict(value),\n )\n self._properties[\"selector\"] = value\n\n @property\n def unhealthy_pod_eviction_policy(self) -> str:\n \"\"\"\n UnhealthyPodEvictionPolicy defines the criteria for when\n unhealthy pods should be considered for eviction. Current\n implementation considers healthy pods, as pods that have\n status.conditions item with type=\"Ready\",status=\"True\".\n\n Valid policies are IfHealthyBudget and AlwaysAllow. If no\n policy is specified, the default behavior will be used,\n which corresponds to the IfHealthyBudget policy.\n\n IfHealthyBudget policy means that running pods\n (status.phase=\"Running\"), but not yet healthy can be evicted\n only if the guarded application is not disrupted\n (status.currentHealthy is at least equal to\n status.desiredHealthy). Healthy pods will be subject to the\n PDB for eviction.\n\n AlwaysAllow policy means that all running pods\n (status.phase=\"Running\"), but not yet healthy are considered\n disrupted and can be evicted regardless of whether the\n criteria in a PDB is met. This means perspective running\n pods of a disrupted application might not get a chance to\n become healthy. Healthy pods will be subject to the PDB for\n eviction.\n\n Additional policies may be added in the future. Clients\n making eviction decisions should disallow eviction of\n unhealthy pods if they encounter an unrecognized policy in\n this field.\n\n This field is alpha-level. The eviction API uses this field\n when the feature gate PDBUnhealthyPodEvictionPolicy is\n enabled (disabled by default).\n \"\"\"\n return typing.cast(\n str,\n self._properties.get(\"unhealthyPodEvictionPolicy\"),\n )\n\n @unhealthy_pod_eviction_policy.setter\n def unhealthy_pod_eviction_policy(self, value: str):\n \"\"\"\n UnhealthyPodEvictionPolicy defines the criteria for when\n unhealthy pods should be considered for eviction. Current\n implementation considers healthy pods, as pods that have\n status.conditions item with type=\"Ready\",status=\"True\".\n\n Valid policies are IfHealthyBudget and AlwaysAllow. If no\n policy is specified, the default behavior will be used,\n which corresponds to the IfHealthyBudget policy.\n\n IfHealthyBudget policy means that running pods\n (status.phase=\"Running\"), but not yet healthy can be evicted\n only if the guarded application is not disrupted\n (status.currentHealthy is at least equal to\n status.desiredHealthy). Healthy pods will be subject to the\n PDB for eviction.\n\n AlwaysAllow policy means that all running pods\n (status.phase=\"Running\"), but not yet healthy are considered\n disrupted and can be evicted regardless of whether the\n criteria in a PDB is met. This means perspective running\n pods of a disrupted application might not get a chance to\n become healthy. Healthy pods will be subject to the PDB for\n eviction.\n\n Additional policies may be added in the future. Clients\n making eviction decisions should disallow eviction of\n unhealthy pods if they encounter an unrecognized policy in\n this field.\n\n This field is alpha-level. The eviction API uses this field\n when the feature gate PDBUnhealthyPodEvictionPolicy is\n enabled (disabled by default).\n \"\"\"\n self._properties[\"unhealthyPodEvictionPolicy\"] = value\n\n def __enter__(self) -> \"PodDisruptionBudgetSpec\":\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n return False\n\n\nclass PodDisruptionBudgetStatus(_kuber_definitions.Definition):\n \"\"\"\n PodDisruptionBudgetStatus represents information about the\n status of a PodDisruptionBudget. Status may trail the actual\n state of a system.\n \"\"\"\n\n def __init__(\n self,\n conditions: typing.Optional[typing.List[\"Condition\"]] = None,\n current_healthy: typing.Optional[int] = None,\n desired_healthy: typing.Optional[int] = None,\n disrupted_pods: typing.Optional[dict] = None,\n disruptions_allowed: typing.Optional[int] = None,\n expected_pods: typing.Optional[int] = None,\n observed_generation: typing.Optional[int] = None,\n ):\n \"\"\"Create PodDisruptionBudgetStatus instance.\"\"\"\n super(PodDisruptionBudgetStatus, self).__init__(\n api_version=\"policy/v1\", kind=\"PodDisruptionBudgetStatus\"\n )\n self._properties = {\n \"conditions\": conditions if conditions is not None else [],\n \"currentHealthy\": current_healthy if current_healthy is not None else None,\n \"desiredHealthy\": desired_healthy if desired_healthy is not None else None,\n \"disruptedPods\": disrupted_pods if disrupted_pods is not None else {},\n \"disruptionsAllowed\": disruptions_allowed\n if disruptions_allowed is not None\n else None,\n \"expectedPods\": expected_pods if expected_pods is not None else None,\n \"observedGeneration\": observed_generation\n if observed_generation is not None\n else None,\n }\n self._types = {\n \"conditions\": (list, Condition),\n \"currentHealthy\": (int, None),\n \"desiredHealthy\": (int, None),\n \"disruptedPods\": (dict, None),\n \"disruptionsAllowed\": (int, None),\n \"expectedPods\": (int, None),\n \"observedGeneration\": (int, None),\n }\n\n @property\n def conditions(self) -> typing.List[\"Condition\"]:\n \"\"\"\n Conditions contain conditions for PDB. The disruption\n controller sets the DisruptionAllowed condition. The\n following are known values for the reason field (additional\n reasons could be added in the future): - SyncFailed: The\n controller encountered an error and wasn't able to compute\n the number of allowed disruptions. Therefore\n no disruptions are\n allowed and the status of the condition will\n be False.\n - InsufficientPods: The number of pods are either at or\n below the number\n required by the PodDisruptionBudget. No\n disruptions are\n allowed and the status of the condition\n will be False.\n - SufficientPods: There are more pods than required by the\n PodDisruptionBudget.\n The condition will be True, and the number\n of allowed\n disruptions are provided by the\n disruptionsAllowed property.\n \"\"\"\n return typing.cast(\n typing.List[\"Condition\"],\n self._properties.get(\"conditions\"),\n )\n\n @conditions.setter\n def conditions(\n self, value: typing.Union[typing.List[\"Condition\"], typing.List[dict]]\n ):\n \"\"\"\n Conditions contain conditions for PDB. The disruption\n controller sets the DisruptionAllowed condition. The\n following are known values for the reason field (additional\n reasons could be added in the future): - SyncFailed: The\n controller encountered an error and wasn't able to compute\n the number of allowed disruptions. Therefore\n no disruptions are\n allowed and the status of the condition will\n be False.\n - InsufficientPods: The number of pods are either at or\n below the number\n required by the PodDisruptionBudget. No\n disruptions are\n allowed and the status of the condition\n will be False.\n - SufficientPods: There are more pods than required by the\n PodDisruptionBudget.\n The condition will be True, and the number\n of allowed\n disruptions are provided by the\n disruptionsAllowed property.\n \"\"\"\n cleaned: typing.List[Condition] = []\n for item in value:\n if isinstance(item, dict):\n item = typing.cast(\n Condition,\n Condition().from_dict(item),\n )\n cleaned.append(typing.cast(Condition, item))\n self._properties[\"conditions\"] = cleaned\n\n @property\n def current_healthy(self) -> int:\n \"\"\"\n current number of healthy pods\n \"\"\"\n return typing.cast(\n int,\n self._properties.get(\"currentHealthy\"),\n )\n\n @current_healthy.setter\n def current_healthy(self, value: int):\n \"\"\"\n current number of healthy pods\n \"\"\"\n self._properties[\"currentHealthy\"] = value\n\n @property\n def desired_healthy(self) -> int:\n \"\"\"\n minimum desired number of healthy pods\n \"\"\"\n return typing.cast(\n int,\n self._properties.get(\"desiredHealthy\"),\n )\n\n @desired_healthy.setter\n def desired_healthy(self, value: int):\n \"\"\"\n minimum desired number of healthy pods\n \"\"\"\n self._properties[\"desiredHealthy\"] = value\n\n @property\n def disrupted_pods(self) -> dict:\n \"\"\"\n DisruptedPods contains information about pods whose eviction\n was processed by the API server eviction subresource handler\n but has not yet been observed by the PodDisruptionBudget\n controller. A pod will be in this map from the time when the\n API server processed the eviction request to the time when\n the pod is seen by PDB controller as having been marked for\n deletion (or after a timeout). The key in the map is the\n name of the pod and the value is the time when the API\n server processed the eviction request. If the deletion\n didn't occur and a pod is still there it will be removed\n from the list automatically by PodDisruptionBudget\n controller after some time. If everything goes smooth this\n map should be empty for the most of the time. Large number\n of entries in the map may indicate problems with pod\n deletions.\n \"\"\"\n return typing.cast(\n dict,\n self._properties.get(\"disruptedPods\"),\n )\n\n @disrupted_pods.setter\n def disrupted_pods(self, value: dict):\n \"\"\"\n DisruptedPods contains information about pods whose eviction\n was processed by the API server eviction subresource handler\n but has not yet been observed by the PodDisruptionBudget\n controller. A pod will be in this map from the time when the\n API server processed the eviction request to the time when\n the pod is seen by PDB controller as having been marked for\n deletion (or after a timeout). The key in the map is the\n name of the pod and the value is the time when the API\n server processed the eviction request. If the deletion\n didn't occur and a pod is still there it will be removed\n from the list automatically by PodDisruptionBudget\n controller after some time. If everything goes smooth this\n map should be empty for the most of the time. Large number\n of entries in the map may indicate problems with pod\n deletions.\n \"\"\"\n self._properties[\"disruptedPods\"] = value\n\n @property\n def disruptions_allowed(self) -> int:\n \"\"\"\n Number of pod disruptions that are currently allowed.\n \"\"\"\n return typing.cast(\n int,\n self._properties.get(\"disruptionsAllowed\"),\n )\n\n @disruptions_allowed.setter\n def disruptions_allowed(self, value: int):\n \"\"\"\n Number of pod disruptions that are currently allowed.\n \"\"\"\n self._properties[\"disruptionsAllowed\"] = value\n\n @property\n def expected_pods(self) -> int:\n \"\"\"\n total number of pods counted by this disruption budget\n \"\"\"\n return typing.cast(\n int,\n self._properties.get(\"expectedPods\"),\n )\n\n @expected_pods.setter\n def expected_pods(self, value: int):\n \"\"\"\n total number of pods counted by this disruption budget\n \"\"\"\n self._properties[\"expectedPods\"] = value\n\n @property\n def observed_generation(self) -> int:\n \"\"\"\n Most recent generation observed when updating this PDB\n status. DisruptionsAllowed and other status information is\n valid only if observedGeneration equals to PDB's object\n generation.\n \"\"\"\n return typing.cast(\n int,\n self._properties.get(\"observedGeneration\"),\n )\n\n @observed_generation.setter\n def observed_generation(self, value: int):\n \"\"\"\n Most recent generation observed when updating this PDB\n status. DisruptionsAllowed and other status information is\n valid only if observedGeneration equals to PDB's object\n generation.\n \"\"\"\n self._properties[\"observedGeneration\"] = value\n\n def __enter__(self) -> \"PodDisruptionBudgetStatus\":\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n return False\n","sub_path":"kuber/v1_26/policy_v1.py","file_name":"policy_v1.py","file_ext":"py","file_size_in_byte":35916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"449469489","text":"# pylint: disable=C0321,C0103,E1221,C0301,E1305,E1121,C0302,C0330\n# -*- coding: utf-8 -*-\n\"\"\"\n### Usage:\n python tsampler.py train_sampler --config config_sampler\n python tsampler.py transform_sampler --config config_sampler\n\n\n\n\"\"\"\nimport warnings, copy, os, sys\nwarnings.filterwarnings(\"ignore\")\n\n####################################################################################\n###### Path ########################################################################\nroot_repo = os.path.abspath(os.getcwd()).replace(\"\\\\\", \"/\") + \"/\" ; print(root_repo)\nTHIS_FILEPATH = os.path.abspath(__file__) \n\nsys.path.append(root_repo)\nfrom source.util_feature import save,os_get_function_name\n\ndef global_pars_update(model_dict, data_name, config_name):\n print(\"config_name\", config_name)\n dir_data = root_repo + \"/data/\" ; print(\"dir_data\", dir_data)\n\n m = {}\n m[\"config_path\"] = THIS_FILEPATH \n m[\"config_name\"] = config_name\n m[\"model_file\"] = \"model_sampler\"\n\n #### peoprocess input path\n m[\"path_data_preprocess\"] = dir_data + f\"/input/{data_name}/train/\"\n\n #### train input path\n dir_data_url = \"https://github.com/arita37/dsa2_data/tree/master/\" #### Remote Data directory\n m[\"path_data_train\"] = dir_data_url + f\"/input/{data_name}/train/\"\n m[\"path_data_test\"] = dir_data_url + f\"/input/{data_name}/test/\"\n #m[\"path_data_val\"] = dir_data + f\"/input/{data_name}/test/\"\n\n #### train output path\n m[\"path_train_output\"] = dir_data + f\"/output/{data_name}/{config_name}/\"\n m[\"path_train_model\"] = dir_data + f\"/output/{data_name}/{config_name}/model/\"\n m[\"path_features_store\"] = dir_data + f\"/output/{data_name}/{config_name}/features_store/\"\n m[\"path_pipeline\"] = dir_data + f\"/output/{data_name}/{config_name}/pipeline/\"\n\n\n #### predict input path\n m[\"path_pred_data\"] = dir_data + f\"/input/{data_name}/test/\"\n m[\"path_pred_pipeline\"] = dir_data + f\"/output/{data_name}/{config_name}/pipeline/\"\n m[\"path_pred_model\"] = dir_data + f\"/output/{data_name}/{config_name}/model/\"\n\n #### predict output path\n m[\"path_pred_output\"] = dir_data + f\"/output/{data_name}/pred_{config_name}/\"\n\n ##### Generic\n m[\"n_sample\"] = model_dict[\"data_pars\"].get(\"n_sample\", 5000)\n\n model_dict[ \"global_pars\"] = m\n return model_dict\n\n\n####################################################################################\n##### Params########################################################################\nconfig_default = \"config_sampler\" ### name of function which contains data configuration\n\n\ncols_input_type_1 = {\n \"coly\" : \"Survived\"\n ,\"colid\" : \"PassengerId\"\n ,\"colcat\" : [\"Sex\", \"Embarked\" ]\n ,\"colnum\" : [\"Pclass\", \"Age\",\"SibSp\", \"Parch\",\"Fare\"]\n ,\"coltext\" : []\n ,\"coldate\" : []\n ,\"colcross\" : [ \"Name\", \"Sex\", \"Ticket\",\"Embarked\",\"Pclass\", \"Age\", \"SibSp\", ]\n}\n\n\n####################################################################################\ndef config_sampler() :\n \"\"\"\n ONE SINGLE DICT Contains all needed informations for\n used for titanic classification task\n \"\"\"\n data_name = \"titanic\" ### in data/input/\n model_class = \"CTGAN\" ### ACTUAL Class name for model_sklearn.py\n n_sample = 1000\n\n def post_process_fun(y): ### After prediction is done\n return int(y)\n\n def pre_process_fun(y): ### Before the prediction is done\n return int(y)\n\n model_dict = {\n \"model_pars\": {\n \"model_class\": model_class\n ,\"model_pars\" : { }\n , \"post_process_fun\" : post_process_fun ### After prediction ##########################################\n , \"pre_process_pars\" : {\n \"y_norm_fun\" : pre_process_fun , ### Before training ##########################\n ### Pipeline for data processing ##############################\n \"pipe_list\": [\n #### coly target prorcessing\n {\"uri\": \"source/prepro.py::pd_coly\", \"pars\": {}, \"cols_family\": \"coly\", \"cols_out\": \"coly\", \"type\": \"coly\" },\n\n {\"uri\": \"source/prepro.py::pd_colnum_bin\", \"pars\": {}, \"cols_family\": \"colnum\", \"cols_out\": \"colnum_bin\", \"type\": \"\" },\n {\"uri\": \"source/prepro.py::pd_colnum_binto_onehot\", \"pars\": {}, \"cols_family\": \"colnum_bin\", \"cols_out\": \"colnum_onehot\", \"type\": \"\" },\n\n #### catcol INTO integer, colcat into OneHot\n {\"uri\": \"source/prepro.py::pd_colcat_bin\", \"pars\": {}, \"cols_family\": \"colcat\", \"cols_out\": \"colcat_bin\", \"type\": \"\" },\n {\"uri\": \"source/prepro.py::pd_colcat_to_onehot\", \"pars\": {}, \"cols_family\": \"colcat_bin\", \"cols_out\": \"colcat_onehot\", \"type\": \"\" },\n\n ],\n }\n },\n\n \"compute_pars\": { \"metric_list\": [\"accuracy_score\",\"average_precision_score\"]\n # ,\"mlflow_pars\" : {} ### Not empty --> use mlflow\n },\n\n \"data_pars\": { \n \"n_sample\" : n_sample,\n \"download_pars\" : None,\n ### Filter data rows ##################################################################\n \"filter_pars\": { \"ymax\" : 2 ,\"ymin\" : -1 },\n\n ### Raw data: column input ##############################################################\n \"cols_input_type\" : cols_input_type_1,\n\n\n ### Model Input : Merge family of columns #############################################\n \"cols_model_group\": [ \"colnum_bin\", \"colcat_bin\",]\n\n #### Model Input : Separate Category Sparse from Continuous : Aribitrary name is OK (!)\n ,'cols_model_type': {\n 'continuous' : [ 'colnum', ],\n 'sparse' : [ 'colcat_bin', 'colnum_bin', ],\n 'my_split_23' : [ 'colnum_bin', ],\n }\n\n }\n }\n\n ##### Filling Global parameters ############################################################\n model_dict = global_pars_update(model_dict, data_name, config_name=os_get_function_name() )\n return model_dict\n\n\n\n#####################################################################################\n########## Profile data #############################################################\nfrom core_run import data_profile\n# def data_profile(path_data=\"\", path_output=\"\", n_sample= 5000):\n\n\n\n###################################################################################\n########## Preprocess #############################################################\n### def preprocess(config=\"\", nsample=1000):\nfrom core_run import preprocess\n\n\n\n\n##################################################################################\n########## Train #################################################################\n# def train_sampler(config=None, nsample=None):\nfrom core_run import train_sampler\n\n\n\ndef test_batch():\n from core_run import get_config_path, get_global_pars\n mdict = config_sampler()\n\n nsample = 100\n config = \"\"\n ll = [\n ('CTGAN', { })\n ]\n\n for m in ll :\n mdict['model_pars']['model_class'] = m[0]\n mdict['model_pars']['model_pars'] = m[1]\n\n config_uri, config_name = get_config_path(config)\n\n mdict = get_global_pars( config_uri)\n m = mdict['global_pars']\n print(mdict)\n from source import run_sampler\n run_sampler.run_train(config_name = None,\n config_path = None,\n n_sample = nsample if nsample is not None else m['n_sample'],\n model_dict= mdict\n # use_mlmflow = False\n )\n\n\n####################################################################################\n####### Inference ##################################################################\n# predict(config=\"\", nsample=10000)\n# from core_run import transform_sampler\n\n\n\n\n\n###########################################################################################################\n###########################################################################################################\nif __name__ == \"__main__\":\n import fire\n fire.Fire()\n \n\n\n\n","sub_path":"tsampler.py","file_name":"tsampler.py","file_ext":"py","file_size_in_byte":8441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"242694813","text":"from django.db import models\nimport django.core.validators\nfrom django.core.exceptions import ValidationError\nimport Company.models\nfrom Registration.models import Account\nfrom math import ceil\nimport string\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import *\nfrom random import *\nfrom datetime import date\n\n############################################# Helper Functions ##########################################\nGARYID = 2\n\n############################################# Models ###################################################\n\n\nclass Major(models.Model):\n db_table = 'Majors',\n major = models.CharField(max_length=50, primary_key=True)\n\n @staticmethod\n def getMajorList():\n return [dic['major'] for dic in Major.objects.values('major')]\n\n\nclass Degree(models.Model):\n db_table = 'Degrees'\n\n # FIXME : Multiple choice field can't be set as primary key.\n ''' \n DEGREE_CHOICES = (\n ('BS', 'BS'),\n ('BA', 'BA'),\n ('MS', 'MS'),\n ('MA', 'MA'),\n ('Ph.D', 'Ph.D'),\n )'''\n degree = models.CharField(max_length=15, primary_key=True)\n\n @staticmethod\n def getDegreeList():\n return [dic['degree'] for dic in Degree.objects.values('degree')]\n\n\nclass User(models.Model):\n db_table = 'user',\n acc = models.OneToOneField(Account, on_delete=models.CASCADE, null=True)\n F_Name = models.CharField(max_length=20)\n L_Name = models.CharField(max_length=20)\n # p_id = models.CharField(max_length=1500)\n # ProfilePic = models.ImageField(upload_to='profile_image', blank=True, default='profile_image/File_Pikachu.png')\n yr_graduation = models.IntegerField(validators=[django.core.validators.MaxValueValidator(2050, message='Year of graduation should be less than 2050!'),\n django.core.validators.MinValueValidator(1970, message='Year of graduation should be more than 1970!')])\n major = models.ForeignKey(Major, null=True, on_delete=models.PROTECT)\n degree = models.ForeignKey(Degree, null=True, on_delete=models.PROTECT)\n contact_email = models.EmailField(verbose_name='email address', null=True, max_length=255, unique=True)\n description = models.CharField(max_length=1500,\n validators=[django.core.validators.MinLengthValidator(50, message='Description must be at least 50 characters!')])\n referral_ability = models.BooleanField(default=False)\n company = models.ForeignKey(Company.models.Company, on_delete=models.PROTECT, null=True, blank=True)\n friend = models.ManyToManyField('User', symmetrical=True, blank=True)\n recommended_users = models.ManyToManyField('User', symmetrical=False, blank=True, related_name='recommended')\n picdata = models.CharField(max_length=256000)\n search_result = models.ManyToManyField('User', symmetrical=False, blank=True, related_name='result')\n\n\n ################################################################## Getters\n\n\n # define the string representation of the user objects\n def __str__(self):\n return self.F_Name + \" \" + self.L_Name\n\n # get the number of common friends between two users\n # parameters user1 and user2 are user objects\n @staticmethod\n def get_common_friend_number(user1, user2):\n if type(user1) != User or type(user2) != User:\n return False\n user1Friends = set(user1.friend.all())\n user2Friends = set(user2.friend.all())\n return len(user1Friends.intersection(user2Friends))\n\n # get the referral list of a user\n # parameter user is an automatically generated user object id\n @staticmethod\n def get_referral_list(userId):\n try:\n user = User.objects.get(id=userId)\n except:\n return False\n\n referralList = []\n for pal in user.friend.all():\n if pal.referral_ability:\n referralList.append(pal)\n if user.referral_ability:\n referralList.append(user)\n return referralList\n\n # get_user_by_name\n @staticmethod\n def get_user_by_name(fname, lname):\n if type(fname) != str or type(lname) != str:\n return False\n else:\n return User.objects.all.filter(F_Name=fname, L_Name=lname)\n\n # get_user_by_graduation\n @staticmethod\n def get_user_by_graduation(yr_grad):\n if type(yr_grad) != int or yr_grad < 1970 or yr_grad > 2050:\n return False\n else:\n return User.objects.all.filter(yr_graduation=yr_grad)\n\n # get_user_by_major\n @staticmethod\n def get_user_by_major(major):\n if type(major) != Major:\n return False\n else:\n return User.objects.all.filter(Major=major)\n\n # get_user_by_degree\n @staticmethod\n def get_user_by_degree(degree):\n if type(degree) != Degree:\n return False\n else:\n return User.objects.all.filter(Degree=degree)\n\n # get_user_by_company\n @staticmethod\n def get_user_by_company(company):\n if type(company) != Company.models.Company:\n return False\n else:\n return User.objects.all.filter(Company=company)\n\n\n ################################################################## Setter\n\n\n # set a user's 'friends who has common friends with the user' list\n # parameter user is a user object\n @staticmethod\n def set_recommended_list(user):\n if type(user) != User:\n return False\n\n for guy in User.objects.all():\n if len(set(user.friend.all()).intersection(set(guy.friend.all()))) != 0:\n if guy not in user.friend.all() and guy != user:\n user.recommended_users.add(guy)\n\n num_of_users = User.objects.all().count()\n # if the total number user is smaller than 5, add all users to his recommended list\n if num_of_users < 6:\n for pal in User.objects.all():\n if pal != user:\n user.recommended_users.add(pal)\n else:\n while len(user.recommended_users.all()) < 6:\n index = randint(0, num_of_users - 1)\n user.recommended_users.add(User.objects.all()[index])\n return True\n\n # set_fname\n def set_fname(self, fname):\n if type(fname) != str:\n return False\n else:\n self.F_Name = fname\n return True\n\n # set_lname\n def set_lname(self, lname):\n if type(lname) != str:\n return False\n else:\n self.L_Name = lname\n return True\n\n # set_yr_grad\n def set_yr_grad(self, yr_grad):\n if type(yr_grad) != int or yr_grad < 1970 or yr_grad > 2050:\n return False\n else:\n self.yr_graduation = yr_grad\n return True\n\n # set_major\n def set_major(self, majr):\n if type(majr) != Major:\n return False\n else:\n self.major = majr\n return True\n\n # set_degree\n def set_degree(self, deg):\n if type(deg) != Degree:\n return False\n else:\n self.degree = deg\n return True\n\n # set_email\n def set_email(self, email):\n try:\n django.core.validators.validate_email(email)\n self.contact_email = email\n\n except ValidationError:\n return False\n return True\n\n # set_description\n def set_description(self, descrip):\n if type(descrip) != str or len(descrip) > 300 or len(descrip) < 50:\n return False\n else:\n self.description = descrip\n return True\n\n # add_company\n def add_company(self, comp):\n if type(comp) != Company.models.Company:\n return False\n else:\n self.company.add(comp)\n return True\n\n # remove_company\n def remove_company(self, comp):\n if type(comp) != Company.models.Company:\n return False\n else:\n self.company.remove(comp)\n return True\n\n # send_request\n def send_request(self, target):\n if type(target) != User:\n return False\n else:\n if not Request.objects.filter(from_user=self).filter(to_user=target):\n request = Request(from_user=self, to_user=target)\n request.save()\n if User.get_gary() is not None:\n if target == User.get_gary():\n target.accept_request(request)\n return True\n else:\n return False\n\n # accept_request\n def accept_request(self, request):\n if type(request) != Request:\n return False\n else:\n if request.to_user == self:\n self.friend.add(request.from_user)\n request.delete()\n return True\n else:\n return False\n\n # deny_request\n def deny_request(self, request):\n if type(request) != Request:\n return False\n else:\n request.delete()\n return True\n\n # remove_friend\n def remove_friend(self, todelete):\n if type(todelete) != User:\n return False\n elif todelete in self.friend.all():\n self.friend.remove(todelete)\n return True\n else:\n return False\n\n # undo_request\n def undo_request(self, request):\n if type(request) != Request:\n return False\n else:\n request.delete()\n return True\n\n # update_user_info\n def update_user_info(self, major, degree, contact_email, description, year_graduation, company):\n if major:\n major_obj = list(Major.objects.filter(major=major))[0]\n self.major = major_obj\n if degree:\n degree_obj = list(Degree.objects.filter(degree=degree))[0]\n self.degree = degree_obj\n if contact_email:\n self.contact_email = contact_email\n if description:\n self.description = description\n if year_graduation:\n self.yr_graduation = year_graduation\n if company:\n company_obj = list(Company.models.Company.objects.filter(company_name=company))[0]\n self.company = company_obj\n self.save()\n return True\n\n # get_go_events\n def get_go_events_today(self):\n return self.go.filter(date=date.today()).order_by('time')\n\n # clear_search_results\n def clear_search_results(self):\n self.search_result.clear()\n return\n\n # This function is for demonstration purposes\n # get_gary\n @staticmethod\n def get_gary():\n try:\n User.objects.get(id=GARYID)\n return User.objects.get(id=GARYID)\n except:\n return None\n\n # gary_send_request\n @staticmethod\n def gary_send_request(user):\n print('db')\n gary = User.get_gary()\n if gary is not None:\n if gary.send_request(user):\n return True\n else:\n return False\n else:\n return False\n\n\nclass Request(models.Model):\n from_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sent_request')\n to_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='received_request')\n\n\nRELEVANT_COEFFICIENT = 0.5\nPUNCTUATIONS = set(string.punctuation)\nSTOPWORDS = set(stopwords.words('english'))\nSTEMMER = PorterStemmer()\nINFINITY = 999999\n\n\n# helper method - string pre-processing\n# return a list of stemmed words in the string in lowercase without punctuations, stop words, or repeated words\ndef string_preprocess(to_process):\n if type(to_process) != str:\n return []\n else:\n to_process = ''.join([char for char in to_process.lower() if char not in PUNCTUATIONS])\n processed = set()\n for word in to_process.split():\n if word not in STOPWORDS:\n word = STEMMER.stem(word)\n processed.add(word)\n return processed\n\n\n# search_by_Keywords\ndef search_By_Keywords(keywords):\n if type(keywords) != str:\n return False\n else:\n # keywords pre-processing:\n keywords = string_preprocess(keywords)\n\n relevant_usr = []\n if len(keywords) == 0:\n threshold = INFINITY\n else:\n threshold = ceil(RELEVANT_COEFFICIENT * len(keywords))\n\n for usr in User.objects.all():\n\n # description pre-processing\n full_name = usr.__str__()\n full_name = string_preprocess(full_name)\n\n # comparing keywords with job descriptions\n counter = 0\n for word in keywords:\n if word in full_name:\n counter += 1\n\n if counter >= threshold:\n relevant_usr.append(usr)\n return relevant_usr\n","sub_path":"Django_UCSD/User/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":12898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"159671050","text":"from random import *\n\nclass Ball:\n\n\n def __init__(self, canvas, x, y, color):\n\n self.diameter = 10\n self.color = color\n\n self.canvas = canvas\n self.ball = canvas.create_oval(x, y, x+self.diameter, self.diameter, fill=self.color)\n\n self.corner = 1 if (randint(0, 1) > 0.5) else -1 # which corner ball is headed 1 = right -1 = left\n\n # represents the direction in which the ball is going\n # [1, 1] = SouthEast\n # [1, -1] = NorthEast\n # [-1, 1] = SouthWest\n # [-1, -1] = NorthWest\n self.direction = [self.corner, 1]\n\n # we need this to allow ball to move away from the\n # top of the screen (where it initially comes from)\n # and not bounce off the top until it has moved away\n self.has_moved = False\n\n\n # we need this to keep track of which balls have\n # moved off the screen (i.e. passed the bottom)\n self.moved_off_screen = False\n\n\n\n # move the ball and bounce off walls/paddle accordingly\n # takes the only paddle in the game as input to \n # check whether ball has touched the paddle and if\n # it does then increment score\n def move_ball(self, paddle, score):\n\n ball_coords = self.canvas.coords(self.ball)\n canvas_width = self.canvas.winfo_width()\n canvas_height = self.canvas.winfo_height()\n paddle_corner = paddle.return_coords()[0]\n paddle_width = 100\n\n x1 = ball_coords[0]\n y1 = ball_coords[1]\n x2 = ball_coords[2]\n y2 = ball_coords[3]\n\n\n # if a ball touches the left or right side of the screen\n # bounce in the opposite horizontal direction\n if x1 <= 0 or x2 >= canvas_width:\n\n self.direction[0] *= -1\n self.canvas.move(self.ball, self.direction[0]*2, self.direction[1]*2)\n\n\n # if a ball touches the top of the screen AFTER\n # it has already moved away from the top (because all\n # balls are generated from top of screen) then bounce\n if y1 <= 0 and self.has_moved:\n\n self.direction[1] *= -1\n self.canvas.move(self.ball, self.direction[0]*2, self.direction[1]*2)\n\n\n # if a ball touches the top of the paddle then bounce and add 1 to score\n if 450 <= y2 < 460 and paddle_corner <= x1 < paddle_corner+paddle_width-self.diameter:\n\n self.direction[1] *= -1\n self.canvas.move(self.ball, self.direction[0]*2, self.direction[1]*2)\n score.update_score()\n\n if y1 >= 500 and not self.moved_off_screen:\n \n score.update_lives()\n self.moved_off_screen = True\n\n\n # keep the ball moving\n self.canvas.move(self.ball, self.direction[0]*2, self.direction[1]*2)\n self.has_moved = True\n\n\n # change the coordinates of the ball every \n # 10 milliseconds simulating a moving ball\n self.canvas.after(10, self.move_ball, paddle, score)\n\n\n\n \n \n \n","sub_path":"Ball.py","file_name":"Ball.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"339698404","text":"from Cit_par import *\nimport control as ctr\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\nt_start = 0.\nt_end = 15.\ndt = 0.01\n\nt = np.arange(t_start, t_end + dt,dt)\n\n\nC1_s = np.array([[-2*muc*(c/(Vt0**2)), 0, 0, 0],\n [0, (CZadot -2*muc)*(c/Vt0), 0, 0],\n [0, 0, -(c/Vt0), 0],\n [0, Cmadot*(c/Vt0), 0, -2*muc*KY2*(c/Vt0)**2]])\n\nC2_s = np.array([[CXu*(1/Vt0), CXa, CZ0, CXq*(c/Vt0)],\n [CZu*(1/Vt0), CZa, -CX0, (CZq+2*muc)*(c/Vt0)],\n [0,0,0,(c/Vt0)],\n [Cmu*(1/Vt0), Cma, 0, Cmq*(c/Vt0)]])\n\nC3_s = np.array([[CXde],\n [CZde],\n [0],\n [Cmde]])\n\n\nC1_a = np.array([[(CYbdot - 2* mub) *(b/Vt0),0,0,0],\n [0,-0.5*(b/Vt0),0,0],\n [0,0,-2*mub*KX2*(b/Vt0)**2, 2*mub*KXZ*(b/Vt0)**2],\n [Cnbdot*(b/Vt0), 0 , 2*mub*KXZ*(b/Vt0)**2 , -2*mub*KZ2*(b/Vt0)**2]])\nC2_a = np.array([[CYb,CL,CYp*(b/(2*Vt0)), (CYr -4*mub)*(b/(2*Vt0))],\n [0,0,(b/(2*Vt0)),0],\n [Clb,0,Clp*(b/(2*Vt0)), Clr*(b/(2*Vt0))],\n [Cnb,0,Cnp*(b/(2*Vt0)), Cnr*(b/(2*Vt0))]])\nC3_a = np.array([[CYda,CYdr],\n [0,0],\n [Clda,Cldr],\n [Cnda,Cndr]])\n\nA_s = np.matmul(-np.linalg.inv(C1_s),C2_s)\nB_s = np.matmul(-np.linalg.inv(C1_s),C3_s)\nC_s = np.array([[1,0,0,0],\n [0,1,0,0],\n [0,0,1,0],\n [0,0,0,1]])\nD_s = np.array([[0],\n [0],\n [0],\n [0]])\n\nA_a = np.matmul(-np.linalg.inv(C1_a),C2_a)\nB_a = np.matmul(-np.linalg.inv(C1_a),C3_a)\nC_a = np.array([[1,0,0,0],\n [0,1,0,0],\n [0,0,1,0],\n [0,0,0,1]])\nD_a = np.array([[0,0],\n [0,0],\n [0,0],\n [0,0]])\n\nsys_s = ctr.ss(A_s, B_s, C_s, D_s)\nsys_a = ctr.ss(A_a, B_a, C_a, D_a)\n\ndef Symmetric_plot():\n #for i in range(len(time)):\n # u_s[i] =u_s[i]*0.5\n t_s, y_s, xouts = ctr.forced_response(sys_s,time, u_s, X0=0)\n damp_s = ctr.damp(sys_s)\n for i in range(len(time)):\n y_s[0][i]= y_s[0][i] + Vt0\n y_s[1][i]= y_s[1][i] + alpha0\n y_s[2][i]= y_s[2][i] + th0\n \n plt.subplot(221)\n plt.plot(time, y_s[0], label = 'u')\n plt.plot(time, u, label = 'u data')\n plt.legend()\n \n plt.subplot(222)\n plt.plot(time, y_s[1], label = 'alpha')\n plt.plot(time, alpha, label = 'alpha data')\n plt.legend()\n \n plt.subplot(223)\n plt.plot(time, y_s[2], label = 'theta')\n plt.plot(time, pitch, label = 'theta data')\n plt.legend()\n \n plt.subplot(224)\n plt.plot(time, y_s[3], label = 'pitch rate')\n plt.plot(time, pitch_rate, label = 'pitch rate data')\n plt.legend()\n plt.show()\n \ndef Asymmetric_plot():\n u_a = []\n# Rudder is wrongly defined, corrected with a minus sign\n for i in range(len(time)):\n delta_r[i]= -delta_r[i]\n delta_a[i]= -delta_a[i]\n roll[i] = roll[i]-roll0\n roll_rate[i] = roll_rate[i]-roll_rate0\n yaw_rate[i] = yaw_rate[i] - yaw_rate0\n \n u_a.append(delta_a)\n u_a.append(delta_r)\n \n t_a, y_a, xout = ctr.forced_response(sys_a,time, u_a, X0=0.)\n damp_a = ctr.damp(sys_a)\n \n plt.subplot(221)\n plt.title(\"Side Slip\")\n plt.plot(time, y_a[0], color = \"orange\" ,label = 'Side slip numerical model')\n plt.plot(time,delta_r)\n plt.plot(time,delta_a)\n plt.xlabel(\"Time (s)\")\n plt.ylabel('$\\\\beta (rad)$')\n plt.grid()\n \n #plt.plot(time, u_data, label = 'side slip data')\n plt.legend()\n \n plt.subplot(222)\n plt.title(\"Roll\")\n plt.plot(time, roll, color = \"darkblue\" ,label = 'Roll data')\n plt.plot(time, y_a[1], color = \"orange\" ,label = 'Roll numerical model')\n plt.xlabel(\"Time (s)\")\n plt.ylabel('$\\\\phi$ (rad)')\n plt.grid()\n plt.legend()\n \n plt.subplot(223)\n plt.title(\"Roll rate\")\n\n plt.plot(time, roll_rate , color = \"darkblue\" , label = 'Roll rate data')\n plt.plot(time, y_a[2], color = \"orange\" ,label = 'Roll rate numerical model')\n plt.xlabel(\"Time (s)\")\n plt.ylabel('$p$ (rad/s)')\n plt.grid()\n plt.legend()\n \n plt.subplot(224)\n plt.title(\"Yaw rate\")\n \n plt.plot(time, yaw_rate,color = \"darkblue\" , label = 'Yaw rate data')\n plt.plot(time, y_a[3], color = \"orange\" ,label = 'Yaw rate numerical model')\n plt.xlabel(\"Time (s)\")\n plt.ylabel(\"$r$ (rad/s)\")\n plt.grid()\n plt.legend()\n plt.show()\n \n\n\nAsymmetric_plot()\n\n\n","sub_path":"Numerical_model.py","file_name":"Numerical_model.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"423004292","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#\n# Date : 15/01/07 19:21:42\n# Desc :\n#\n\nimport os\nimport subprocess\nimport logging\nimport yaml\nimport getpass\nimport ConfigParser\nfrom caliper.server.shared import error\nfrom caliper.server.shared import caliper_path\n\n\nclass SettingsError(error.AutoError):\n pass\n\n\nclass SettingsValueError(SettingsError):\n pass\n\nsettings_filename = 'project_config.cfg'\nshadow_config_filename = 'shadow_config.cfg'\n\nsettings_path_root = os.path.join(\n caliper_path.config_files.config_dir,\n settings_filename)\nconfig_in_root = os.path.exists(settings_path_root)\n\n# need to change\nif config_in_root:\n DEFAULT_CONFIG_FILE = settings_path_root\n RUNNING_STAND_ALONE_CLIENT = False\nelse:\n DEFAULT_CONFIG_FILE = None\n RUNNING_STAND_ALONE_CLIENT = False\n\nclass Settings(object):\n _NO_DEFAULT_SPECIFIED = object()\n\n config = None\n config_file = DEFAULT_CONFIG_FILE\n running_stand_alone_client = RUNNING_STAND_ALONE_CLIENT\n\n def check_stand_alone_client_run(self):\n return self.running_stand_alone_client\n\n def set_config_files(self, config_file=DEFAULT_CONFIG_FILE):\n self.config_file = config_file\n self.config = self.parse_config_file()\n\n def _handle_no_value(self, section, key, default):\n if default is self._NO_DEFAULT_SPECIFIED:\n msg = (\"Value '%s' not found in section '%s'\" % (key, section))\n raise SettingsError(msg)\n else:\n return default\n\n def get_section_values(self, sections):\n \"\"\"\n Return a config parser object containing a single section of the\n global configuration, that can be written to a file object.\n\n :param\n section: Tuple with sections we want to turn into a config\n parser\n :return: ConfigParser() onject containing all the contents of\n sections.\n \"\"\"\n self._ensure_config_parsed()\n\n if isinstance(sections, str):\n sections = [sections]\n cfgparser = ConfigParser.ConfigParser()\n for section in sections:\n cfgparser.add_section(section)\n for option, value in self.config.items(section):\n cfgparser.set(section, option, value)\n return cfgparser\n\n def get_value(self, section, key, type=str, default=_NO_DEFAULT_SPECIFIED,\n allow_blank=False):\n self._ensure_config_parsed()\n\n try:\n val = self.config.get(section, key)\n except ConfigParser.Error:\n return self._handle_no_value(section, key, default)\n\n if not val.strip() and not allow_blank:\n return self._handle_no_value(section, key, default)\n\n return self._convert_value(key, section, val, type)\n\n def override_value(self, section, key, new_value):\n \"\"\"\n Override a value from the config file with a new value.\n \"\"\"\n self._ensure_config_parsed()\n self.config.set(section, key, new_value)\n\n def reset_values(self):\n \"\"\"\n Reset all values to those found in the config files (undoes all\n overrides).\n \"\"\"\n self.parse_config_file()\n\n def _ensure_config_parsed(self):\n if self.config is None:\n self.parse_config_file()\n\n def merge_configs(self, shadow_config):\n # overwrite whats in config with whats in shadow_config\n sections = shadow_config.sections()\n for section in sections:\n # add the section if needed\n if not self.config.has_section(section):\n self.config.add_section(section)\n\n # now run through all options and set them\n options = shadow_config.options(section)\n for option in options:\n val = shadow_config.get(section, option)\n self.config.set(section, option, val)\n\n def parse_config_file(self):\n self.config = ConfigParser.ConfigParser()\n if self.config_file and os.path.exists(self.config_file):\n self.config.read(self.config_file)\n else:\n raise SettingsError('%s not found' % (self.config_file))\n\n # the values pulled from ini are strings\n # try to convert them to other types if needed.\n def _convert_value(self, key, section, value, value_type):\n sval = value.strip()\n\n if len(sval) == 0:\n if value_type == str:\n return\n elif value_type == bool:\n return False\n elif value_type == int:\n return 0\n elif value_type == float:\n return 0.0\n elif value_type == list:\n return []\n else:\n return None\n\n if value_type == bool:\n if sval.lower() == \"false\":\n return False\n else:\n return True\n\n if value_type == list:\n return [val.strip() for val in sval.split('.')]\n\n try:\n conv_val = value_type(sval)\n return conv_val\n except Exception:\n msg = (\"Could not convert %s value in section %s to type %s\" %\n (key, section, value_type))\n raise SettingsValueError(msg)\n\n def read_config(self):\n '''\n :return: tool list and run case list\n '''\n config_files = os.path.join(caliper_path.config_files.config_dir, 'cases_config.json')\n fp = open(config_files, 'r')\n tool_list = []\n run_case_list = []\n case_list = yaml.load(fp.read())\n for dimension in case_list:\n for i in range(len(case_list[dimension])):\n for tool in case_list[dimension][i]:\n for case in case_list[dimension][i][tool]:\n if case_list[dimension][i][tool][case][0] == 'enable':\n tool_list.append(tool)\n run_case_list.append(case)\n sections = list(set(tool_list))\n return sections, run_case_list\n\n def get_config(self, option):\n '''\n :return: tool list and run case list\n '''\n config_files = os.path.join(caliper_path.config_files.config_dir, 'cases_config.json')\n fp = open(config_files, 'r')\n tool_list = []\n run_case_list = []\n case_list = yaml.load(fp.read())\n dimension_list = case_list.keys()\n tool_dic = {}\n for key, value in case_list.items():\n for va in value:\n for toolkey, toolvalue in va.items():\n tool_dic[toolkey] = []\n for casekey, casevalue in toolvalue.items():\n tool_dic[toolkey].append(casekey)\n sections = []\n if option != 'all':\n if option in dimension_list:\n for i in range(len(case_list[option])):\n for tool in case_list[option][i]:\n for case in case_list[option][i][tool]:\n tool_list.append(tool)\n run_case_list.append(case)\n sections = list(set(tool_list))\n else:\n if option in tool_dic:\n sections.append(option)\n run_case_list = tool_dic[option]\n else:\n run_case_list.append(option)\n for tool in tool_dic:\n if option in tool_dic[tool]:\n sections.append(tool)\n else:\n sections, run_case_list = self.read_config()\n return sections, run_case_list\n\n def get_sections(self, dimension_list):\n all_sections = []\n config_files = os.path.join(caliper_path.config_files.config_dir, 'cases_config.json')\n fp = open(config_files, 'r')\n run_case_list = []\n case_list = yaml.load(fp.read())\n cf = ConfigParser.ConfigParser()\n cf.read(DEFAULT_CONFIG_FILE)\n devices = cf.options('FastTest')\n for device in devices:\n tool_list = yaml.load(cf.get('FastTest', device))\n all_sections = all_sections + tool_list\n sections = list(set(all_sections))\n for section in sections:\n for dimension in dimension_list:\n for i in range(len(case_list[dimension])):\n try:\n for case in case_list[dimension][i][section]:\n run_case_list.append(case)\n except:\n pass\n return sections, run_case_list\n\n def get_run_sections(self, c_option, dimension_list, option):\n if c_option == 1:\n sections, run_case_list = self.get_sections(dimension_list)\n else:\n if 'all' in option:\n sections, run_case_list = self.get_config('all')\n else:\n sections, run_case_list = self.get_config(option)\n return sections, run_case_list\n\n def push_ssh_key(self):\n '''\n use ansible push ssh key to test host\n :return: \n '''\n TEST_CASE_DIR = caliper_path.config_files.config_dir\n ssh_key_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa.pub')\n if not os.path.exists(ssh_key_path):\n os.system(\"ssh-keygen -t rsa -P '' -f '%s/.ssh/id_rsa'\" % os.environ['HOME'])\n try:\n logging.info('Begining to push ssh key for the test host')\n os.chdir(TEST_CASE_DIR)\n cf = ConfigParser.ConfigParser()\n cf.read(DEFAULT_CONFIG_FILE)\n sections = cf.sections()\n for section in sections:\n if 'Device' not in section:\n continue\n subprocess.call('ansible-playbook -i project_config.cfg push_sshkey.yml -e hosts=%s -u %s' % (\n section, getpass.getuser()), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n except Exception as e:\n logging.debug(e)\n logging.info('push ssh key fail')\n pass\n\n# insure the class is a singleton. Now the symbol settings will point to the\n# one and only one instance pof the class\nsettings = Settings()\n","sub_path":"server/shared/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":10256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"135076538","text":"# coding: utf-8\n\nimport ujson\n\nimport time\n\nfrom .utils import rd, signer\n\n\nclass FoodCache(object):\n\n KEY = \"foods:%s\"\n\n def __init__(self, backend):\n self.backend = backend\n self._load()\n\n def _load(self):\n # load from cache\n food_ids = self.backend.smembers(\"foods\")\n food_stocks = self.backend.mget(\n \"foods:stock:%s\" % i for i in food_ids)\n food_prices = self.backend.mget(\n \"foods:price:%s\" % i for i in food_ids)\n\n self.cached_foods = {\n int(i): {\"id\": int(i), \"stock\": int(s), \"price\": int(p)}\n for i, s, p in zip(food_ids, food_stocks, food_prices)}\n\n self.update_time = time.time()\n\n def __contains__(self, item):\n return item in self.cached_foods\n\n def get_food(self, food_id):\n return self.cached_foods[food_id]\n\n def get_all(self, timeout=10):\n if time.time() - self.update_time > timeout:\n self._load()\n return ujson.dumps(list(self.cached_foods.values()))\nfood_cache = FoodCache(rd)\n\n\nclass CartCache(object):\n\n KEY = \"carts:%s\"\n USER_KEY = \"carts:user:%s\"\n\n # KEYS = [cart_id]\n # ARGV = [*food_ids]\n # language=Lua\n LUA_ADD_FOOD = ' '.join(\"\"\"\n local cart_key = 'carts:' .. KEYS[1]\n local count = tonumber(redis.call('LLEN', cart_key))\n local patch = tonumber(table.getn(ARGV))\n if count + patch <= 3 then\n redis.call('LPUSH', cart_key, unpack(ARGV))\n return 0\n else\n return 1\n end\n \"\"\".split())\n\n def __init__(self, backend):\n self.backend = backend\n\n self.add_food = backend.register_script(self.LUA_ADD_FOOD)\n\n def get_cart(self, cart_id):\n cart_str = self.backend.get(self.KEY % cart_id, force=True)\n if cart_str:\n return ujson.loads(cart_str)\n\n def set_cart(self, user_id, cart):\n self.backend.sadd(self.USER_KEY % user_id, cart[\"id\"])\n self.backend.set(self.KEY % cart[\"id\"], ujson.dumps(cart), force=True)\n\n def patch_cart(self, cart_id, food_id, count):\n if count > 0:\n return self.add_food(keys=[cart_id],\n args=[str(food_id)] * count) == 0\n else:\n self.backend.lrem(self.KEY % cart_id, count, str(food_id))\n return True\ncart_cache = CartCache(rd)\n\n\nclass UserCache(object):\n\n KEY = \"users:%s\"\n TOKEN_KEY = \"token:%s\"\n\n def __init__(self, backend):\n self.backend = backend\n self._load()\n\n def _load(self):\n user_ids = self.backend.smembers(\"users\")\n with self.backend.pipeline() as p:\n for i in user_ids:\n p.hgetall(self.KEY % i)\n res = p.execute()\n\n self.auth_map = {\n u[\"name\"]: {\"id\": int(u[\"id\"]), \"password\": u[\"password\"]}\n for u in res}\n\n self.user_token = {int(i): signer.dumps(i) for i in user_ids}\n self.token_user = {k: v for v, k in self.user_token.items()}\n\n def login(self, username, password):\n if username in self.auth_map and \\\n self.auth_map[username][\"password\"] == password:\n user_id = self.auth_map[username][\"id\"]\n return user_id, self.user_token[user_id]\n else:\n return None, None\n\n def auth(self, token):\n return self.token_user.get(token)\nuser_cache = UserCache(rd)\n\n\nclass OrderCache(object):\n\n # language=Lua\n LUA_MAKE_ORDER = ' '.join(\"\"\"\n local cart_key = 'carts:' .. KEYS[2]\n local food_ids = redis.call('LRANGE', cart_key, 0, -1)\n if table.getn(food_ids) == 0 then\n return 1\n end\n\n for _, f in pairs(food_ids) do\n if tonumber(redis.call('GET', 'foods:stock:' .. f)) < 1 then\n return 2\n else\n redis.call('DECR', 'foods:stock:' .. f)\n end\n end\n\n local user_key = 'orders:user:' .. KEYS[1]\n local order_id = ARGV[1]\n redis.call('RENAME', cart_key, user_key)\n redis.call('LPUSH', user_key, order_id)\n return 0\n \"\"\".split())\n\n ORDER_KEY = \"orders:user:%s\"\n\n def __init__(self, backend):\n self.backend = backend\n\n self.make_order = backend.register_script(self.LUA_MAKE_ORDER)\n\n def get_order(self, user_id):\n return self.backend.lrange(self.ORDER_KEY % user_id, 0, -1)\n\n def is_new(self, user_id):\n return not self.backend.exists(self.ORDER_KEY % user_id)\n\n def get_all(self):\n order_keys = self.backend.keys(self.ORDER_KEY % '*')\n with self.backend.pipeline() as p:\n for k in order_keys:\n p.lrange(k, 0, -1)\n order_info = p.execute()\n return {int(k.split(':')[-1]): info\n for k, info in zip(order_keys, order_info)}\norder_cache = OrderCache(rd)\n","sub_path":"hackathon-py-lxyu/hackathon/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":4762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"515644408","text":"import random\n\nfrom templates.text import TextTemplate\n\n\ndef process(input, entities=None):\n greetings = [\n 'Salutations! Enter a command, user!',\n 'Yes? Tell me to do something, user.',\n 'Hello! How can I be of service?',\n 'At your service, user.',\n 'Oh hello, user!',\n 'Jarvis, reporting in. How can I help you today, user?',\n ]\n if entities is not None:\n if 'sender' in entities and 'first_name' in entities['sender']:\n sender_name = entities['sender']['first_name']\n greetings = [greeting.replace('user', sender_name) for greeting in greetings]\n output = {\n 'input': input,\n 'output': TextTemplate(random.choice(greetings)).get_message(),\n 'success': True\n }\n return output\n","sub_path":"modules/src/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"382458523","text":"from os import listdir\nfrom os.path import isfile, join\nimport numpy as np\n\nnp.set_printoptions(suppress=True)\n\ndataset_path = \"./SurveyLogs/\" # Keep trailing /\ndestination_path = \"./SFBased/\" # Keep trailing /\nfiles = [f for f in listdir(dataset_path) if isfile(join(dataset_path, f))]\nnumTxPkts = 30.\n\n\ndef splitSpread():\n for fl in files:\n with open(dataset_path+fl, 'r') as log_file:\n logs = log_file.readlines()\n name = logs[1].split(\",\")[0]\n lat = logs[1].split(\",\")[1]\n lon = logs[1].split(\",\")[2][:-1]\n for row in logs[4:]:\n new_row = row[:-1] + \",\" + name + \",\" + lat + \",\" + lon + \"\\n\"\n sf = row.split(\",\")[2]\n with open(sf+\".csv\", \"a\") as f:\n f.write(new_row)\n \n \ndef splitGeoCombine():\n for fl in files:\n sfbin = {} \n #print(\"\\n\\n File, \" + fl)\n with open(dataset_path+fl, 'r') as log_file:\n logs = log_file.readlines()\n lat = logs[1].split(\",\")[1]\n lon = logs[1].split(\",\")[2][:-1]\n\n for row in logs[4:]:\n row = row.strip(\"\\n\").split(\",\")\n sf = row[2]\n if sf in sfbin.keys() :\n sfbin[sf] = np.concatenate((sfbin[sf], np.array([[float(row[0]), float(row[1])]])), axis=0)\n else:\n sfbin[sf] = np.array([[float(row[0]), float(row[1])]])\n for sf in sfbin:\n rowStat = lat + \",\" + lon + \",\" + sf + \",\" + str(np.average(sfbin[sf][:,0])) + \",\" + str(np.average(sfbin[sf][:,1])) + \",\" + str(int(100*(numTxPkts-len(sfbin[sf]))/numTxPkts)) + \"\\n\"\n with open(destination_path+sf+\".csv\", \"a\") as f:\n f.write(rowStat)\n notEmptyFLag = 0\n\n\n\ndef main():\n splitGeoCombine()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"datasets/combine.py","file_name":"combine.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"211436026","text":"import socket\nimport os\nimport struct\nimport hashlib\nimport time\n\nserverIP = '10.0.2.15'\nserverPort = 3333\n\nclnt_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nclnt_sock.settimeout(3)\nprint(\"Sender Socket open...\")\nprint(\"Receiver IP = \", serverIP)\nprint(\"Receiver Port = \", serverPort)\n\nre_fileName = input(\"Input File Name : \")\nwhile os.path.exists(re_fileName) == 0:\n\tprint(\"No files found.\")\n\tre_fileName = input(\"Input File Name : \")\nfilePath = os.path.abspath(re_fileName) # file path\nre_fileSize = os.path.getsize(filePath) # file size\nfileName = re_fileName.encode()\t# byte file name\nfileSize = re_fileSize.to_bytes(4, byteorder = \"big\") # byte file size\n\nseqN = 0b0000\ntmpseqN = 0\nACK = 0b0000\ntmpACK = 0\nseqN = seqN << 4\nACK = ACK & 0b1111\nbNum = (seqN|ACK).to_bytes(1, byteorder =\"big\")\n\nh = hashlib.sha1()\nh.update(bNum + fileName + fileSize)\nmessage = h.digest() + bNum + fileName + fileSize # 36byte\nclnt_sock.sendto(message, (serverIP, serverPort)) # message info send\n\ncount = 0\ncurrentSize = 0\nflag = 0 # 초기상태\nbase = 0\nwindowSize = 4\nwindow = []\n\ndata, addr = clnt_sock.recvfrom(1)\nchk = struct.unpack(\"!b\", data[0:1])[0]\nif chk == 0:\n\tprint(\"정상\")\n\nfile = open(\"./\"+re_fileName, \"rb\")\nprint(\"Send File Info(file Name, file Size, seqNum) to Server...\")\nprint(\"Start File Send\")\n\nwhile True:\n\ttry:\n\t\tif currentSize == re_fileSize and len(window) == 0:\n\t\t\tbreak\t\t\n\t\t\n\t\tNAK = 0\n\t\tif currentSize !=0:\n\t\t\trecvData,addr = clnt_sock.recvfrom(1)\n\t\t\ttmpseqN = struct.unpack(\"!b\", recvData[0:1])[0]&0b11110000\n\t\t\ttmpACK = struct.unpack(\"!b\", recvData[0:1])[0]&0b1111\n\t\t\tif tmpACK == 15 and NAK == 0: # NAK 받았을때\n\t\t\t\tfor i in range(len(window)):\n\t\t\t\t\tcurrentSize = currentSize - len(window[i][21:])\n\t\t\t\tprint(\"* Received NAK - Retransmit!\")\n\t\t\t\tfor i in range(len(window)):\n\t\t\t\t\tclnt_sock.sendto(window[i], addr)\n\t\t\t\t\tcurrentSize = currentSize + len(window[i][21:])\n\t\t\t\t\tprint(\"Retransmission : (current size / total size ) = \", currentSize,\"/\",re_fileSize,\" , \",round((currentSize/re_fileSize)*100, 3),\"%\")\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\tfor i in range(len(window)):\n\t\t\t\tif struct.unpack(\"!b\", window[i][20:21])[0]>>4 == tmpACK: #[0][1][받은 ACK가 있는 window][3]일때, [0][1][2] 처리\n\t\t\t\t\tfor j in range(0, i+1):\n\t\t\t\t\t\twindow.pop(0)\n\t\t\t\t\t\tbase = base -1\n\t\t\t\t\tflag = 3 #받은 ACK를 정상적으로 처리한 경우\n\t\t\t\t\tbreak\n\n\t\t\tif flag == 2:\t#flagr가 3이 아닐경우 ACK가 정상적으로 처리되지 않은 경우\n\t\t\t\tprint(\"Data retransmission!\")\n\t\t\t\tfor i in range(len(window)): # for문에 온 경우는 sender에서 보낸 data가 손실된 경우이다. window의 data를 재전송한다.\n\t\t\t\t\tclnt_sock.sendto(window[i], addr)\n\t\t\tflag = 2\n\t\n\t\t\t\n\t\tif count == 283: # 바이트 조작\n\t\t\tdata = file.read(1024)\n\t\t\tif len(data) != 0:\n\t\t\t\tbase = base+1\n\t\t\tif seqN == 8:\n\t\t\t\tseqN = 0b0000\n\t\t\t\tACK = 0b0000\n\t\t\tsendData = ((seqN<<4)|(ACK&0b1111)).to_bytes(1,\"big\") + data\n\t\t\th = hashlib.sha1()\n\t\t\th.update(sendData)\n\t\t\tmessage = h.digest() + sendData\n\t\t\twindow.append(message)\n\t\t\tcurrentSize = currentSize + len(data)\n\t\t\tvar = \"var\"\n\t\t\ttemp = message + var.encode()\n\t\t\tclnt_sock.sendto(temp, addr)\n\t\t\tprint(\"(current size / total size) = \", currentSize,\"/\",re_fileSize,\" , \",round((currentSize/re_fileSize)*100, 3), \"%\")\n\t\t\tseqN = seqN +1\n\t\t\tACK = ACK +1\n\t\t\tflag = 2 # 바이트 조작\n\t\t\tcount = count+1\n\t\t\t\t\n\n\t\tif flag == 0: # 처음 data 4개(windsize)만큼 전송, 이후에 사용x\n\t\t\tfor i in range(0, windowSize):\n\t\t\t\tbase = i + 1\n\t\t\t\tdata = file.read(1024)\n\t\t\t\tsendData = ((seqN<<4)|(ACK&0b1111)).to_bytes(1,\"big\") + data\n\t\t\t\th = hashlib.sha1()\n\t\t\t\th.update(sendData)\n\t\t\t\tmessage = h.digest() + sendData\n\t\t\t\tclnt_sock.sendto(message, addr)\n\t\t\t\tcurrentSize = currentSize + len(data)\n\t\t\t\tprint(\"(current size / total size) = \", currentSize,\"/\",re_fileSize,\" , \",round((currentSize/re_fileSize)*100, 3), \"%\")\n\t\t\t\twindow.append(message)\n\t\t\t\tseqN = seqN +1\n\t\t\t\tACK = ACK + 1\n\t\t\t\tcount = count+1\n\t\t\n\t\tflag = flag +1 #초기상태 벗어난 상태)\n\t\n\n\t\twhile flag != 0 and base < windowSize and currentSize < re_fileSize:\n\t\t\tdata = file.read(1024)\n\t\t\tif len(data) !=0:\n\t\t\t\tbase = base +1\n\t\t\tif seqN == 8:\n\t\t\t\tseqN = 0b0000\n\t\t\t\tACK = 0b0000\n\t\t\tsendData = ((seqN<<4)|(ACK&0b1111)).to_bytes(1,\"big\") + data\n\t\t\th = hashlib.sha1()\n\t\t\th.update(sendData)\n\t\t\tmessage = h.digest() + sendData\n\t\t\tclnt_sock.sendto(message, addr)\n\t\t\tcurrentSize = currentSize + len(data)\n\t\t\tprint(\"(current size / total size) = \", currentSize,\"/\",re_fileSize,\" , \",round((currentSize/re_fileSize)*100, 3),\"%\")\n\t\t\twindow.append(message)\n\t\t\tseqN = seqN +1\n\t\t\tACK = ACK +1\n\t\t\tcount = count+1\n\n\n\texcept socket.timeout:\n\t\tprint(\"* TimeOut!! ***\")\n\t\tfor i in range(len(window)):\n\t\t\tcurrentSize = currentSize - len(window[i][21:])\n\t\tfor i in range(len(window)):\n\t\t\tclnt_sock.sendto(window[i], addr)\n\t\t\tcurrentSize = currentSize + len(window[i][21:])\n\t\t\tprint(\"Retransmission : (current size / total size) = \", currentSize,\"/\",re_fileSize,\" , \",round((currentSize/re_fileSize)*100, 3), \"%\")\n\t\tcontinue\n\nprint(\"File Send End.\")\nfile.close()\nclnt_sock.close()\n\n","sub_path":"2018/Data Communications/DC_201402448_한진영_10/sender/201402448_sender.py","file_name":"201402448_sender.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"148569116","text":"'''\nInput:\n2\n20 20\n4 5\n13\nLLUUUUURRRRRR\n10 10\n3 4\n7\nUDUDDRR\n'''\nfor _ in range(int(input())):\n m, n = [int(x) for x in input().split()]\n rx, ry = [int(x) for x in input().split()]\n nom = int(input())\n moves= input()\n dx = moves.count(\"L\")*-1 + moves.count(\"R\")\n dy = moves.count(\"U\") + moves.count(\"D\")*-1\n\n if dx == rx and dy == ry:\n print(\"REACHED\")\n elif dx < 0 or dx > m or dy < 0 or dy > n:\n print(\"DANGER\")\n else:\n print(\"SOMEWHERE\")\n\n","sub_path":"codechef/JReachedSafelyOrNot.py","file_name":"JReachedSafelyOrNot.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"404914174","text":"# 909. 蛇梯棋\n\nclass Solution:\n def snakesAndLadders(self, board: list[list[int]]) -> int:\n # 转成一维数组\n arr = [0]\n row = 0\n for i in range(len(board)-1, -1, -1):\n if row & 1 == 0:\n for j in range(len(board[0])):\n arr.append(board[i][j])\n else:\n for j in range(len(board[0])-1, -1, -1):\n arr.append(board[i][j])\n row += 1\n queue = [1]\n visit = set([1])\n target = len(arr)-1\n res = 0\n while queue:\n temp = []\n for i in queue:\n for j in range(1, 7):\n pos = i + j\n if pos == target:\n return res + 1\n elif pos > target:\n continue\n if pos not in visit:\n if arr[pos] == target:\n return res + 1\n if arr[pos] != -1:\n temp.append(arr[pos])\n else:\n temp.append(pos)\n visit.add(pos)\n queue = temp\n res += 1\n return -1\n\n\nif __name__ == '__main__':\n print(Solution().snakesAndLadders([[-1,-1,19,10,-1],[2,-1,-1,6,-1],[-1,17,-1,19,-1],[25,-1,20,-1,-1],[-1,-1,-1,-1,15]]))\n print(Solution().snakesAndLadders([[-1,-1,-1],[-1,9,8],[-1,8,9]]))\n","sub_path":"answers/snakesAndLadders.py","file_name":"snakesAndLadders.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"627424880","text":"\nversion = '0.0.5'\n__description__ = \"\"\"\n mclust for multi-resolution clustering\n\"\"\"\n\n__doc__ = __doc__ \n__version__ = version\n__author__ = [\"Gholamali Rahnavard\"]\n__contact__ = \"gholamali.rahnavard@gmail.com\"\n\n\nkeys_attribute = [\"__description__\", \"__version__\", \"__author__\", \"__contact__\", \"clustering\", \"multi-resolution\"]\n\n# default Parameters\nsimilarity_method = 'spearman'\ndiatance_metric = 'spearman' #euclidean'\ndata = None\nmetadata = None\nresolution = 'low'\noutput_dir = 'mclust_output'\nestimated_number_of_clusters = 2\nlinkage_method = 'average'\nplot = False\nsize_to_plot = 3\n\n#output directort\noutput_dir = './'","sub_path":"mclust/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"602424693","text":"from django import forms\r\n\r\nfrom crispy_forms.helper import FormHelper\r\nfrom crispy_forms.layout import Submit, Layout, Field\r\nfrom crispy_forms.bootstrap import (\r\n PrependedText, PrependedAppendedText, FormActions)\r\n\r\n\r\nfrom .models import Paciente, Institucion, Examen\r\n\r\nclass PacienteModForm(forms.ModelForm):\r\n\r\n class Meta:\r\n model = Paciente\r\n fields = '__all__'\r\n #fields = (\r\n #\t'nombre', 'apellidos', 'institucion', 'f_nac', 'sexo', 'domicilio', 'tel',\r\n #\t'ci', 'seguro', 'procedencia', 'ocupacion', 'ec', 'enfermedad', 'sintomas',\r\n #\t'signos', 'sindromes', 'a_personales', 'a_patologicos', 'a_nopatologicos',\r\n #\t'a_hereditarios', 'a_presuntivo', 'd_definitivo', 'interconsulta'\r\n #)\r\n\r\nclass InstitucionModForm(forms.ModelForm):\r\n\r\n\t\tclass Meta:\r\n\t\t\tmodel = Institucion\r\n\t\t\tfields = '__all__'\r\n\r\n\r\nclass ExamenModForm(forms.ModelForm):\r\n\r\n class Meta:\r\n model = Examen\r\n fields = '__all__'\r\n\r\nExamenFormset = forms.modelformset_factory(Examen, form=ExamenModForm, can_delete=True)\r\n","sub_path":"cineantro/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"448232438","text":"#------coding=utf-8--*---\n\nfrom urllib import request\nimport re\nimport os\nimport sys\nimport zipfile\nkeyword=sys.argv[1]\nprint(keyword)\nurl0=\"http://www.offensivecomputing.net/search.cgi?search=\"\nurl=url0+keyword\nurl1=\"http://www.offensivecomputing.net/\"\nprint(\"password = infected\")\nRequest =request.urlopen(url)\nresult = Request.read()\nmainhtml=keyword+\".html\"\nwith open(mainhtml,\"wb\") as fmain:\n fmain.write(result)\nresult = result.decode('utf-8')\nreg=r'Download Sample'\npattern = re.compile(reg)\ninfoList=pattern.findall(result)\nfor info in infoList:\n print(info)\n NowUrl=url1+info\n exefile=request.urlopen(NowUrl).read()\n regNow=r'id=(.*?)&auth'\n patternNow = re.compile(regNow)\n nameList = patternNow.findall(info)\n name = keyword+\"_\"+nameList[0] + \".zip\"\n with open(name,\"wb\") as f:\n f.write(exefile)\nprint(\"OK\")\n","sub_path":"python/恶意代码历代/mal428.py","file_name":"mal428.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"36046087","text":"#!/usr/bin/python\n# -*- codding: utf-8 -*-\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom common.execute_command import write_one_parameter\n\n# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/disable-insight-rules.html\nif __name__ == '__main__':\n \"\"\"\n\tdelete-insight-rules : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/delete-insight-rules.html\n\tdescribe-insight-rules : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/describe-insight-rules.html\n\tenable-insight-rules : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/enable-insight-rules.html\n\tput-insight-rule : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-insight-rule.html\n \"\"\"\n\n parameter_display_string = \"\"\"\n # rule-names : An array of the rule names to disable. If you need to find out the names of your rules, use DescribeInsightRules .\n(string)\n \"\"\"\n add_option_dict = {}\n\n #######################################################################\n # parameter display string\n add_option_dict[\"parameter_display_string\"] = parameter_display_string\n # ex: add_option_dict[\"no_value_parameter_list\"] = \"--single-parameter\"\n write_one_parameter(\"cloudwatch\", \"disable-insight-rules\", \"rule-names\", add_option_dict)\n\n\n\n\n\n","sub_path":"cloudwatch_write_1/insight-rule_disable.py","file_name":"insight-rule_disable.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"388972435","text":"import os\nimport re\nimport logging\nimport platform\nimport subprocess\n\nfrom distutils.version import LooseVersion\nfrom mcutk.apps.decorators import build\nfrom mcutk.apps.idebase import IDEBase, BuildResult\nfrom mcutk.elftool import transform_elf_basic\nfrom mcutk.apps.cmake import generate_build_cmdline\n\n\nclass APP(IDEBase):\n \"\"\"GNU ARM GCC compiler.\n\n CMake and ARM-GCC build explanation:\n - Generate Makefile:\n >>> cmake -DCMAKE_TOOLCHAIN_FILE={path}/armgcc.cmake -G \"{MinGW|Unix} Makefiles\" -DCMAKE_BUILD_TYPE=debug\n\n - Start build with make tool or mingw32-make:\n >>> make -C \"\" -j4\n >>> mingw32-make -C \"\" -j4\n\n - Compile. Armgcc compiler will be called to compile in makefile.\n\n CMake is a cross-platform build system generator. Projects specify their build\n process with platform-independent CMake listfiles included in each directory\n of a source tree with the name CMakeLists.txt. Users build a project by using\n CMake to generate a build system for a native tool on their platform.\n\n GNU Make is a tool which controls the generation of executables and other non-source\n files of a program from the program's source files. Make gets its knowledge of how to\n build your program from a file called the makefile, which lists each of the non-source\n files and how to compute it from other files. When you write a program, you should\n write a makefile for it, so that it is possible to use Make to build and install the\n program.\n\n\n \"\"\"\n\n OSLIST = [\"Windows\", \"Linux\", \"Darwin\"]\n\n\n @property\n def is_ready(self):\n return os.path.exists(self.path)\n\n @build\n def build_project(self, project, target, logfile, **kwargs):\n \"\"\"Return a command line string for armgcc. The build commands\n are packaging into a shell/bat script.\n\n Arguments:\n project {armgcc.Project} -- armgcc project object\n target {string} -- target name\n logfile {string} -- log file path\n\n Returns:\n string -- commandline string.\n \"\"\"\n os.environ[\"ARMGCC_DIR\"] = self.path\n return generate_build_cmdline(project, target, logfile)\n\n def transform_elf(self, type, in_file, out_file):\n \"\"\"Convert ELF to specific type.\n Called /bin/arm-none-eabi-objcopy to do the job.\n\n Supported types: bin, ihex, srec.\n\n Arguments:\n in_file {str} -- path to elf file.\n out_file {str} -- output file\n type {str} -- which type you want to convert.\n\n Raises:\n ReadElfError -- Unknown elf format will raise such error\n Exception -- Convert failed will raise exception\n\n Returns:\n bool\n \"\"\"\n executor = os.path.join(self.path, 'bin/arm-none-eabi-objcopy')\n if os.name == 'nt':\n executor += '.exe'\n\n return transform_elf_basic(type, in_file, out_file, executor)\n\n @staticmethod\n def verify(path):\n '''\n verify the path of compiler is avaliable\n '''\n return os.path.exists(path)\n\n @staticmethod\n def get_latest():\n \"\"\"Search and return a latest armgcc instance from system.\n\n Returns:\n \n \"\"\"\n path, version = get_armgcc_latest()\n if path:\n return APP(path, version=version)\n else:\n return None\n\n @staticmethod\n def parse_build_result(exitcode, logfile):\n \"\"\"GNU make exits with a status of zero if all makefiles were successfully\n parsed and no targets that were built failed. A status of one will be\n returned if the -q flag was used and make determines that a target\n needs to be rebuilt. A status of two will be returned if any errors\n were encountered.\n \"\"\"\n\n if exitcode != 0:\n return BuildResult.map(\"error\")\n\n if not logfile:\n return BuildResult.map(\"pass\")\n\n p = re.compile(r'warning:', re.I)\n\n with open(logfile) as f:\n for line in f:\n if p.search(line) != None:\n return BuildResult.map(\"warning\")\n\n return BuildResult.map(\"pass\")\n\n\n @staticmethod\n def default_install_path():\n default_path_table = {\n \"Windows\": \"C:/Program Files (x86)/GNU Tools ARM Embedded\",\n \"Linux\": \"/usr/local\",\n \"Darwin\": \"/usr/local\",\n }\n osname = platform.system()\n return default_path_table[osname]\n\ndef _scan_windows_register():\n try:\n import _winreg as winreg\n except ImportError:\n import winreg\n\n root_key_path = r\"SOFTWARE\\\\Wow6432Node\\\\ARM\\\\GNU Tools for ARM Embedded Processors\"\n try:\n key_object = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, root_key_path)\n path = winreg.QueryValueEx(key_object, \"InstallFolder\")[0].replace('\\\\', '/')\n version = path.split(\"/\")[-1].replace(\" \", \"-\")\n winreg.CloseKey(key_object)\n return path, version\n except WindowsError:\n pass\n\n return None, None\n\ndef get_armgcc_latest():\n \"\"\"Get the latest armgcc version\n\n Returns:\n tuple -- (path, version)\n \"\"\"\n path, version = None, None\n osname = platform.system()\n\n if osname == \"Windows\":\n path, version = _scan_windows_register()\n if path:\n return path, version\n\n logging.debug(\"Could not found ARM GCC installation in windows register!\"\\\n \"Trying to scan in default installation directory!\")\n\n root_path = APP.default_install_path()\n if not os.path.exists(root_path):\n return None, None\n\n if osname == \"Windows\" and not os.path.exists(root_path):\n root_path = \"C:/Program Files/GNU Tools ARM Embedded\"\n\n return get_armgcc_latest_version(root_path)\n\n\ndef get_armgcc_latest_version(rootpath):\n osname = platform.system()\n versions_dict = {}\n armgcc_rootfolders = []\n\n if \"Windows\" == osname:\n armgcc_rootfolders = os.listdir(rootpath)\n else:\n try:\n s = subprocess.check_output(\"ls {0} | grep gcc-arm-none-eabi\".format(rootpath), shell=True)\n armgcc_rootfolders = s.split('\\n')\n except subprocess.CalledProcessError:\n return None, None\n\n for per_folder in armgcc_rootfolders:\n if not os.path.isdir(os.path.join(rootpath, per_folder)) or '' == per_folder:\n continue\n\n version_content = os.popen(\"\\\"{}\\\" --version\".format(os.path.join(rootpath, per_folder, \"bin\", \"arm-none-eabi-gcc\"))).read()\n ret = re.search(r\"\\d\\.\\d\\.\\d\", version_content)\n if None != ret:\n versions_dict[ret.group()] = os.path.join(rootpath, per_folder)\n\n latest_v = sorted(versions_dict.keys(), key=lambda v:LooseVersion(v))[-1]\n return versions_dict[latest_v], latest_v\n","sub_path":"mcutk/apps/armgcc/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"69560640","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport random\nimport sys\nimport numpy as np\nfrom rl.core import Env\nfrom rl.core import Space\n\n# check up the environment, import python modules from $SUMO_HOME/tools directory\nif 'SUMO_HOME' in os.environ:\n tools = os.path.join(os.environ['SUMO_HOME'], 'tools')\n sys.path.append(tools)\nelse:\n sys.exit(\"please declare environment variable 'SUMO_HOME' after installing sumo!\")\n\n# import python modules from sumo\nfrom sumolib import checkBinary\nimport traci\nimport traci.constants as tc\n\n\nclass SumoEnv(Env):\n \"\"\"sumo environment definition, extend rl.core.Env\"\"\"\n def __init__(self, cfg_file, route_file, router=None, observed_prob=1.0, nogui=False, log_out=\"log/inter\"):\n self.cfg_file = cfg_file\n self.route_file = route_file\n self.router = router\n if not self.router:\n self.generate_route_file()\n else:\n self.router.generate_route_file(self.route_file)\n\n self.observable_probability = observed_prob\n self.observable_id = set()\n self.rix = [0, 2, 1, 3]\n\n if nogui:\n self.sumoBinary = checkBinary('sumo')\n self.cmd_lines = [self.sumoBinary, \"--start\", \"-c\", self.cfg_file]\n self.load_cmd = [\"--start\", \"-c\", self.cfg_file]\n else:\n self.sumoBinary = checkBinary('sumo-gui')\n # --start, --quit-on-end\n self.cmd_lines = [self.sumoBinary, \"-c\", self.cfg_file]\n self.load_cmd = [\"-c\", self.cfg_file]\n\n self.log_out = log_out\n if not os.path.exists(log_out):\n os.makedirs(log_out)\n\n self.log_file = os.path.join(log_out, 'metrics.log')\n self.phases_file = os.path.join(log_out, 'phases.log')\n\n # constants\n self.road_length = 500 # m\n self.margin = 14.65 # m\n self.max_speed = 16.67 # m/s\n\n # divide each lane into 32 cell\n self.length = 256\n self.eps = 2\n self.veh_length = 5 # m\n self.cell_length = 16 # m\n self.max_n = 8.0\n self.n_lanes = 4\n self.n_sects = 4\n self.region = self.length + self.margin - self.eps\n self.height = self.length // self.cell_length\n self.width = self.n_sects\n self.index2green_phases = [0, 2, 4, 6]\n self.green_phases2index = {0: 0, 2: 1, 4: 2, 6: 3}\n self.phases_length = 8\n self.max_green_time = 60 # s\n self.min_green_time = 6 # s\n self.action_space = PhasesSpace()\n # max_simulation_time, ms\n self.max_sim_time = 3600000\n\n # the value need to be reset in reset()\n self.epoch_num = 0\n self.n_decision_step = 0\n self.cycle = 0\n self.phase_line = []\n self.observable_id = set()\n self.arrived_num = 0\n self.total_waiting_time = 0\n self.last_jam_vl = 0\n self.last_green_time = 0\n\n # this is the normal way of using traci. sumo is started as a\n # subprocess and then the python script connects and runs\n traci.start(self.cmd_lines)\n # context subscriptions, subscribe vehicles near the intersection\n traci.junction.subscribeContext(\"0\", tc.CMD_GET_VEHICLE_VARIABLE, self.region,\n [tc.VAR_LANE_ID, tc.VAR_ROAD_ID,\n tc.VAR_WAITING_TIME, tc.VAR_LANEPOSITION,\n tc.VAR_SPEED])\n\n def step(self, action):\n # definition = traci.trafficlight.getCompleteRedYellowGreenDefinition('tlstatic')\n self.n_decision_step += 1\n current_phase = traci.trafficlight.getPhase('tlstatic')\n current_index = self.green_phases2index[current_phase] # type: int\n next_phase = self.index2green_phases[(action + current_index) % len(self.index2green_phases)]\n if next_phase == current_phase:\n # current phase continues 2s\n traci.trafficlight.setPhase('tlstatic', current_phase)\n _ = self.simulate_one_step()\n flag = self.simulate_one_step()\n\n self.last_green_time += 2\n\n if self.last_green_time >= self.max_green_time:\n next_phase = self.index2green_phases[(current_index + 1)\n % len(self.index2green_phases)]\n flag = self.change2phase(current_phase, next_phase)\n else:\n flag = self.change2phase(current_phase, next_phase)\n\n cx_res = traci.junction.getContextSubscriptionResults(\"0\")\n obs = self.get_observations(cx_res)\n # remain modification\n reward = self.get_reward(cx_res)\n\n # if traci.simulation.getCurrentTime() > self.max_sim_time: # ms\n # print(\"MinExpected Number: %d\" % traci.simulation.getMinExpectedNumber())\n if not flag:\n with open(self.log_file, 'a') as log:\n # write sim time /t arrived num /t aver waiting time /n\n log.write('epoch: %d, time_step: %d, decision_step: %d, arrived_num: %d, awt: %.4f\\n' %\n (self.epoch_num, traci.simulation.getCurrentTime(), self.n_decision_step,\n self.arrived_num, float(self.total_waiting_time) / float(self.arrived_num)))\n # returns a tuple (observation, reward, done, info). \"Done\" indicates whether the simulation has end.\n self.epoch_num += 1\n return obs, reward, True, {}\n else:\n return obs, reward, False, {}\n\n def change2phase(self, current_phase, next_phase):\n \"\"\"shift the current green phase to next green phase, with min duration time 6s\n if current_phase == next_phase, reset the current_phase\"\"\"\n if current_phase == next_phase:\n traci.trafficlight.setPhase('tlstatic', current_phase)\n return True\n traci.trafficlight.setPhase('tlstatic', (current_phase + 1) % self.phases_length)\n if current_phase == 0:\n self.phase_line = ['epoch: %d, cycle: %d, green_phase: %d'\n % (self.epoch_num, self.cycle, self.last_green_time)]\n elif current_phase == 6:\n self.phase_line.append(str(self.last_green_time))\n with open(self.phases_file, 'a') as ph_file:\n if len(self.phase_line) == len(self.index2green_phases):\n ph_file.write(','.join(self.phase_line) + '\\n')\n self.cycle += 1\n else:\n self.phase_line.append(str(self.last_green_time))\n self.last_green_time = 0\n # reset the traffic lights to the action green phases\n while self.last_green_time < self.min_green_time: # min duration time 6s\n flag = self.simulate_one_step()\n if not flag:\n return False\n if traci.trafficlight.getPhase('tlstatic') == next_phase:\n self.last_green_time += 1\n else:\n self.last_green_time = 0\n return True\n\n def simulate_one_step(self):\n if traci.simulation.getMinExpectedNumber() > 0:\n traci.simulationStep()\n for i in range(1, self.n_sects + 1):\n for j in range(0, self.n_lanes):\n det = 'e2det_{}i_{}'.format(i, j)\n self.total_waiting_time += traci.lanearea.getLastStepHaltingNumber(det)\n\n self.arrived_num += traci.simulation.getArrivedNumber()\n id_list = traci.simulation.getDepartedIDList()\n for ix in id_list:\n if (ix not in self.observable_id) and random.uniform(0, 1) < self.observable_probability:\n self.observable_id.add(ix)\n aid_list = traci.simulation.getArrivedIDList()\n for aid in aid_list:\n if aid in self.observable_id:\n self.observable_id.remove(aid)\n return True\n else:\n return False\n\n def get_observations(self, cx_res):\n \"\"\"get vehicle position and speed matrix from context subscription, plus the current phase as one hot vector\"\"\"\n current_phase = traci.trafficlight.getPhase('tlstatic')\n if current_phase not in self.green_phases2index:\n current_index = random.randint(0, len(self.index2green_phases) - 1)\n else:\n current_index = self.green_phases2index[current_phase]\n phase = np.zeros(len(self.index2green_phases))\n phase[current_index] = 1\n position = np.zeros((self.height, self.width))\n speed = np.zeros((self.height, self.width))\n if not cx_res:\n return np.array([position, speed, phase])\n for vid, mes in cx_res.iteritems():\n if (vid in self.observable_id) and mes[tc.VAR_LANE_ID].__contains__('i'):\n rid, lid = [int(x) for x in mes[tc.VAR_LANE_ID].split('i_')]\n cid = int((self.road_length - self.margin - mes[tc.VAR_LANEPOSITION]) / self.cell_length)\n assert cid >= 0\n assert cid < self.height\n ix = self.rix[rid - 1]\n position[cid][ix] += 1\n speed[cid][ix] = speed[cid][ix] + (mes[tc.VAR_SPEED] - speed[cid][ix]) / position[cid][ix]\n position /= self.max_n\n speed /= self.max_speed\n return np.array([position, speed, phase])\n\n def get_reward(self, cx_res):\n \"\"\"get change of the total queuing vehicle number between two state as reward.\"\"\"\n if not cx_res:\n reward = self.last_jam_vl\n self.last_jam_vl = 0\n return reward\n jam_vl = 0\n for i in range(1, self.n_sects + 1):\n for j in range(0, self.n_lanes):\n det = 'e2det_{}i_{}'.format(i, j)\n jam_vl += traci.lanearea.getJamLengthVehicle(det)\n reward = self.last_jam_vl - jam_vl\n self.last_jam_vl = jam_vl\n return reward\n\n def reset(self):\n # context subscriptions\n # traci.close(wait=True)\n # Reset before simulationOneStep\n self.clear_metrics()\n if not self.router:\n self.generate_route_file()\n else:\n self.router.generate_route_file(self.route_file)\n\n # traci.start(self.cmd_lines)\n traci.load(self.load_cmd)\n traci.junction.subscribeContext(\"0\", traci.constants.CMD_GET_VEHICLE_VARIABLE, self.region,\n [traci.constants.VAR_LANE_ID, traci.constants.VAR_ROAD_ID,\n traci.constants.VAR_WAITING_TIME, traci.constants.VAR_LANEPOSITION,\n traci.constants.VAR_SPEED])\n # reset the traffic lights to the action green phases\n while self.last_green_time < self.min_green_time:\n self.simulate_one_step()\n if traci.trafficlight.getPhase('tlstatic') in self.green_phases2index:\n self.last_green_time += 1\n else:\n self.last_green_time = 0\n cx_res = traci.junction.getContextSubscriptionResults(\"0\")\n return self.get_observations(cx_res)\n\n def clear_metrics(self):\n self.n_decision_step = 0\n self.cycle = 0\n self.phase_line = []\n self.observable_id = set()\n self.arrived_num = 0\n self.total_waiting_time = 0\n self.last_jam_vl = 0\n self.last_green_time = 0\n\n def close(self):\n traci.close(wait=True)\n self.epoch_num = 0\n self.clear_metrics()\n\n def generate_route_file(self, pns=1.0/4.0, pew=1.0/8.0, psn=1.0/4.0, pwe=1.0/8.0, plt=1.0/4.0, prt=1.0/4.0):\n num_time_step = 3600 # number of time steps\n routes = [{'route': 'n2s', 'prob': pns},\n {'route': 'n2e', 'prob': pns*plt},\n {'route': 'n2w', 'prob': pns*prt},\n {'route': 'e2w', 'prob': pew},\n {'route': 'e2s', 'prob': pew*plt},\n {'route': 'e2n', 'prob': pew*prt},\n {'route': 's2n', 'prob': psn},\n {'route': 's2w', 'prob': psn*plt},\n {'route': 's2e', 'prob': psn*prt},\n {'route': 'w2e', 'prob': pwe},\n {'route': 'w2n', 'prob': pwe*plt},\n {'route': 'w2s', 'prob': pwe*prt}]\n\n head = ['',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '']\n\n tail = \"\"\n\n # print(\"pns: %.2f, pew: %.2f, psn: %.2f, pwe: %.2f, plt: %.2f, prt: %.2f\" % (pns, pew, psn, pwe, plt, prt))\n with open(self.route_file, \"w\") as output_file:\n print(os.linesep.join(head), file=output_file)\n cur_veh = 0\n for i in range(num_time_step):\n for route in routes:\n if random.uniform(0, 1) < route['prob']:\n print('' % (route['route'], cur_veh, 'stdSKVehicle',\n route['route'], i), file=output_file)\n cur_veh += 1\n print(tail, file=output_file)\n\n def seed(self, seed=None):\n if seed:\n random.seed(seed) # make tests reproducible\n\n def render(self, mode='human', close=False):\n pass\n\n def configure(self, *args, **kwargs):\n pass\n\n\nclass PhasesSpace(Space):\n\n def __init__(self):\n self.phases = [0, 1]\n\n def sample(self, seed=None):\n \"\"\"sample phase actions.\"\"\"\n ix = random.randint(0, len(self.phases) - 1)\n return self.phases[ix]\n\n def contains(self, x):\n return self.phases.__contains__(x)\n\n\nclass Router(object):\n\n def __init__(self):\n self.seed = None\n\n def set_seed(self, seed=42):\n if seed:\n self.seed = seed\n random.seed(seed)\n\n def generate_route_file(self, output_file):\n \"\"\"Generate the .rou.xml file.\"\"\"\n raise NotImplementedError()\n","sub_path":"Code_Reference/sumocore.py","file_name":"sumocore.py","file_ext":"py","file_size_in_byte":14916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"268502244","text":"import cv2\r\nimport numpy as np \r\nimport pyautogui\r\nimport time\r\nct=0\r\nct1=0\r\ntime.sleep(5)\r\ncap = cv2.VideoCapture(0)\r\nhand_cascade = cv2.CascadeClassifier('palm.xml')\r\nwhile(True):\r\n ret, frame = cap.read()\r\n print(type(cap))\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n hand = hand_cascade.detectMultiScale(gray, 1.3, 5)\r\n if len(hand) == 0:\r\n print (\"No hand found\")\r\n else:\r\n sum = 0\r\n print(\"detecting the number of hands\")\r\n for (x,y,w,h) in hand:\r\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)\r\n sum = sum+1\r\n #print(\"frame:\", len(frame))\r\n if len(frame) > 0:\r\n pyautogui.press('space')\r\n print(\"1\")\r\n sum = 1\r\n else:\r\n pass\r\n cv2.imshow('frame', frame)\r\n if cv2.waitKey(1) & 0xFF == ord('q'): \r\n break\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"hand_detection_from_scratch/hand_detection_2.py","file_name":"hand_detection_2.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"566825837","text":"from collections import namedtuple as struct\nimport pygame\nimport time\n\nBall = struct(\"Ball\", [\"pos_x\", \"pos_y\", \"width\", \"height\", \"speed_x\", \"speed_y\", \"image\"])\nPaddle = struct(\"Paddle\", [\"pos_x\", \"pos_y\", \"width\", \"height\", \"max_speed_y\", \"image\"])\nField = struct(\"Field\", [\"width\", \"height\", \"ball\", \"paddle\"])\nGame = struct(\"Game\", [\"field\", \"screen\"])\n\ndef ball_hits_paddle(ball, paddle):\n \"\"\"Return True if the ball has hit the paddle.\"\"\"\n return (ball.speed_x < 0 and \n ball.pos_x >= paddle.pos_x + paddle.width / 2.0 and\n ball.pos_x < paddle.pos_x + paddle.width and\n ball.pos_y + ball.height > paddle.pos_y and\n ball.pos_y <= paddle.pos_y + paddle.height)\n\ndef get_new_ball(ball, field, delta_t):\n \"Return a new ball considering collisions (None if the ball went out of bounds)\"\n new_pos_x = ball.pos_x + delta_t*ball.speed_x\n new_pos_y = ball.pos_y + delta_t*ball.speed_y\n new_ball = ball._replace(pos_x=new_pos_x, pos_y=new_pos_y)\n \n if (new_ball.pos_x + new_ball.width) < 0:\n return\n else:\n if ball_hits_paddle(new_ball, field.paddle):\n new_speed_x = abs(ball.speed_x)\n elif ball.speed_x > 0 and (new_ball.pos_x + ball.width) >= field.width:\n new_speed_x = -abs(ball.speed_x)\n else:\n new_speed_x = ball.speed_x\n \n if ball.speed_y < 0 and new_ball.pos_y < 0:\n new_speed_y = abs(ball.speed_y)\n elif ball.speed_y > 0 and (new_ball.pos_y + ball.height) >= field.height:\n new_speed_y = -abs(ball.speed_y)\n else:\n new_speed_y = ball.speed_y\n\n return new_ball._replace(speed_x=new_speed_x, speed_y=new_speed_y)\n\ndef get_new_paddle(paddle, field, keys, delta_t):\n \"\"\"Return a new paddle (keys: UP/DOWN).\"\"\"\n if keys[pygame.K_DOWN]:\n paddle_speed_y = paddle.max_speed_y\n elif keys[pygame.K_UP]:\n paddle_speed_y = -paddle.max_speed_y\n else:\n paddle_speed_y = 0\n\n new_paddle_pos_y = paddle.pos_y + delta_t*paddle_speed_y\n if new_paddle_pos_y < 0 or (new_paddle_pos_y + paddle.height) >= field.height:\n final_paddle_pos_y = paddle.pos_y\n else:\n final_paddle_pos_y = new_paddle_pos_y\n return paddle._replace(pos_y=final_paddle_pos_y)\n\ndef get_new_field(field, keys, delta_t):\n \"\"\"Return the new field (None if the game finished).\"\"\"\n new_paddle = get_new_paddle(field.paddle, field, keys, delta_t)\n new_ball = get_new_ball(field.ball, field, delta_t)\n return (field._replace(ball=new_ball, paddle=new_paddle) if new_ball else None)\n\ndef update_game(game, keys, delta_t):\n \"\"\"Return the new field (None if the game finished).\"\"\"\n new_field = get_new_field(game.field, keys, delta_t)\n return game._replace(field=new_field)\n\ndef draw_game(game):\n \"\"\"Draw the game (field, ball and paddle) onto the game screen.\"\"\"\n field = game.field\n game.screen.fill((0, 0, 0))\n game.screen.blit(field.ball.image, (field.ball.pos_x, field.ball.pos_y))\n game.screen.blit(field.paddle.image, (field.paddle.pos_x, field.paddle.pos_y))\n pygame.display.flip()\n \ndef loop_game(game):\n \"\"\"State loop of a game.\"\"\"\n time0 = time.time()\n while 1: \n draw_game(game)\n \n time1 = time.time()\n events = pygame.event.get()\n keys = pygame.key.get_pressed()\n new_game = update_game(game, keys, delta_t=time1-time0)\n \n if any(event.type == pygame.QUIT for event in events):\n break\n elif not new_game.field:\n break\n else:\n time0 = time1\n game = new_game\n\ndef build_game(screen_size):\n \"\"\"Load multimedia files and return the initial game object.\"\"\"\n ball_image = pygame.image.load(\"media/ball.png\")\n ball = Ball(image=ball_image, pos_x=100, pos_y=200, speed_x=550, speed_y=300, \n width=ball_image.get_width(), height=ball_image.get_height())\n \n paddle_image = pygame.image.load(\"media/paddle.png\")\n paddle = Paddle(image=paddle_image, pos_x=10, pos_y=100, max_speed_y=600, \n width=paddle_image.get_width(), height=paddle_image.get_height())\n \n width, height = screen_size\n field = Field(ball=ball, paddle=paddle, width=width, height=height)\n\n screen = pygame.display.set_mode(screen_size)\n return Game(field=field, screen=screen)\n\ndef run():\n \"\"\"Run the loop game.\"\"\"\n pygame.init()\n game = build_game(screen_size=(640, 480))\n loop_game(game)\n\nrun()\n","sub_path":"pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"197855075","text":"import sys\nimport os\nimport glob\n\nprint(\"Init Pre Caric\")\n\n\n#Estraggo info da file di properties\npathFileProp = \"dati\\\\FIX_CONFIG_FILE.txt\"\nfileConfigOut = \"dati\\\\CONFIGURATION_FILE.txt\"\n\naddedFile = [] #lista file aggiunti per controllo univocita caricamento\n\nwith open(pathFileProp) as f:\n\twith open(fileConfigOut,\"w\") as g:\n\t\tcontent = f.readlines()\n\t\tfor line in content:\n\t\t\tif not line.startswith(\"#\"):\n\t\t\t\tlineSpiltted = line.rstrip(\"\\n\").split(\",\")\n\t\t\t\t#print(lineSpiltted)\n\n\t\t\t\t#Estraggo nome file da directory dati\\ con filtro\n\t\t\t\t#print(\"filtro:\" + \"dati\\\\\"+lineSpiltted[1]+\"*\")\n\t\t\t\tfileCSVList = glob.glob(\"dati\\\\\"+lineSpiltted[1]+\"*\")\n\t\t\t\t#print(fileCSVList)\t\n\n\t\t\t\t#per ogni file trovati inserisco una entry nel file di configurazione \n\t\t\t\tfor entry in fileCSVList:\t\t\t\t\t\t\n\t\t\t\t\tif entry in addedFile:\n\t\t\t\t\t\tprint(\"###ERROR### file \"+entry[5:]+\" inserito più volte\")\t\n\t\t\t\t\t\tsys.exit()\n\t\t\t\t\telse:\n\t\t\t\t\t\t#print(\"write line:\" + lineSpiltted[0]+\",\"+entry[5:])\n\t\t\t\t\t\tg.write(lineSpiltted[0]+\",\"+entry[5:]+\"\\n\")\n\t\t\t\t\t\taddedFile.append(entry)\n\n\n\nallFileCSVList = glob.glob(\"dati\\\\*.csv\")\n#print(allFileCSVList)\n\nfor aFile in allFileCSVList:\n\tif not aFile in addedFile:\n\t\tprint(\"###ERROR###\"+aFile + \" non inserito in CONFIGURATION_FILE\")\n\t\t\nprint(\"End Pre Caric\")","sub_path":"Database Oracle/Sql loader script/preCaric.py","file_name":"preCaric.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"407925187","text":"import json\n\ndef textos_to_json():\n\tout = {}\n\tpuntos = {}\n\tfor i in range(7):\n\t\twith open(\"../data/output_punto_\"+str(i)+\".txt\", 'r') as f:\n\t\t\ttext = f.read()\n\t\t\titems = text.split('---')\n\n\t\t\tpunto_actual = {}\n\t\t\tresumen = {}\n\t\t\ttopicos = {}\n\n\t\t\tfor j in range(3):\n\t\t\t\tnivel = items[j+2].replace(\"nivel_\"+str(j+1)+\":\\n\", '')\n\t\t\t\ttopico = items[j+6].replace(\"topicos_\"+str(j+1)+\":\\n\", '')\n\t\t\t\tresumen[\"nivel_\"+str(j+1)] = nivel\n\t\t\t\ttopicos[\"topicos_\"+str(j+1)] = topico\n\n\t\t\tpunto_actual[\"resumen\"] = resumen\n\t\t\tpunto_actual[\"topicos\"] = topicos\n\t\t\tpuntos[\"punto_\"+str(i)] = punto_actual\n\n\tout[\"puntos\"] = puntos\n\n\twith open('../data/ejemplo.json', 'w', encoding='utf8') as json_file:\n\t json.dump(out, json_file, ensure_ascii=False)\n\n\ndef frecuencias_to_json():\n\tout = {}\n\t\n\tpolitica = []\n\tjusticia = []\n\ttierras = []\n\tposconflicto = []\n\treparacion = []\n\n\twith open(\"../data/frecuencias.txt\", 'r') as f:\n\t\tlines = f.read().split(\"\\n\")\n\t\tpolitica = [float(x.split(\",\")[0]) for x in lines]\n\t\tjusticia = [float(x.split(\",\")[1]) for x in lines]\n\t\ttierras = [float(x.split(\",\")[2]) for x in lines]\n\t\tposconflicto = [float(x.split(\",\")[3]) for x in lines]\n\t\treparacion = [float(x.split(\",\")[4]) for x in lines]\n\n\tout[\"politica\"] = politica\n\tout[\"justicia\"] = justicia\n\tout[\"tierras\"] = tierras\n\tout[\"posconflicto\"] = posconflicto\n\tout[\"reparacion\"] = reparacion\n\n\twith open('../data/frecuencias.json', 'w', encoding='utf8') as json_file:\n\t json.dump(out, json_file, ensure_ascii=False)\n\n\n\n\n\n\n\t\n\t\n\n\n","sub_path":"preprocesamiento/limpieza/to_json.py","file_name":"to_json.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"43346648","text":"#!/usr/bin/env python\n\n# Example GPIO code\n# Note difference between \"BOARD\" and \"BCM\" options\n\nimport time\nimport os\nimport RPi.GPIO as GPIO\n\n#PINS = (0, 1, 4, 14) # Specify pins to use, BCM mode\nPINS = (3, 5, 7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24, 26) # Specify pins to use, Board mode\ndelay = 8 # time delay in seconds\n\ndef setup():\n\tGPIO.setmode(GPIO.BOARD)\n\tfor pin in PINS:\n\t\tGPIO.setup(pin, GPIO.OUT)\n\ndef applyvalues(values):\n\tfor pin, val in zip(PINS, values):\n\t\tprint(\"setting pin %s to %s\" % (pin, val))\n\t\tGPIO.output(pin, val)\n\ndef quit():\n\tfor pin in PINS:\n\t\tGPIO.output(pin, GPIO.LOW)\n\n# Set all pins high, then low.\n# Repeat until interrupted.\ndef main():\n\tsetup()\n\twhile True:\n\t\ttry:\n\t\t\tprint(\"High...\")\n\t\t\tapplyvalues([GPIO.HIGH]*len(PINS))\n\t\t\ttime.sleep(delay/2.0)\n\t\t\tprint(\"Low...\")\n\t\t\tapplyvalues([GPIO.LOW]*len(PINS))\n\t\t\ttime.sleep(delay)\n\t\texcept (KeyboardInterrupt, SystemExit):\n\t\t\tquit()\n\t\t\tbreak\n\t\tfinally:\n\t\t\tquit()\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"gpio_test.py","file_name":"gpio_test.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"82398855","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimg = cv2.imread('../data/sample_image/sample_rib2.jpg')\nheight, width = img.shape[:2]\n\ngray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\neq_img = cv2.equalizeHist(gray_img)\nenhance_img = cv2.medianBlur(eq_img,3)\nplt.imshow(eq_img,'gray')\nplt.show()\n\nplt.imshow(enhance_img,cmap = 'gray')\nplt.show()\n\n\nstructuredEdgeModel = cv2.ximgproc.createStructuredEdgeDetection(\"../Materials/structuredEdgeModel.yml\")\nenhance_img2 = cv2.cvtColor(enhance_img,cv2.COLOR_GRAY2BGR)\nplt.imshow(enhance_img2,cmap = 'gray')\nplt.show()\n\nenhance_img2 = np.float32(enhance_img2)\nenhance_img2 = enhance_img2/255.0\nplt.imshow(enhance_img2,cmap = 'gray')\nplt.show()\n\nenhance_img3 = structuredEdgeModel.detectEdges(enhance_img2)\nplt.imshow(enhance_img3,cmap = 'gray')\nplt.show()\n\nenhance_img3 = enhance_img3*255\nenhance_img4 = enhance_img3>2\nenhance_img4\nlines = cv2.HoughLinesP(enhance_img4, 1, np.pi/180, 100)\nfor x in range(0, len(lines)):\n for x1,y1,x2,y2 in lines[x]:\n cv2.line(enhance_img4,(x1,y1),(x2,y2),(0,255,0),2)\nplt.imshow(enhance_img4,'gray')\nplt.show()\n\nenh_low_threshold = 120\nedge_img = cv2.Canny(enhance_img,enh_low_threshold, enh_low_threshold*3 )\nplt.imshow(edge_img,cmap = 'gray')\nplt.show()\n\n\n## Thoracic vertebrae detectionh\nvert_threshold_value = 100\nvert_max_BINARY_value = 255\nvert_threshold_type = 1\n\nret,vertebrae = cv2.threshold(img,vert_threshold_value, vert_max_BINARY_value, vert_threshold_type)\n\n## Draw Lines of each rib\nthreshold_value = 180\nmax_BINARY_value = 255\nthreshold_type = 1\nkernel = np.ones((5,5),np.uint8)\n\n#output = cv2.Canny(inputImage,lowThreshold,lowThreshold*4);\nret2,binary_img = cv2.threshold(img,threshold_value, max_BINARY_value,threshold_type);\noutput = cv2.morphologyEx(binary_img, cv2.MORPH_CLOSE, kernel)\n\n# cv2.imshow(\"Thoracic Vertebrae\",vertebrae)\n# cv2.imshow(\"Output\",output)\nfig = plt.figure(figsize=(15,7))\ntitles = ['Original Image','BINARY','OUTPUT','VERTEBRAE']\nimages = [img, binary_img,output,vertebrae]\nfor i in range(len(titles)):\n plt.subplot(1,4,i+1),plt.imshow(images[i])\n plt.title(titles[i])\n plt.xticks([]),plt.yticks([])\n plt.show()\n# cv2.waitKey(0)\n","sub_path":"rib_counting_v1.py","file_name":"rib_counting_v1.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"257071215","text":"# 27 May 2018 Miroslav Gasparek\n# Python bootcamp, lesson 36: Exercise on testing and test-driven development\n\n# Import modules\nimport re\nimport pytest\n\nimport numpy as np\nimport pandas as pd\n\n\n### Practice 2 ###\n\ndef test_dissoc_equil():\n \"\"\" Tests for dissoc_equil().\"\"\"\n\n # Check for the validity of the response to the proper inputs\n # Edge cases\n assert np.allclose(dissoc_equil(1,0,0), np.array([0,0,0]))\n assert np.allclose(dissoc_equil(0,0,0), np.array([0,0,0]))\n assert np.allclose(dissoc_equil(0, 1, 1), np.array([0, 0, 1]))\n assert np.allclose(dissoc_equil(0, 1, 2), np.array([0, 1, 1]))\n assert np.allclose(dissoc_equil(0, 2, 1), np.array([1, 0, 1]))\n assert np.allclose(dissoc_equil(np.inf,1,1), np.array([1,1,0]))\n\n # Standard cases\n # Check for the range of initial conditions on a log scale\n # This will exhibit an error - due to the numerical stability issue\n Kd_vals = np.logspace(-10, 1, 50)\n ca0_vals = np.logspace(-5, 2, 50)\n cb0_vals = np.logspace(-5, 2, 50)\n for Kd in Kd_vals:\n for ca0 in ca0_vals:\n for cb0 in cb0_vals:\n assert check_eq(Kd, ca0, cb0, *dissoc_equil(Kd, ca0, cb0)), \\\n 'Kd = %g, ca0 = %g, cb0 = %g' % (Kd, ca0, cb0)\n # Check for the validity of the user input\n # Errors\n pytest.raises(RuntimeError, \"dissoc_equil(-1,1,1)\")\n pytest.raises(RuntimeError, \"dissoc_equil(1, -1, 1)\")\n pytest.raises(RuntimeError, \"dissoc_equil(1, 1, -1)\")\n pytest.raises(RuntimeError, \"dissoc_equil(1, np.inf, 1)\")\n pytest.raises(RuntimeError, \"dissoc_equil(1, 1, np.inf)\")\n\n return None\n\ndef dissoc_equil(Kd, ca0, cb0):\n \"\"\" Compute equilibrium for dissociation reaction.\"\"\"\n\n # Check input\n if Kd < 0 or ca0 < 0 or cb0 < 0:\n raise RuntimeError('All input must be nonnegative.')\n if not (ca0 < np.inf and cb0 < np.inf):\n raise RuntimeError('Input concentrations must be finite.')\n\n # If we have infinite Kd\n if Kd == np.inf:\n return ca0, cb0, 0\n\n # Compute cab from quadratic formula\n b = ca0 + cb0 + Kd\n cab = (b - np.sqrt(b**2 - 4*ca0*cb0))/2\n\n # Compute ca and cb from conservation of mass\n ca = ca0 - cab\n cb = cb0 - cab\n return ca, cb, cab\n\n\ndef check_eq(Kd, ca0, cb0, ca, cb, cab):\n \"\"\"Verify equilibrium expressions hold.\"\"\"\n eq = np.isclose(Kd, ca * cb / cab)\n cons_mass_A = np.isclose(ca0, ca + cab)\n cons_mass_B = np.isclose(cb0, cb + cab)\n\n return eq and cons_mass_A and cons_mass_B\n\n# Test the function\ntest_dissoc_equil()\n","sub_path":"tdd_practice2.py","file_name":"tdd_practice2.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"287580834","text":"\"\"\"ecomerce_turing URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import include, path\nfrom .app import app, store\nfrom .app.api import departments, categories, attributes, products, customers, orders, cart, tax, shipping, stripe, base\n\ndepartmentPatterns = [\n path('', departments.departments),\n path('', departments.departments),\n path('', base.url_error)\n]\n\ncategoryPatterns = [\n path('', categories.categories),\n path('', categories.categories),\n path('inProduct/', categories.product),\n path('inDepartment/', categories.department),\n path('', base.url_error)\n]\n\nattributePatterns = [\n path('', attributes.attributes),\n path('', attributes.attributes),\n path('values/', attributes.values),\n path('inProduct/', attributes.product),\n path('', base.url_error)\n]\n\nproductPatterns = [\n path('', products.products),\n path('', products.products),\n path('inCategory/', products.products),\n path('inDepartment/', products.products),\n path('inDepartment/', products.products),\n path('search', products.search),\n path('/details', products.details),\n path('/locations', products.locations),\n path('/reviews', products.reviews),\n path('', base.url_error)\n]\n\ncustomerPatterns = [\n path('', customers.register),\n path('/login', customers.login),\n path('/facebook', customers.login_fb),\n path('/address', customers.update_address),\n path('/creditCard', customers.update_creditcard),\n path('/', base.url_error)\n]\n\nordersPatterns = [\n path('', orders.create),\n path('/', orders.details),\n path('/inCustomer', orders.customer_data),\n path('/shortDetail/', orders.details_short),\n path('/', base.url_error)\n]\n\nshoppingCartPatterns = [\n path('generateUniqueId', cart.get_id),\n path('add', cart.add),\n path('update/', cart.update),\n path('empty/', cart.empty),\n path('moveToCart/', cart.move),\n path('totalAmount/', cart.amount),\n path('saveForLater/', cart.save),\n path('getSaved/', cart.get_saved),\n path('removeProduct/', cart.remove),\n path('clearOld', cart.clear_old_cart),\n path('', cart.get_list),\n path('', base.url_error)\n]\n\ntaxPatterns = [\n path('', tax.tax),\n path('',tax.tax),\n path('', base.url_error)\n]\n\nshippingPatterns = [\n path('regions', shipping.regions),\n path('regions/', shipping.region_data),\n path('', base.url_error)\n]\n\nstripePatterns = [\n path('charge', stripe.charge),\n path('webhooks', stripe.webhooks),\n path('', base.url_error)\n]\n\nurlpatterns = [\n path('', app.main),\n path('store/', store.main),\n path('store/stripe_session/', store.stripe_session),\n path('admin/', admin.site.urls),\n path('departments/', include(departmentPatterns)),\n path('categories/', include(categoryPatterns)),\n path('attributes/', include(attributePatterns)),\n path('products/', include(productPatterns)),\n path('customer', customers.customer),\n path('customers', include(customerPatterns)),\n path('orders', include(ordersPatterns)),\n path('shoppingcart/',include(shoppingCartPatterns)),\n path('tax/',include(taxPatterns)),\n path('shipping/',include(shippingPatterns)),\n path('stripe/',include(stripePatterns))\n]","sub_path":"ecomerce_turing/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"37641655","text":"import numpy as np\nimport cv2\nfrom imutils.object_detection import non_max_suppression\nimport pytesseract\nimport os\nfrom matplotlib import pyplot as plt\n\nfrom imutils.video import FPS\nimport imutils\n\nfrom find_contour import thresh_callback\n\n\ndef load(img, newW, newH, **kwargs):\n # resize the original image to new dimensions\n image = cv2.resize(img, (newW, newH))\n (H, W) = image.shape[:2]\n\n # construct a blob from the image to forward pass it to EAST model\n blob = cv2.dnn.blobFromImage(image, 1.0, (W, H), (123.68, 116.78, 103.94), swapRB=True, crop=False)\n\n return blob\n\n\n# Returns a bounding box and probability score if it is more than minimum confidence\ndef predictions(prob_score, geo, args, **kwargs):\n (numR, numC) = prob_score.shape[2:4]\n boxes_list = []\n confidence_val_list = []\n\n # loop over rows\n for y in range(0, numR):\n scoresData = prob_score[0, 0, y]\n x0 = geo[0, 0, y]\n x1 = geo[0, 1, y]\n x2 = geo[0, 2, y]\n x3 = geo[0, 3, y]\n anglesData = geo[0, 4, y]\n\n # loop over the number of columns\n for i in range(0, numC):\n if scoresData[i] < args[\"min_confidence\"]:\n continue\n\n (offX, offY) = (i * 4.0, y * 4.0)\n\n # extracting the rotation angle for the prediction and computing the sine and cosine\n angle = anglesData[i]\n cos = np.cos(angle)\n sin = np.sin(angle)\n\n # using the geo volume to get the dimensions of the bounding box\n h = x0[i] + x2[i]\n w = x1[i] + x3[i]\n\n # compute start and end for the text pred bbox\n endX = int(offX + (cos * x1[i]) + (sin * x2[i]))\n endY = int(offY - (sin * x1[i]) + (cos * x2[i]))\n startX = int(endX - w)\n startY = int(endY - h)\n\n boxes_list.append((startX, startY, endX, endY))\n confidence_val_list.append(scoresData[i])\n\n # return bounding boxes and associated confidence_val\n return boxes_list, confidence_val_list\n\n\ndef decode_predictions(scores, geometry, min_confidence):\n # grab the number of rows and columns from the scores volume, then\n # initialize our set of bounding box rectangles and corresponding\n # confidence scores\n (numRows, numCols) = scores.shape[2:4]\n rects = []\n confidences = []\n # loop over the number of rows\n for y in range(0, numRows):\n # extract the scores (probabilities), followed by the\n # geometrical data used to derive potential bounding box\n # coordinates that surround text\n scoresData = scores[0, 0, y]\n xData0 = geometry[0, 0, y]\n xData1 = geometry[0, 1, y]\n xData2 = geometry[0, 2, y]\n xData3 = geometry[0, 3, y]\n anglesData = geometry[0, 4, y]\n # loop over the number of columns\n for x in range(0, numCols):\n # if our score does not have sufficient probability,\n # ignore it\n if scoresData[x] < min_confidence:\n continue\n # compute the offset factor as our resulting feature\n # maps will be 4x smaller than the input image\n (offsetX, offsetY) = (x * 4.0, y * 4.0)\n # extract the rotation angle for the prediction and\n # then compute the sin and cosine\n angle = anglesData[x]\n cos = np.cos(angle)\n sin = np.sin(angle)\n # use the geometry volume to derive the width and height\n # of the bounding box\n h = xData0[x] + xData2[x]\n w = xData1[x] + xData3[x]\n # compute both the starting and ending (x, y)-coordinates\n # for the text prediction bounding box\n endX = int(offsetX + (cos * xData1[x]) + (sin * xData2[x]))\n endY = int(offsetY - (sin * xData1[x]) + (cos * xData2[x]))\n startX = int(endX - w)\n startY = int(endY - h)\n # add the bounding box coordinates and probability score\n # to our respective lists\n rects.append((startX, startY, endX, endY))\n confidences.append(scoresData[x])\n # return a tuple of the bounding boxes and associated confidences\n return rects, confidences\n\n\ndef read_video(args, vid_file, **kwargs):\n # initialize the original frame dimensions, new frame dimensions,\n # and ratio between the dimensions\n (W, H) = (None, None)\n (newW, newH) = (args[\"width\"], args[\"height\"])\n (rW, rH) = (None, None)\n # load the pre-trained EAST model for text detection\n net = cv2.dnn.readNet(args[\"east\"])\n\n # The following two layer need to pulled from EAST model for achieving this.\n layerNames = [\"feature_fusion/Conv_7/Sigmoid\", \"feature_fusion/concat_3\"]\n\n vs = cv2.VideoCapture(vid_file)\n\n # start the FPS throughput estimator\n fps = FPS().start()\n\n # loop over frames from the video stream\n while True:\n # grab the current frame, then handle if we are using a\n # VideoStream or VideoCapture object\n frame = vs.read()\n frame = frame[1]\n # check to see if we have reached the end of the stream\n if frame is None:\n break\n plt.imshow(frame)\n plt.title('gray')\n plt.show()\n # resize the frame, maintaining the aspect ratio\n frame = imutils.resize(frame, width=1000)\n plt.imshow(frame)\n plt.title('resize')\n plt.show()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray, (3, 3), 0)\n #otsu\n threshold = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]\n invert = 255 - threshold\n frame = np.dstack([invert] * 3)\n # Invert the image\n #threshold = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)\n plt.imshow(frame)\n plt.title('invert')\n plt.show()\n # frame = np.dstack([gray, gray, gray])\n\n kernel = np.ones((1, 1), np.uint8)\n dilate = cv2.dilate(threshold, kernel, iterations=1)\n erode = cv2.erode(dilate, kernel, iterations=1)\n\n #thresholding\n\n frame = np.dstack([invert] * 3)\n\n plt.imshow(frame)\n plt.title('Preprocessed')\n plt.show()\n orig = frame.copy()\n\n # if our frame dimensions are None, we still need to compute the\n # ratio of old frame dimensions to new frame dimensions\n if W is None or H is None:\n (H, W) = frame.shape[:2]\n rW = W / float(newW)\n rH = H / float(newH)\n # resize the frame, this time ignoring aspect ratio\n frame = cv2.resize(frame, (newW, newH))\n\n # construct a blob from the frame and then perform a forward pass\n # of the model to obtain the two output layer sets\n blob = cv2.dnn.blobFromImage(frame, 1.0, (newW, newH),\n (123.68, 116.78, 103.94), swapRB=True, crop=False)\n net.setInput(blob)\n (scores, geometry) = net.forward(layerNames)\n # decode the predictions, then apply non-maxima suppression to\n # suppress weak, overlapping bounding boxes\n (rects, confidences) = decode_predictions(scores, geometry, args['min_confidence'])\n boxes = non_max_suppression(np.array(rects), probs=confidences)\n\n # initialize the list of results\n results = []\n texts = []\n # loop over the bounding boxes\n for (startX, startY, endX, endY) in boxes:\n # scale the bounding box coordinates based on the respective\n # ratios\n startX = int(startX * rW)\n startY = int(startY * rH)\n endX = int(endX * rW)\n endY = int(endY * rH)\n\n # extract the region of interest\n r = orig[startY:endY, startX:endX]\n\n # configuration setting to convert image to string.\n configuration = (\"-l eng --oem 1 --psm 6\")\n ##This will recognize the text from the image of bounding box\n text = pytesseract.image_to_string(r, config=configuration)\n\n # append bbox coordinate and associated text to the list of results\n results.append(((startX, startY, endX, endY), text))\n\n texts.append(text)\n\n # Display the image with bounding box and recognized text\n orig_image = orig.copy()\n\n # Moving over the results and display on the image\n for ((start_X, start_Y, end_X, end_Y), text) in results:\n # display the text detected by Tesseract\n print(\"{}\\n\".format(text))\n\n # Displaying text\n text = \"\".join([x if ord(x) < 128 else \"\" for x in text]).strip()\n cv2.rectangle(orig_image, (start_X, start_Y), (end_X, end_Y),\n (0, 0, 255), 2)\n cv2.putText(orig_image, text, (start_X, start_Y - 30),\n cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n\n # draw the bounding box on the frame\n # cv2.rectangle(orig, (startX, startY), (endX, endY), (0, 255, 0), 2)\n # update the FPS counter\n fps.update()\n\n # show the output frame\n plt.imshow(orig_image)\n plt.title('Output')\n plt.show()\n concat = ','.join(texts)\n key = cv2.waitKey(1) & 0xFF\n # if the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n break\n # stop the timer and display FPS information\n fps.stop()\n print(\"[INFO] elasped time: {:.2f}\".format(fps.elapsed()))\n print(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n\n vs.release()\n\n # close all windows\n cv2.destroyAllWindows()\n\n\ndef read_frame(args, cropped, **kwargs):\n # load the pre-trained EAST model for text detection\n plt.imshow(cropped)\n plt.title('Cropped')\n plt.show()\n threshold = cv2.threshold(cropped, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]\n invert = 255 - threshold\n\n cnts = cv2.findContours(invert, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n cnts = cnts[0] if len(cnts) == 2 else cnts[1]\n for contour in cnts:\n (x, y, w, h) = cv2.boundingRect(contour)\n cv2.rectangle(invert, (x, y), (x + w, y + h), (0, 255, 0), 2)\n plt.imshow(invert)\n plt.title('invert Image')\n plt.show()\n cnts = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n cnts = cnts[0] if len(cnts) == 2 else cnts[1]\n for c in cnts:\n area = cv2.contourArea(c)\n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.01 * peri, True)\n x, y, w, h = cv2.boundingRect(approx)\n aspect_ratio = w / float(h)\n if (aspect_ratio >= 2.5 or area < 75):\n cv2.drawContours(threshold, [c], -1, (255, 255, 255), -1)\n\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 3))\n image = np.dstack([invert] * 3)\n # kernel = np.ones((1, 1), np.uint8)\n # image = cv2.dilate(image, kernel, iterations=1)\n # image = cv2.erode(image, kernel, iterations=1)\n\n plt.imshow(image)\n plt.title('Preprocessed Image')\n plt.show()\n\n # Saving a original image and shape\n orig = image.copy()\n (origH, origW) = image.shape[:2]\n\n # set the new height and width to default 320 by using args #dictionary.\n (newW, newH) = (args[\"width\"], args[\"height\"])\n\n # Forward pass the blob from the image to get the desired output layers\n net.setInput(load(img=image, newW=newW, newH=newH))\n (scores, geometry) = net.forward(layerNames)\n # Find predictions and apply non-maxima suppression\n (boxes, confidence_val) = predictions(scores, geometry, args)\n boxes = non_max_suppression(np.array(boxes), probs=confidence_val)\n\n ##Text Detection and Recognition\n\n # initialize the list of results\n results = []\n\n # Calculate the ratio between original and new image for both height and weight.\n # This ratio will be used to translate bounding box location on the original image.\n rW = origW / float(newW)\n rH = origH / float(newH)\n\n texts = []\n # loop over the bounding boxes to find the coordinate of bounding boxes\n for (startX, startY, endX, endY) in boxes:\n # scale the coordinates based on the respective ratios in order to reflect bounding box on the original image\n startX = int(startX * rW)\n startY = int(startY * rH)\n endX = int(endX * rW)\n endY = int(endY * rH)\n\n # extract the region of interest\n r = orig[startY:endY, startX:endX]\n\n # configuration setting to convert image to string.\n configuration = (\"-l eng --oem 1 --psm 6\")\n try:\n ##This will recognize the text from the image of bounding box\n text = pytesseract.image_to_string(r, config=configuration)\n\n # append bbox coordinate and associated text to the list of results\n results.append(((startX, startY, endX, endY), text))\n\n texts.append(text)\n\n # Display the image with bounding box and recognized text\n orig_image = orig.copy()\n\n # Moving over the results and display on the image\n for ((start_X, start_Y, end_X, end_Y), text) in results:\n # display the text detected by Tesseract\n print(\"{}\\n\".format(text))\n\n # Displaying text\n text = \"\".join([x if ord(x) < 128 else \"\" for x in text]).strip()\n cv2.rectangle(orig_image, (start_X, start_Y), (end_X, end_Y),\n (0, 0, 255), 2)\n cv2.putText(orig_image, text, (start_X, start_Y - 30),\n cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 2)\n\n plt.imshow(orig_image)\n plt.title('Output')\n plt.show()\n concat = ','.join(texts)\n except Exception as e:\n print(e)\n return True\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n user = \"consumingcouple\"\n folder = f\"/Users/thomascho/code/tiktokvideos/{user}\"\n\n default_args = {\n \"east\": \"/Users/thomascho/code/frozen_east_text_detection.pb\",\n \"min_confidence\": 0.5,\n \"width\": 320,\n \"height\": 320}\n\n for root, dirs, files in os.walk(folder, topdown=False):\n for index, file in enumerate(files):\n if file.endswith('frame0.jpg'):\n full_path = os.path.join(root, file)\n net = cv2.dnn.readNet(default_args[\"east\"])\n\n # The following two layer need to pulled from EAST model for achieving this.\n layerNames = [\"feature_fusion/Conv_7/Sigmoid\", \"feature_fusion/concat_3\"]\n image = cv2.imread(full_path)\n plt.imshow(image)\n plt.title('Image')\n plt.show()\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray, (3, 3), 0)\n cropped = thresh_callback(100, blur)\n for crop in cropped:\n read_frame(default_args, cropped=crop)\n print(index)\n","sub_path":"Python/read_frames.py","file_name":"read_frames.py","file_ext":"py","file_size_in_byte":15279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"215900302","text":"# coding=utf-8\nimport datetime\n\nfrom marvin.api.plugin import Plugin\n\nclass LastSeenPlugin(Plugin):\n \"\"\"Remembers the last time people were online\"\"\"\n alias = \"seen\"\n online = {}\n seen = {}\n\n def __init__(self):\n self.commands = {\n \"seen\": self._seen\n }\n\n def on_joined(self, user):\n name = user.name.lower()\n\n self.online[name] = user.room\n if name in self.seen:\n del self.seen[name]\n\n def on_left(self, user):\n name = user.name.lower()\n\n self.seen[name] = {\"room\": user.room, \"time\": datetime.datetime.now()}\n if name in self.online:\n del self.online[name]\n\n def _seen(self, _, args):\n \"\"\"Show the last time a user was online, or a room where they are online in\n seen \"\"\"\n if not args:\n return \"No args!\"\n\n name = args[0].lower()\n\n if name in self.online:\n return \"{0} is online in {1}!\".format(args[0], self.online[name])\n if name in self.seen:\n return \"I last saw {0} in {1} at {2}!\".format(args[0], self.seen[name][\"room\"], self.seen[name][\"time\"])\n return \"I haven't seen {0}!\".format(args[0])\n","sub_path":"marvin/plugins/seen.py","file_name":"seen.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"435589640","text":"import pickle\nfrom flask import Flask, request, render_template\n\napp = Flask(__name__)\nModel = pickle.load(open('Model.pkl','rb'))\n\n@app.route('/')\ndef index():\n return render_template('CreditInfo.html') \n\n@app.route('/result', methods=['GET', 'POST'])\ndef creditPrediction():\n if request.method == 'POST':\n LoanAmount = request.form['loanAmount']\n Age = request.form['age']\n HasHouse = request.form['home']\n CreditCount = request.form['creditCount']\n HasPhone = request.form['phone']\n \n predict = Model.predict([[float(LoanAmount),\n float(Age),\n float(HasHouse),\n float(CreditCount),\n float(HasPhone),]])\n creditResult = predict[0]\n if(creditResult>=1):\n creditState = \"Kredi verilebilir.\"\n else:\n creditState = \"Kredi verilemez.\"\n \n return render_template(\"result.html\",creditState = creditState)\n else:\n return render_template('CreditInfo.html')\n\nif __name__ == '__main__':\n try:\n app.run(debug=False)\n print(\"Sunucu aktif!\")\n except:\n print(\"Sunucu hatası!\")","sub_path":"Credit_Service/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"373067003","text":"__author__ = 'fferreira'\n\nfrom random import shuffle, random, choice\n\nimport psa\nfrom psa.util import argmax\n\n\n#___________________________________________________\n\n\nclass QLearning(object ):\n def __init__(self): # ** deveriamos passar os parametros psa para anular as dependencais\n self.alfa = 0.5 # se for 1 fica reativo\n self.gama = 0.9 # e o elemento de previsao do futuro\n self.epson = 0.010 # faz sentido ser pequeno senao nao aproveita so explora\n self.Q= {} #dicionario com par de estado accao com chave a que e associado o valor r\n self.accoes= psa.dirmov()\n\n def qval(self, s,a):\n return self.Q.get((s,a), 0)\n\n def max_accao(self, s):\n # baralha a lista para garantir que nao corremos sempre a mesma lista\n shuffle( self.accoes)\n return argmax( self.accoes, lambda a: self.qval(s,a) )\n\n def assimilar(self, s, a, r, sn):\n amax = self.max_accao(sn)\n qsa= self.Q.get( (s,a), 0)\n qsnan= self.Q.get((sn,amax),0)\n delta = r + self.gama * qsnan -qsa\n self.Q[(s,a)] = qsa + self.alfa * delta\n\n\n\n def seleccionar_accao(self, sn):\n # se maior que ep\n x = random()\n if x < self.epson:\n # vai explorar com um movimento aleatorio\n accao = choice(self.accoes)\n else:\n accao = self.max_accao(sn)\n\n return accao\n\n","sub_path":"src/lib/aprend_ref/q_learning.py","file_name":"q_learning.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"561529766","text":"# -*- coding:utf-8 -*-\n# json转换csv文件\n\nimport json\nimport csv\n\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\ndef json_to_csv():\n\n # 1.读取json文件\n json_file = open(\"5tencent.json\", \"r\")\n\n # 2.创建csv文件\n csv_file = open(\"6json.csv\", \"w\")\n\n # 3.创建读写器\n csv_writer = csv.writer(csv_file)\n\n # 4.提取表头和正文内容\n data = json.load(json_file)\n\n # 表头\n sheet_title = data[0].keys()\n # 内容\n content_list = []\n for dic in data:\n content_list.append(dic.values())\n\n # content_list = [dic.values() for dic in data]\n\n # 通过读写器 写入文件\n csv_writer.writerow(sheet_title)\n csv_writer.writerows(content_list)\n\n # 关闭文件\n json_file.close()\n csv_file.close()\n\nif __name__ == '__main__':\n json_to_csv()","sub_path":"day04/6jsontocsv.py","file_name":"6jsontocsv.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"67331929","text":"\"\"\"zz URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.conf.urls import url, include\r\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.conf.urls import url\r\nfrom myadmin import views\r\n\r\nurlpatterns = [\r\n url(r'^$', views.index),\r\n url(r'book/$', views.book),\r\n url(r'book/add/$', views.book_add),\r\n url(r'book/(?P\\d+)/change/$', views.book_change),\r\n url(r'publisher/$', views.publisher),\r\n url(r'publisher/add/$', views.publisher_add),\r\n url(r'publisher/(?P\\d+)/change/$', views.publisher_change),\r\n url(r'author/$', views.author),\r\n url(r'author/add/$', views.author_add),\r\n url(r'author/(?P\\d+)/change/$', views.author_change),\r\n url(r'(?P\\w+)/(?P\\d+)/delete/$', views.delete),\r\n]\r\n","sub_path":"day16/homework/zz/myadmin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"267015493","text":"__author__ = 'ca1ek'\n\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"file\", help='file to search in')\nparser.add_argument(\"text\", help='text to be searched in the file')\nparser.add_argument(\"-a\", \"--all\", help=\"show all occurrences of the word without any prompting\", action=\"store_true\")\nparser.add_argument(\"-s\", \"--simple\", help=\"returns only position of words separated with semicolons, works only with -a\", action=\"store_true\")\nargs = parser.parse_args()\n\ndef split_all_in_array(to_split, split_by):\n words = [] # array of single words\n for element in to_split: # element is now a single line in the array\n split = element.split(split_by) # split is an array of words separated by split_by from to_split\n for word in split:\n words.append(word)\n return words\n\ndef find_in_data(srch_in, srch_for, earlier_data):\n if not earlier_data:\n data = srch_in.read().splitlines() # array split at lines\n data = split_all_in_array(data, \" \") # array split at words\n if earlier_data:\n data = earlier_data\n position = data.index(srch_for) # first position found\n return position, data\n\ntry:\n\n search_in = open(str(args.file))\n search_for = str(args.text)\n\n second_search = False\n\n response = \"y\"\n while response.upper() == \"Y\":\n if second_search:\n found_at, earlier_data = find_in_data(search_in, search_for, earlier_data)\n else:\n found_at, earlier_data = find_in_data(search_in, search_for, False)\n\n if not args.simple:\n print(\"Found, word #\" + str(found_at + 1))\n del earlier_data[found_at]\n elif args.simple:\n print(str(found_at + 1) + \";\")\n del earlier_data[found_at]\n\n if not args.all:\n print(\"Continue searching? (y/n)\")\n response = str(raw_input())\n else:\n response = \"Y\"\n if response.upper() == \"Y\":\n second_search = True\n\n\nexcept ValueError:\n if second_search and not args.all:\n print(\"No more occurrences of that word found\")\n elif not args.all:\n print(\"Text was not found.\")\n elif args.simple:\n print(\"\")\n\nexcept IOError:\n print(\"File does not exist, please check filename.\")","sub_path":"find_in_file.py","file_name":"find_in_file.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"583908151","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 3 15:42:32 2020\n\n@author: joyce\n\"\"\"\n\n'''\nUma string S de letras inglesas minúsculas é fornecida. Queremos particionar esta string em tantas partes quanto possível, de \nmodo que cada letra apareça em no máximo uma parte e retornar uma lista de inteiros representando o tamanho dessas partes.\n\n'''\n\nclass Solution(object):\n def partitionLabels(self, S):\n \"\"\"\n :type S: str\n :rtype: List[int]\n \"\"\"\n\n \n ultima = dict() #criar um dicionário que armazenará os maiores indices de cada letra\n unicas = set(S) #letras na ordem sem repetição\n i = len(S)-1\n res = []\n start = 0\n end = 0\n \n while unicas:\n if S[i] in unicas:\n ultima[S[i]] = i\n unicas.remove(S[i])\n i = i - 1\n \n #return ultima\n\n for indice, valor in enumerate(S):\n end = max(end, ultima[valor])\n if end == indice: \n res.append(end - start + 1)\n start = indice + 1\n \n return res\n \n \ndef main():\n \n testlist = \"ababcbacadefegdehijhklij\" \n\n print(\"Teste 1\")\n \n \n s = Solution() #chamo a classe\n\n print(s.partitionLabels(testlist)) #[9,7,8]\n \n\n\n \n \nmain()\n \n ","sub_path":"leetcodePartitionLabels.py","file_name":"leetcodePartitionLabels.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"33075128","text":"from pymongo import MongoClient\nimport os\n\nclient = MongoClient(os.environ.get(\"MONGO_URL\", default = \"localhost\"), 27017)\n\ndef create_entrie(object, collection_name):\n\tcollection = client[collection_name]\n\tserialized_object = object.serialize()\n\tpost_id = collection.insert_one(serialized_object)\n\n\treturn post_id\n\ndef get_entries(collection_name, query, model):\n\tcollection = client[collection_name]\n\tentries = collection.find(query)\n\n\tif not entries: return []\n\n\tresult = []\n\tfor entry in entries:\n\t\tobj = model(serialized_object = entry)\n\t\tresult.append(obj)\n\n\treturn obj\n\ndef delete_entries(collection_name, query):\n\tcollection = client[collection_name]\n\treturn collection.delete_many(query)\n\ndef update_entries(query, obj):\n\tserialized_object = object.serialize()\n\tmycollection.update(query, {\"$set\": serialized_object}, upsert=False)","sub_path":"app/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"426232822","text":"# @Github : https://github.com/ermongroup/GraphScoreMatching\nimport numpy as np\nimport torch\n\n\ndef node_feature_to_matrix(x):\n \"\"\"\n :param x: BS x N x F\n :return:\n x_pair: BS x N x N x 2F\n \"\"\"\n x_b = x.unsqueeze(-2).expand(-1, -1, x.size(1), -1) # BS x N x N x F\n x_b_t = x_b.transpose(1, 2) # BS x N x N x F\n x_pair = torch.cat([x_b, x_b_t], dim=-1) # BS x N x N x 2F\n return x_pair\n\n\ndef mask_adjs(adjs, node_flags):\n \"\"\"\n :param adjs: B x N x N or B x C x N x N\n :param node_flags: B x N\n :return:\n \"\"\"\n if len(adjs.shape) == 4:\n node_flags = node_flags.unsqueeze(1) # B x 1 x N\n adjs = adjs * node_flags.unsqueeze(-1)\n adjs = adjs * node_flags.unsqueeze(-2)\n return adjs\n\n\ndef pad_adjs(ori_adj, node_number):\n a = ori_adj\n ori_len = a.shape[-1]\n if ori_len == node_number:\n return a\n if ori_len > node_number:\n raise ValueError(f'ori_len {ori_len} > node_number {node_number}')\n a = np.concatenate([a, np.zeros([ori_len, node_number - ori_len])],\n axis=-1)\n a = np.concatenate([a, np.zeros([node_number - ori_len, node_number])],\n axis=0)\n return a\n\n\ndef get_corrupt_k(min_k=0, max_k=None, p=0.5):\n ret = np.random.geometric(p) + min_k - 1\n if max_k is not None:\n ret = min(ret, max_k)\n return ret\n\n\ndef remove_self_loop_if_exists(adjs):\n return (adjs - torch.eye(adjs.size()[-1]).unsqueeze(0).to(adjs.device)\n ).clamp(min=0.0)\n\n\ndef add_self_loop_if_not_exists(adjs):\n if len(adjs.shape) == 4:\n return adjs + torch.eye(adjs.size()[-1]\n ).unsqueeze(0).unsqueeze(0).to(adjs.device)\n return adjs + torch.eye(adjs.size()[-1]).unsqueeze(0).to(adjs.device)\n\n\ndef toggle_edge_np(adj, count=1):\n \"\"\"\n uniformly toggle `count` edges of the graph,\n suppose that the vertex number is fixed\n\n :param adj: N x N\n :param count: int\n :return: new adjs and node_flags\n \"\"\"\n count = min(count, adj.shape[-1])\n x = np.random.choice(adj.shape[0], count)\n y = np.random.choice(adj.shape[1], count)\n change = 1. - adj[x, y]\n adj[x, y] = change\n adj[y, x] = change\n return adj\n\n\ndef check_adjs_symmetry(adjs, do_check_adjs_symmetry=False):\n if not do_check_adjs_symmetry:\n return\n tr_adjs = adjs.transpose(-1, -2)\n assert (adjs - tr_adjs).abs().sum([0, 1, 2]) < 1e-2\n\n\ndef gen_list_of_data(train_x_b, train_adj_b, sigma_list):\n \"\"\"\n :param train_x_b: [bs, N, F_in], batch of feature vectors of nodes\n :param train_adj_b: [bs, N, N], batch of original adjacency matrices\n :param sigma_list: list of noise levels\n :return:\n train_x_b: [len(sigma_list) * bs, N, F_in],\n batch of feature vectors of nodes (w.r.t. `train_noise_adj_b`)\n train_noise_adj_b: [len(sigma_list) * bs, N, N],\n batch of perturbed adjacency matrices\n train_node_flag_b: [len(sigma_list) * bs, N], the flags for\n the existence of nodes (w.r.t. `train_noise_adj_b`)\n grad_log_q_noise_list: [len(sigma_list) * bs, N, N],\n the ground truth gradient (w.r.t. `train_noise_adj_b`)\n \"\"\"\n assert isinstance(sigma_list, list)\n train_noise_adj_b_list = []\n grad_log_q_noise_list = []\n for sigma_i in sigma_list:\n train_noise_adj_b, grad_log_q_noise = add_gaussian_noise(\n train_adj_b,\n sigma=sigma_i\n )\n train_noise_adj_b_list.append(train_noise_adj_b)\n grad_log_q_noise_list.append(grad_log_q_noise)\n \n train_noise_adj_b = torch.cat(train_noise_adj_b_list, dim=0)\n train_x_b = train_x_b.repeat(len(sigma_list), 1, 1)\n \n return train_x_b, train_noise_adj_b, grad_log_q_noise_list\n\n\ndef add_gaussian_noise(adjs, sigma, is_half=False):\n assert isinstance(adjs, torch.Tensor)\n noise = torch.randn_like(adjs).triu(diagonal=1) * sigma\n if is_half:\n noise = noise.abs()\n noise_s = noise + noise.transpose(-1, -2)\n check_adjs_symmetry(noise_s)\n grad_log_noise = - noise_s / (sigma ** 2)\n ret_adjs = adjs + noise_s\n \n return ret_adjs, grad_log_noise\n\n\ndef add_feature_noise(feats, sigma=0.2):\n assert isinstance(feats, torch.Tensor)\n ret_feats, grad_log_noise = [], []\n for i in range(36):\n noise = torch.randn_like(feats[:, i, :]) * sigma\n grad_log_noise.append(- noise / (sigma ** 2))\n ret_feats.append(feats[:, i, :] + noise)\n return torch.stack(ret_feats, dim=1), torch.stack(grad_log_noise, dim=1)\n\n\ndef add_feature_noise_v2(feats, sigma=0.2):\n assert isinstance(feats, torch.Tensor)\n noise = torch.randn_like(feats) * sigma\n feats = feats + noise\n grad_log_noise = - noise / (sigma ** 2)\n return feats, grad_log_noise\n\n\ndef add_edge_noise(adjs, sigma=0.2):\n noise = torch.zeros_like(adjs)\n temp = torch.randn((adjs.shape[0], 630), device=adjs.device) * sigma\n noise[torch.ones_like(adjs).triu(1) == 1] = temp.view(-1)\n noise = noise + noise.transpose(-1, -2)\n grad_log_noise = - noise / (sigma ** 2)\n adjs = adjs + noise\n return adjs, grad_log_noise\n\n\ndef add_edge_noise_v2(adjs, sigma=0.2):\n assert isinstance(adjs, torch.Tensor)\n noise = torch.randn_like(adjs).triu(diagonal=1) * sigma\n noise = noise + noise.transpose(-1, -2)\n grad_log_noise = - noise / (sigma ** 2)\n adjs = adjs + noise\n return adjs, grad_log_noise\n\n# def add_edge_noise(adjs, sigma=0.2):\n# noise = torch.zeros_like(adjs)\n# temp = torch.randn((adjs.shape[0], 630), device=adjs.device) * sigma\n# noise[torch.ones_like(adjs).triu(1) == 1] = temp.view(-1)\n#\n# noise = noise + noise.transpose(-1, -2)\n# grad_log_noise = - noise / (sigma ** 2)\n# adjs = adjs + noise\n# adjs = torch.div(adjs, adjs.max(1)[0].unsqueeze(-1))\n# return adjs, grad_log_noise\n","sub_path":"src/module/graph_utils.py","file_name":"graph_utils.py","file_ext":"py","file_size_in_byte":5854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"480146417","text":"from selenium.webdriver import Chrome\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.keys import Keys\nimport time\ndriver = Chrome(executable_path='F:\\TestingWorld\\SeleniumPython\\chromedriver.exe')\ndriver.get('http://www.thetestingworld.com')\ndriver.maximize_window()\n\n# Select all Ctrl+A\nact = ActionChains(driver)\nact.send_keys(Keys.CONTROL).send_keys(\"a\").perform()\n\n# Left Click\nact.click(driver.find_element_by_xpath(\"//a[text()='Login']\")).perform()\n# Right Click\nact.context_click(driver.find_element_by_xpath(\"//a[text()='Login']\")).perform()\n\n# Press TAB\ndriver.find_element_by_name('username')\nact = ActionChains(driver)\nact.send_keys(Keys.TAB).perform()\n\n# Mouse Hover\nact.move_to_element(driver.find_element_by_xpath(\"//a[text()='Login']\")).perform()","sub_path":"KeyBoardMouseOperation.py","file_name":"KeyBoardMouseOperation.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"291821691","text":"#!/usr/bin/env python\nimport argparse\nfrom pathlib import Path\nfrom datetime import datetime\nfrom tqdm import tqdm\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom data import Data\nfrom model import Seq2Seq\nfrom tools import log, calc_bleu_score, Logging, batch_label2word, output_translation\n\nclass Classifier(nn.Module):\n def __init__(self, model_s2t, model_t2s, constraint):\n super(Classifier, self).__init__()\n self.model_s2t = model_s2t\n self.model_t2s = model_t2s\n self.loss_fun = nn.CrossEntropyLoss(ignore_index=1)\n self.constraint = constraint\n self.mse_loss = nn.MSELoss()\n \n def forward(self, src, trg, train=True, max_length=60):\n # train==False: Translation else: Train or Varidation\n # Translation->trg is None, Train or Varidation->trg is not None\n s_length = src[1]\n src = src[0]\n t_length = trg[1]\n trg = trg[0]\n src_sos = src[ :-1] if train else None\n src_eos = src[1: ]\n trg_sos = trg[ :-1] if train else None\n trg_eos = trg[1: ]\n\n # target2source \n if train: max_length = len(src_eos)\n labels_t2s, output_t2s, enc_outputs_t2s = self.model_t2s(\n trg_eos, src_sos, src_lengths=t_length-1, length=max_length)\n\n # sorce2target\n if train: max_length = len(trg_eos)\n labels_s2t, output_s2t, enc_outputs_s2t = self.model_s2t(\n src_eos, trg_sos, src_lengths=s_length-1, length=max_length)\n\n # translation\n if not train:\n return labels_s2t, labels_t2s\n\n # constraint\n if self.constraint is not None:\n loss_c = self.constraint(enc_outputs_s2t, enc_outputs_t2s,\n s_length, t_length, self.mse_loss)\n else:\n loss_c = None\n\n # sorce2target loss\n L, B, V = output_s2t.size()\n output_s2t = output_s2t.view(L * B, V)\n trg_eos = trg_eos.view(L * B)\n loss_s2t = self.loss_fun(output_s2t, trg_eos)\n\n # target2source loss\n L, B, V = output_t2s.size()\n output_t2s = output_t2s.view(L * B, V)\n src_eos = src_eos.view(L * B)\n loss_t2s = self.loss_fun(output_t2s, src_eos)\n\n return labels_s2t, labels_t2s, loss_s2t, loss_t2s, loss_c\n\ndef main():\n parser = argparse.ArgumentParser(description='Custom_loop PyTorch')\n parser.add_argument('--mode', type=str,\n choices=['None', 'propose2', 'propose_soft', 'propose_hard'],\n default=None, const=None, nargs='+',\n help='None / propose2 / propose_soft, propose_hard')\n parser.add_argument('--hiddensize', type=int, default=256,\n help='number of node in hidden layer')\n parser.add_argument('--batchsize', '-b', type=int, default=50,\n help='Number of images in each mini-batch')\n parser.add_argument('--epoch', '-e', type=int, default=20,\n help='Number of sweeps over the dataset to train')\n parser.add_argument('--size', '-s', type=str, default='100k',\n help='Size of datasets')\n parser.add_argument('--vocab-size', type=int, default=16000,\n help='Upper limit of dictionary size')\n parser.add_argument('--freq', type=int, default=1,\n help='Lower limit of word frequency registered in dictionary')\n parser.add_argument('--gradclip', type=int, default=1.0,\n help='Grad clipping Norm')\n parser.add_argument('--no-bpe', action='store_true',\n help='If no use BPE, To enable this flag')\n parser.add_argument('--lang', type=str, default='ja-en',\n help='Language of parallel corpus')\n parser.add_argument('--gpu', '-g', type=int, default=-1,\n help='GPU ID (negative value indicates CPU)')\n parser.add_argument('--out', '-o', type=str, default='result',\n help='Directory to output the result')\n parser.add_argument('--load-last', action='store_true',\n help='load last.m, last.o')\n parser.add_argument('--model', '-m', type=str, default=None,\n help='model')\n parser.add_argument('--interval', '-i', type=int, default=None,\n help='Log interval')\n args = parser.parse_args()\n\n log('GPU: {}'.format(args.gpu))\n log('# Minibatch-size: {}'.format(args.batchsize))\n log('# epoch: {}'.format(args.epoch))\n\n # Path to data\n root = Path('Data')\n Path(args.out).mkdir(parents=True, exist_ok=True)\n\n # Log param\n log(args)\n log(args, file_name=Path(args.out) / 'param.txt')\n\n # Setup a GPU\n if args.gpu >= 0:\n # Make a speciied GPU current\n device = torch.device('cuda:{}'.format(args.gpu))\n else:\n device = torch.device('cpu')\n\n # Load the dataset\n data = Data(root, args.size, args.lang, args.batchsize, use_bpe=not args.no_bpe,\n vocab_size=args.vocab_size, min_freq=args.freq, device=device)\n data.make_dataset(Path(args.out), logger=log)\n train_iter = data.train_iter\n val_iter = data.val_iter\n test_iter = data.test_iter\n source_vocab_size = len(data.TEXT_src.vocab)\n target_vocab_size = len(data.TEXT_trg.vocab)\n log('vocab size source:{}, target:{}'.format(source_vocab_size, target_vocab_size))\n\n # Setup a Seq2Seq\n source2target = Seq2Seq(source_vocab_size, target_vocab_size, args.hiddensize)\n target2source = Seq2Seq(target_vocab_size, source_vocab_size, args.hiddensize)\n\n # Select constraint\n args.mode = args.mode[0] if args.mode is not None else None\n if args.mode == 'propose2':\n from constraint import Map\n constraint = Map()\n elif args.mode == 'propose_soft':\n from constraint import MapSoft\n constraint = MapSoft()\n elif args.mode == 'propose_hard':\n from constraint import MapHard\n constraint = MapHard()\n else:#args.mode == 'None':\n constraint = None\n\n # Setup a model\n model = Classifier(source2target, target2source, constraint)\n if args.model is not None:\n cp_path = Path(args.model)\n if cp_path.exists():\n check_point = torch.load(cp_path)\n model.load_state_dict(check_point['model'], strict=False)\n model.to(device=device)\n\n # Setup an optimizer\n optimizer_s2t = optim.Adam(source2target.parameters())\n optimizer_t2s = optim.Adam(target2source.parameters())\n if constraint is not None and args.mode != 'propose2':\n optimizer_map = optim.Adam(model.constraint.parameters())\n else:\n optimizer_map = None\n\n # Setup Logger\n start_time = datetime.now()\n train_loss = Logging()\n train_tmp_loss = Logging()\n val_loss = Logging()\n logger = Logging()\n start_epoch = 0\n if args.load_last:\n if logger.load_log(file_name=Path(args.out) / 'log.json'):\n start_epoch = max(map(int, logger._log.keys()))\n # Check pointからロード\n cp_path = Path(args.out) / 'epoch_{}.cp'.format(start_epoch)\n if cp_path.exists():\n check_point = torch.load(cp_path)\n model.load_state_dict(check_point['model'])\n optimizer_s2t.load_state_dict(check_point['opt_s2t'])\n optimizer_t2s.load_state_dict(check_point['opt_t2s'])\n if optimizer_map is not None:\n optimizer_map.load_state_dict(check_point['opt_map'])\n else:\n # Check pointがない場合(互換性のため、あとで消す)\n try:\n #直前のモデルをロード\n model.load_state_dict(\n torch.load(Path(args.out) / 'epoch_{}.m'.format(start_epoch)))\n optimizer_s2t.load_state_dict(\n torch.load(Path(args.out) / 'last_s2t_{}.o'.format(start_epoch)))\n optimizer_t2s.load_state_dict(\n torch.load(Path(args.out) / 'last_t2s_{}.o'.format(start_epoch)))\n if optimizer_map is not None:\n optimizer_map.load_state_dict(\n torch.load(Path(args.out) / 'last_map{}.o'.format(start_epoch)))\n except:\n # saveに失敗している場合は,さらに一つ前のモデルをロード\n log(\"faild load epoch {}'s model\".format(start_epoch))\n start_epoch = start_epoch - 1\n model.load_state_dict(\n torch.load(Path(args.out) / 'epoch_{}.m'.format(start_epoch)))\n optimizer_s2t.load_state_dict(\n torch.load(Path(args.out) / 'last_s2t_{}.o'.format(start_epoch)))\n optimizer_t2s.load_state_dict(\n torch.load(Path(args.out) / 'last_t2s_{}.o'.format(start_epoch)))\n if optimizer_map is not None:\n optimizer_map.load_state_dict(\n torch.load(Path(args.out) / 'last_map{}.o'.format(start_epoch)))\n # Seve the last model\n epoch = start_epoch\n status = {\n 'epoch': epoch,\n 'model': model.state_dict(),\n 'opt_s2t': optimizer_s2t.state_dict(),\n 'opt_t2s': optimizer_t2s.state_dict(),\n }\n if optimizer_map is not None:\n status['opt_map'] = optimizer_map.state_dict()\n\n torch.save(status, Path(args.out) / 'epoch_{}.cp'.format(epoch))\n log('Done load log.json: Start learning from epoch {}'.format(start_epoch+1))\n else:\n log('Not found log.json: Start learning from epoch 0')\n start_epoch = 0\n\n # Training loop\n for e in range(start_epoch, args.epoch):\n epoch = str(e + 1) #jsonのキーが文字列のため\n # Train\n model.train()\n for i, batch in tqdm(enumerate(train_iter), desc='Iteration'):\n iteration = i + 1\n # Init Grad\n optimizer_s2t.zero_grad()\n optimizer_t2s.zero_grad()\n if optimizer_map is not None: optimizer_map.zero_grad()\n # Forward computation\n _, _, loss_s2t, loss_t2s, loss_map = model(batch.src, batch.trg)\n # Log\n train_loss.log('loss_s2t', loss_s2t.item() / len(train_iter))\n train_loss.log('loss_t2s', loss_t2s.item() / len(train_iter))\n if optimizer_map is not None: train_loss.log('loss_map', loss_map.item() / len(train_iter))\n if args.interval is not None:\n train_tmp_loss.log('loss_s2t', loss_s2t.item() / args.interval)\n train_tmp_loss.log('loss_t2s', loss_t2s.item() / args.interval)\n if optimizer_map is not None:\n train_tmp_loss.log('loss_map', loss_map.item() / args.interval)\n \n # Backword loss\n if optimizer_map is not None:\n loss_t2s.backward(retain_graph=True)\n loss_s2t.backward(retain_graph=True)\n loss_map.backward()\n else:\n loss_t2s.backward()\n loss_s2t.backward()\n\n # Grad cliping\n nn.utils.clip_grad_norm_(source2target.parameters(), args.gradclip)\n nn.utils.clip_grad_norm_(target2source.parameters(), args.gradclip)\n if optimizer_map is not None: nn.utils.clip_grad_norm_(constraint.parameters(), args.gradclip)\n\n # Update parameters\n optimizer_s2t.step()\n optimizer_t2s.step()\n if optimizer_map is not None: optimizer_map.step()\n if args.interval is not None and iteration % args.interval == 0:\n # Log\n train_tmp_loss.print_log(prefix='epoch: {}\\t'.format(epoch))\n train_tmp_loss.reset(('loss_s2t', 'loss_t2s'))\n if optimizer_map is not None: train_tmp_loss.reset('loss_map')\n\n optimizer_s2t.zero_grad()\n optimizer_t2s.zero_grad()\n\n # Validation\n model.eval()\n for batch in val_iter:\n # Forward computation with no_grad()\n with torch.no_grad():\n _, _, loss_s2t, loss_t2s, loss_map = model(batch.src, batch.trg)\n # Log\n val_loss.log('loss_s2t', loss_s2t.item() / len(val_iter))\n val_loss.log('loss_t2s', loss_t2s.item() / len(val_iter))\n if optimizer_map is not None: val_loss.log('loss_map', loss_map.item() / len(val_iter))\n\n # BLEU (Val)\n hyp_s2t, ref_s2t, hyp_t2s, ref_t2s = [], [], [], []\n for batch in val_iter:\n # Forward computation with no_grad()\n with torch.no_grad():\n labels_s2t, labels_t2s = model(batch.src, batch.trg, train=False)\n # target2source\n hyp_s2t.extend(batch_label2word(labels_s2t, data.TEXT_trg, args.no_bpe))\n ref_s2t.extend(batch_label2word(batch.trg[0], data.TEXT_trg, args.no_bpe))\n # target2source\n hyp_t2s.extend(batch_label2word(labels_t2s, data.TEXT_src, args.no_bpe))\n ref_t2s.extend(batch_label2word(batch.src[0], data.TEXT_src, args.no_bpe))\n\n ref_s2t = [[line] for line in ref_s2t]\n ref_t2s = [[line] for line in ref_t2s]\n # Calcurate bleu\n bleu_s2t = calc_bleu_score(hyp_s2t, ref_s2t)\n bleu_t2s = calc_bleu_score(hyp_t2s, ref_t2s)\n\n hyp_s2t, hyp_t2s = [], []\n # BLEU (test)\n for batch in test_iter:\n # Forward computation with no_grad()\n with torch.no_grad():\n labels_s2t, labels_t2s = model(batch.src, batch.trg, train=False)\n # target2source\n hyp_s2t.extend(batch_label2word(labels_s2t, data.TEXT_trg, args.no_bpe))\n # target2source\n hyp_t2s.extend(batch_label2word(labels_t2s, data.TEXT_src, args.no_bpe))\n\n # Output system translation\n lang = args.lang.split('-')\n output_translation(\n hyp_s2t, file_name=Path(args.out) / 'output_epoch_{}.{}'.format(epoch, lang[1]))\n output_translation(\n hyp_t2s, file_name=Path(args.out) / 'output_epoch_{}.{}'.format(epoch, lang[0]))\n\n # Log\n logger.log('train/loss(s2t)', train_loss.get_log('loss_s2t'), epoch=epoch)\n logger.log('train/loss(t2s)', train_loss.get_log('loss_t2s'), epoch=epoch)\n if optimizer_map is not None: logger.log('train/loss(map)', train_loss.get_log('loss_map'), epoch=epoch)\n logger.log('val/loss(s2t)', val_loss.get_log('loss_s2t'), epoch=epoch)\n logger.log('val/loss(t2s)', val_loss.get_log('loss_t2s'), epoch=epoch)\n if optimizer_map is not None: logger.log('val/loss(map)', val_loss.get_log('loss_map'), epoch=epoch)\n logger.log('bleu(s2t)', bleu_s2t, epoch=epoch)\n logger.log('bleu(t2s)', bleu_t2s, epoch=epoch)\n current_time = datetime.now()\n elapsed_time = (current_time - start_time).total_seconds()\n logger.log('elapsed_time', elapsed_time, epoch=epoch)\n\n # Reset log of loss\n train_loss.reset()\n val_loss.reset()\n\n # Seve the last model\n status = {\n 'epoch': epoch,\n 'model': model.state_dict(),\n 'opt_s2t': optimizer_s2t.state_dict(),\n 'opt_t2s': optimizer_t2s.state_dict(),\n }\n if optimizer_map is not None:\n status['opt_map'] = optimizer_map.state_dict()\n\n torch.save(status, Path(args.out) / 'epoch_{}.cp'.format(epoch))\n \n \"\"\"\n with open(Path(args.out) / 'epoch_{}.m'.format(epoch), 'wb') as f:\n torch.save(model.state_dict(), f)\n with open(Path(args.out) / 'last_s2t_{}.o'.format(epoch), 'wb') as f:\n torch.save(optimizer_s2t.state_dict(), f)\n with open(Path(args.out) / 'last_t2s_{}.o'.format(epoch), 'wb') as f:\n torch.save(optimizer_t2s.state_dict(), f)\n if optimizer_map is not None:\n with open(Path(args.out) / 'last_map{}.o'.format(epoch), 'wb') as f:\n torch.save(optimizer_map.state_dict(), f)\n \"\"\"\n # print log\n logger.print_log(epoch=epoch)\n # log file\n logger.print_log(file_name=Path(args.out) / 'log.json')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":16552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"521019382","text":"# mira.py\n# -------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\n# Mira implementation\nimport util\nimport math\nPRINT = True\n\nclass MiraClassifier:\n \"\"\"\n Mira classifier.\n\n Note that the variable 'datum' in this code refers to a counter of features\n (not to a raw samples.Datum).\n \"\"\"\n def __init__( self, legalLabels, max_iterations):\n self.legalLabels = legalLabels\n self.type = \"mira\"\n self.automaticTuning = False\n self.C = 0.001\n self.legalLabels = legalLabels\n self.max_iterations = max_iterations\n self.initializeWeightsToZero()\n\n def initializeWeightsToZero(self):\n \"Resets the weights of each label to zero vectors\"\n self.weights = {}\n for label in self.legalLabels:\n self.weights[label] = util.Counter() # this is the data-structure you should use\n\n def train(self, trainingData, trainingLabels, validationData, validationLabels):\n \"Outside shell to call your method. Do not modify this method.\"\n\n self.features = trainingData[0].keys() # this could be useful for your code later...\n\n if (self.automaticTuning):\n Cgrid = [0.002, 0.004, 0.008]\n else:\n Cgrid = [self.C]\n\n return self.trainAndTune(trainingData, trainingLabels, validationData, validationLabels, Cgrid)\n\n def calculate(self, validationData,validationLabels):\n correctness1 = 0\n correctness = 0\n guesses = self.classify(validationData)\n for i,j in enumerate(guesses):\n correctness += (validationLabels[i] == j and 1.0 or 0.0)\n acc = (correctness/len(guesses))\n return acc\n\n\n def compute_tau(self, W1, w2, y, c):\n tau = min (c, (((W1-w2)*y + 1.0)/ (2.0 *(math.sqrt(y*y)))))\n return tau \n\n def changey(self, y, tau):\n y.divideAll(1.0/tau)\n return y\n \n\n def trainAndTune(self, trainingData, trainingLabels, validationData, validationLabels, Cgrid):\n \"\"\"\n This method sets self.weights using MIRA. Train the classifier for each value of C in Cgrid,\n then store the weights that give the best accuracy on the validationData.\n\n Use the provided self.weights[label] data structure so that\n the classify method works correctly. Also, recall that a\n datum is a counter from features to values for those features\n representing a vector of values.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n weights = util.Counter()\n bestAccuracy = None\n score = util.Counter()\n for c in Cgrid:\n weights = self.weights\n for i in range(self.max_iterations):\n for t,y in enumerate(trainingData):\n #print self.legalLabels\n for l1 in self.legalLabels:\n \n #print \"weight[c][l]\", weights[l1]\n #print \"print trainingData[t]\",trainingData[t]\n #print \"print trainingDLabels[t]\",trainingLabels[t]\n score[l1] = y*weights[l1]\n maxScore = score.argMax()\n if not (maxScore == trainingLabels[t]): \n Wp = weights[maxScore]\n w = weights[trainingLabels[t]]\n \n tau = min(c, ((Wp-w)*y+1.0)/((y*y)*2))\n for f in self.features:\n weights[trainingLabels[t]][f] += tau*y[f]\n weights[maxScore][f] -= tau*y[f]\n\n if self.calculate(validationData, validationLabels) > bestAccuracy or bestAccuracy is None:\n bestAccuracy = self.calculate(validationData, validationLabels)\n bestWeights = weights\n\n self.weights = bestWeights\n\n def classify(self, data ):\n \"\"\"\n Classifies each datum as the label that most closely matches the prototype vector\n for that label. See the project description for details.\n\n Recall that a datum is a util.counter...\n \"\"\"\n guesses = []\n for datum in data:\n vectors = util.Counter()\n for l in self.legalLabels:\n vectors[l] = self.weights[l] * datum\n guesses.append(vectors.argMax())\n return guesses\n\n\n","sub_path":"chandrika2311-master/assignment5/classification/mira.py","file_name":"mira.py","file_ext":"py","file_size_in_byte":4937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"19299114","text":"import os\nimport logging\nimport argparse\nimport time\nimport datetime\nimport random\n\nimport tensorflow as tf\nimport trfl\nfrom trfl import indexing_ops\nimport numpy as np\nimport pandas as pd\nimport torch\nimport matplotlib.pyplot as plt\n\nfrom utils import *\nfrom NextItNetModules import *\n\n\nclass Agent:\n\tdef __init__(self, args, name='Agent', dqda_clipping=None, clip_norm=False, max_action=1.0):\n\t\tself.args = args\n\t\tself.name = name\n\t\tself.hw = 10\n\t\tself.hidden_size = args.hidden_factor\n\t\tself.item_num = args.max_iid + 1\n\t\tself.is_training = tf.placeholder(tf.bool, shape=())\n\n\t\twith tf.variable_scope(self.name):\n\t\t\tself.all_embeddings = self.initialize_embeddings()\n\n\t\t\tself.inputs = tf.placeholder(tf.int32, [None, self.hw],name='inputs')\n\t\t\tself.len_state = tf.placeholder(tf.int32, [None],name='len_state')\n\t\t\tself.discount = tf.placeholder(tf.float32, [None] , name=\"discount\")\n\t\t\tself.reward = tf.placeholder(tf.float32, [None], name='reward')\n\t\t\tself.target = tf.placeholder(tf.float32, [None],name='target')\n\n\t\t\t# ranking model\n\t\t\tself.target_items = tf.placeholder(tf.int32, [None], name='target_items')\n\n\t\t\tmask = tf.expand_dims(tf.to_float(tf.not_equal(self.inputs, self.item_num)), -1)\n\n\t\t\t# self.input_emb=tf.nn.embedding_lookup(all_embeddings['state_embeddings'],self.inputs)\n\t\t\tself.model_para = {\n\t\t\t\t'dilated_channels': 64, # larger is better until 512 or 1024\n\t\t\t\t'dilations': [1, 2, 1, 2, 1, 2, ], # YOU should tune this hyper-parameter, refer to the paper.\n\t\t\t\t'kernel_size': 3,\n\t\t\t}\n\n\t\t\tcontext_embedding = tf.nn.embedding_lookup(self.all_embeddings['state_embeddings'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t self.inputs)\n\t\t\tcontext_embedding *= mask\n\n\t\t\tdilate_output = context_embedding\n\t\t\tfor layer_id, dilation in enumerate(self.model_para['dilations']):\n\t\t\t\tdilate_output = nextitnet_residual_block(dilate_output, dilation,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlayer_id, self.model_para['dilated_channels'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.model_para['kernel_size'], causal=True, train=self.is_training)\n\t\t\t\tdilate_output *= mask\n\n\t\t\tself.state_hidden = extract_axis_1(dilate_output, self.len_state - 1)\n\t\t\tself.action_size = int(self.state_hidden.shape[-1])\n\n\t\t\t# ddpg\n\t\t\tactor = eval(args.actor_layers)\n\t\t\tactor.append(self.action_size)\n\t\t\twith tf.variable_scope(\"actor\"):\n\t\t\t\tself.actor_output = mlp(self.state_hidden, self.is_training, hidden_sizes=actor, \n\t\t\t\t\tdropout_rate=args.atten_dropout_rate, \n\t\t\t\t\tl2=tf.contrib.layers.l2_regularizer(args.weight_decay))\n\n\t\t\tself.actor_out_ = self.actor_output * max_action\n\t\t\t# learnable\n\t\t\t# self.alpha = tf.Variable(np.array([max_action for _ in range(self.action_size)], dtype=np.float32), name=\"a\")\n\t\t\t# self.alpha = tf.Variable(max_action, name=\"a\")\n\t\t\t# self.actor_out_ = self.actor_output * self.alpha\n\n\t\t\t# learnable A (MLP)\n\t\t\t# A = tf.contrib.layers.fully_connected(tf.concat([self.actor_output, self.state_hidden], axis=1), 1,\n\t\t\t# \tactivation_fn=None,\n\t\t\t# \tweights_regularizer=tf.contrib.layers.l2_regularizer(args.weight_decay))\n\t\t\t# self.actor_out_ = self.actor_output * A\n\n\t\t\tself.critic_input = tf.concat([self.actor_out_, self.state_hidden], axis=1)\n\t\t\tcritic = eval(args.critic_layers)\n\t\t\tcritic.append(1)\n\t\t\twith tf.variable_scope(\"critic\"):\n\t\t\t\tself.critic_output = mlp(self.critic_input, self.is_training, hidden_sizes=critic, \n\t\t\t\t\toutput_activation=None, dropout_rate=args.atten_dropout_rate, \n\t\t\t\t\tl2=tf.contrib.layers.l2_regularizer(args.weight_decay))\n\n\t\t\tself.dpg_return = trfl.dpg(self.critic_output, self.actor_out_, \n\t\t\t\tdqda_clipping=dqda_clipping, clip_norm=clip_norm)\n\n\t\t\tself.actor_loss = tf.reduce_mean(self.dpg_return.loss)\n\t\t\tself.actor_optim = tf.train.AdamOptimizer(args.alr).minimize(self.actor_loss)\n\n\t\t\tself.td_return = trfl.td_learning(tf.squeeze(self.critic_output), self.reward, \n\t\t\t\tself.discount, self.target)\n\t\t\tself.critic_loss = tf.reduce_mean(self.td_return.loss)\n\t\t\tself.critic_optim = tf.train.AdamOptimizer(args.clr).minimize(self.critic_loss)\n\n\t\t\t# NextItNet\n\t\t\t# self.actions = tf.placeholder(tf.float32, [None, self.action_size], name='actions')\n\t\t\t# self.ranking_model_input = self.actions + self.state_hidden\n\t\t\tself.ranking_model_input = self.actor_out_ + self.state_hidden\n\n\t\t\tself.logits = tf.contrib.layers.fully_connected(self.ranking_model_input, self.item_num,\n\t\t\t\tactivation_fn=None,\n\t\t\t\tweights_regularizer=tf.contrib.layers.l2_regularizer(args.weight_decay))\n\n\t\t\tself.ce_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.target_items,\n\t\t\t\tlogits=self.logits)\n\t\t\tself.ranking_model_loss = tf.reduce_mean(self.ce_loss)\n\t\t\tself.model_optim = tf.train.AdamOptimizer(args.mlr).minimize(self.ranking_model_loss)\n\n\tdef initialize_embeddings(self):\n\t\tall_embeddings = dict()\n\t\tstate_embeddings= tf.Variable(tf.random_normal([self.item_num+1, self.hidden_size], 0.0, 0.01),\n\t\t\tname='state_embeddings')\n\t\tall_embeddings['state_embeddings']=state_embeddings\n\t\treturn all_embeddings\n\n\tdef get_qnetwork_variables(self):\n\t\treturn [t for t in tf.trainable_variables() if t.name.startswith(self.name)]\n\n\nclass Run(object):\n\tdef __init__(self, args, main_agent, target_agent):\n\t\tsuper(Run, self).__init__()\n\t\tself.args = args\n\t\tself.main_agent = main_agent\n\t\tself.target_agent = target_agent\n\t\tself.target_network_update_ops = trfl.update_target_variables(target_agent.get_qnetwork_variables(), \n\t\t\tmain_agent.get_qnetwork_variables(), tau=args.tau)\n\t\tself.copy_weight = trfl.update_target_variables(target_agent.get_qnetwork_variables(), \n\t\t\tmain_agent.get_qnetwork_variables(), tau=1.0)\n\n\t\tself.topk = [int(x) for x in args.topk.split(',')]\n\t\tself.replay_buffer = pd.read_pickle(os.path.join(args.base_data_dir, 'replay_buffer.df'))\n\n\tdef sample_data(self):\n\t\tbatch = self.replay_buffer.sample(n=args.batch_size).to_dict()\n\t\tstate = list(batch['state'].values())\n\t\tlen_state = list(batch['len_state'].values())\n\t\tnext_state = list(batch['next_state'].values())\n\t\tlen_next_states = list(batch['len_next_states'].values())\n\t\ttarget_items = list(batch['action'].values())\n\t\tis_done = list(batch['is_done'].values())\n\t\tis_buy = list(batch['is_buy'].values())\n\t\treturn state, len_state, next_state, len_next_states, target_items, is_done, is_buy\n\n\tdef cal_rewards(self, logits, target_items, is_buy):\n\t\tlogits = torch.tensor(logits)\n\t\t_, rankings = logits.topk(self.args.reward_top)\n\t\trankings = rankings.tolist()\t# (batch, topk)\n\t\trewards = []\n\t\tfor target_iid, rec_list, buy in zip(target_items, rankings, is_buy):\n\t\t\tndcg = 0.0\n\t\t\tfor i, iid in enumerate(rec_list):\n\t\t\t\tif iid == target_iid:\n\t\t\t\t\tndcg = 1.0 / np.log2(i + 2.0).item()\n\t\t\t\t\tbreak\n\t\t\trewards.append(self.args.buy_weight * ndcg if buy == 1 else ndcg)\n\t\treturn rewards\n\n\tdef state_trans(self, rewards, state, next_state, len_state, len_next_states):\n\t\ttrue_next_state, true_next_state_len = [], []\n\t\tfor r, s, s_, sl, sl_ in zip(rewards, state, next_state, len_state, len_next_states):\n\t\t\tif r == 0:\n\t\t\t\ttrue_next_state.append(s)\n\t\t\t\ttrue_next_state_len.append(sl)\n\t\t\telse:\n\t\t\t\ttrue_next_state.append(s_)\n\t\t\t\ttrue_next_state_len.append(sl_)\n\t\treturn true_next_state, true_next_state_len\n\n\tdef train(self):\n\t\tnum_rows = self.replay_buffer.shape[0]\n\t\tnum_batches = int(num_rows / self.args.batch_size)\n\t\tmax_ndcg_and_epoch = [[0, 0, 0] for _ in self.args.topk.split(',')]\t# (ng_click, ng_purchase, step)\n\t\ttotal_step = 0\n\n\t\tgpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=self.args.mem_ratio)\n\t\twith tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n\t\t\tsess.run(tf.global_variables_initializer())\n\t\t\tsess.graph.finalize()\n\t\t\tsess.run(self.copy_weight)\t\t# copy weights\n\t\t\tdiscount = [self.args.gamma] * self.args.batch_size\n\t\t\tfor i_epoch in range(self.args.epoch):\n\t\t\t\tfor j in range(num_batches):\n\t\t\t\t\tstate, len_state, next_state, len_next_states, target_items, is_done, is_buy = self.sample_data()\n\t\t\t\t\tactions = sess.run(self.main_agent.actor_out_, feed_dict={\n\t\t\t\t\t\tself.main_agent.inputs: state, \n\t\t\t\t\t\tself.main_agent.len_state: len_state,\n\t\t\t\t\t\tself.main_agent.is_training: False})\n\n\t\t\t\t\t# add noise\n\t\t\t\t\tnoise = np.random.normal(0, self.args.noise_var, size=self.main_agent.action_size).clip(-self.args.noise_clip, self.args.noise_clip)\n\n\t\t\t\t\tactions = (actions + noise).clip(-self.args.max_action, self.args.max_action)\n\t\t\t\t\t# learnable\n\t\t\t\t\t# actions = (actions + noise).clip(-1, 1)\n\n\t\t\t\t\tce_loss, ranking_model_loss, _ = sess.run([\n\t\t\t\t\t\t# self.main_agent.logits, \n\t\t\t\t\t\tself.main_agent.ce_loss,\n\t\t\t\t\t\tself.main_agent.ranking_model_loss, \n\t\t\t\t\t\tself.main_agent.model_optim], \n\t\t\t\t\t\tfeed_dict={\n\t\t\t\t\t\tself.main_agent.inputs: state, \n\t\t\t\t\t\tself.main_agent.len_state: len_state,\n\t\t\t\t\t\tself.main_agent.actor_out_: actions,\n\t\t\t\t\t\t# self.main_agent.actions: actions,\n\t\t\t\t\t\tself.main_agent.target_items: target_items,\n\t\t\t\t\t\tself.main_agent.is_training: True})\n\n\t\t\t\t\tif self.args.reward == 'ndcg':\n\t\t\t\t\t\t# target logits\n\t\t\t\t\t\tlogits = sess.run(self.target_agent.logits,\n\t\t\t\t\t\t\tfeed_dict={\n\t\t\t\t\t\t\tself.target_agent.inputs: state, \n\t\t\t\t\t\t\tself.target_agent.len_state: len_state,\n\t\t\t\t\t\t\tself.target_agent.actor_out_: actions,\n\t\t\t\t\t\t\t# self.target_agent.actions: actions,\n\t\t\t\t\t\t\tself.target_agent.is_training: False})\n\t\t\t\t\t\trewards = self.cal_rewards(logits, target_items, is_buy)\n\t\t\t\t\t\t# true_next_state, true_next_state_len = self.state_trans(rewards, state, next_state, len_state, len_next_states)\n\t\t\t\t\telif self.args.reward == 'loss':\n\t\t\t\t\t\t# ce_loss = sess.run(self.target_agent.ce_loss, feed_dict={\n\t\t\t\t\t\t# \tself.target_agent.inputs: state, \n\t\t\t\t\t\t# \tself.target_agent.len_state: len_state,\n\t\t\t\t\t\t# \tself.target_agent.actor_out_: actions,\n\t\t\t\t\t\t# \t# self.target_agent.actions: actions,\n\t\t\t\t\t\t# \tself.target_agent.target_items: target_items,\n\t\t\t\t\t\t# \tself.target_agent.is_training: False})\n\t\t\t\t\t\trewards = loss_reward(ce_loss)\n\t\t\t\t\telif self.args.reward == 'hit':\n\t\t\t\t\t\t# target logits\n\t\t\t\t\t\tlogits = sess.run(self.target_agent.logits, feed_dict={\n\t\t\t\t\t\t\tself.target_agent.inputs: state, \n\t\t\t\t\t\t\tself.target_agent.len_state: len_state,\n\t\t\t\t\t\t\tself.target_agent.actor_out_: actions,\n\t\t\t\t\t\t\t# self.target_agent.actions: actions,\n\t\t\t\t\t\t\tself.target_agent.is_training: False})\n\t\t\t\t\t\trewards = hit_reward(self.args, logits, target_items)\n\t\t\t\t\t\t# true_next_state, true_next_state_len = self.state_trans(rewards, state, next_state, len_state, len_next_states)\n\n\t\t\t\t\ttarget_v = sess.run(self.target_agent.critic_output, feed_dict={\n\t\t\t\t\t\tself.target_agent.inputs: next_state,\n\t\t\t\t\t\tself.target_agent.len_state: len_next_states,\n\t\t\t\t\t\t# self.target_agent.inputs: true_next_state,\n\t\t\t\t\t\t# self.target_agent.len_state: true_next_state_len,\n\n\t\t\t\t\t\tself.target_agent.is_training: False})\n\t\t\t\t\ttarget_v = target_v.squeeze()\n\t\t\t\t\tfor index in range(self.args.batch_size):\n\t\t\t\t\t\tif is_done[index]:\n\t\t\t\t\t\t\ttarget_v[index] = 0.0\n\n\t\t\t\t\tcritic_loss, _ = sess.run([self.main_agent.critic_loss, \n\t\t\t\t\t\tself.main_agent.critic_optim], \n\t\t\t\t\t\tfeed_dict={self.main_agent.inputs:state, \n\t\t\t\t\t\tself.main_agent.len_state:len_state,\n\t\t\t\t\t\tself.main_agent.actor_out_: actions, \n\t\t\t\t\t\tself.main_agent.reward: rewards,\n\t\t\t\t\t\tself.main_agent.discount: discount,\n\t\t\t\t\t\tself.main_agent.target: target_v,\n\t\t\t\t\t\tself.main_agent.is_training: True})\n\t\t\t\t\tactor_loss, _ = sess.run([self.main_agent.actor_loss, self.main_agent.actor_optim],\n\t\t\t\t\t\tfeed_dict={self.main_agent.inputs: state, \n\t\t\t\t\t\tself.main_agent.len_state: len_state,\n\t\t\t\t\t\tself.main_agent.is_training: True})\n\t\t\t\t\tsess.run(self.target_network_update_ops)\t\t# update target net\n\n\t\t\t\t\ttotal_step += 1\n\t\t\t\t\tif (total_step == 1) or (total_step % 200 == 0):\n\t\t\t\t\t\taver_reward = round(np.array(rewards).mean().item(), 5)\n\t\t\t\t\t\tranking_model_loss, actor_loss, critic_loss = round(ranking_model_loss.item(), 5), round(actor_loss.item(), 5), round(critic_loss.item(), 5)\n\t\t\t\t\t\tinfo = f\"epoch:{i_epoch} Step:{total_step}, aver reward:{aver_reward}, ranking model loss:{ranking_model_loss}, actor loss:{actor_loss}, critic loss:{critic_loss}\"\n\t\t\t\t\t\tprint(info)\n\t\t\t\t\t\tlogging.info(info)\n\t\t\t\t\tif (total_step >= self.args.start_eval) and (total_step % self.args.eval_interval == 0):\n\t\t\t\t\t\tt1 = time.time()\n\t\t\t\t\t\t# debug\n\t\t\t\t\t\t# evaluate_with_actions(self.args, self.main_agent, sess, max_ndcg_and_epoch, total_step, logging)\n\t\t\t\t\t\tevaluate_multi_head(self.args, self.main_agent, sess, max_ndcg_and_epoch, total_step, logging)\n\t\t\t\t\t\tt2 = time.time()\n\t\t\t\t\t\tprint(f'Time:{t2 - t1}')\n\t\t\t\t\t\tlogging.info(f'Time:{t2 - t1}')\n\n\ndef main(args):\n\ttf.reset_default_graph()\n\tmain_agent = Agent(args, name='train', max_action=args.max_action)\n\ttarget_agent = Agent(args, name='target', max_action=args.max_action)\n\n\trun = Run(args, main_agent, target_agent)\n\trun.train()\n\n\ndef parse_args():\n\tbase_data_dir = '../../data/'\n\tparser = argparse.ArgumentParser(description=\"NextItNet DDPG\")\n\tparser.add_argument('--v', default=\"v\")\n\tparser.add_argument('--mode', default='valid')\n\tparser.add_argument('--seed', type=int, default=1)\n\tparser.add_argument('--base_log_dir', default=\"log/\")\n\tparser.add_argument('--base_data_dir', default=base_data_dir + 'kaggle-RL4REC')\n\tparser.add_argument('--topk', default='5,10,20')\n\n\tparser.add_argument('--epoch', type=int, default=100)\n\tparser.add_argument('--eval_interval', type=int, default=2000)\n\tparser.add_argument('--start_eval', type=int, default=2000)\n\tparser.add_argument('--eval_batch', type=int, default=10)\n\tparser.add_argument('--batch_size', type=int, default=256)\n\tparser.add_argument('--mlr', type=float, default=1e-3)\n\tparser.add_argument('--alr', type=float, default=5e-3)\n\tparser.add_argument('--clr', type=float, default=5e-3)\n\n\tparser.add_argument('--reward_top', type=int, default=20)\n\tparser.add_argument('--reward_click', type=float, default=1.0)\n\tparser.add_argument('--reward_buy', type=float, default=5.0)\n\n\tparser.add_argument('--max_iid', type=int, default=70851)\t# 0~70851\n\n\tparser.add_argument('--hidden_factor', type=int, default=64)\n\n\tparser.add_argument('--weight_decay', default=1e-4, type=float)\n\n\tparser.add_argument('--noise_var', type=float, default=0.01)\n\tparser.add_argument('--noise_clip', type=float, default=0.05)\n\tparser.add_argument('--tau', type=float, default=0.001)\n\tparser.add_argument('--gamma', type=float, default=0.5)\n\n\tparser.add_argument('--mem_ratio', type=float, default=0.2)\n\tparser.add_argument('--note', default=\"None......\")\n\tparser.add_argument('--cuda', default='0')\n\tparser.add_argument('--reward', default='ndcg')\n\n\tparser.add_argument('--atten_dropout_rate', type=float, default=0.1)\n\tparser.add_argument('--actor_layers', default=\"[]\")\n\tparser.add_argument('--critic_layers', default=\"[]\")\n\tparser.add_argument('--max_action', type=float, default=0.1)\n\n\tparser.add_argument('--init_r', type=float, default=-1.0)\n\tparser.add_argument('--buy_weight', type=float, default=5.0)\n\treturn parser.parse_args()\n\ndef init_log(args):\n\tif not os.path.exists(args.base_log_dir):\n\t\tos.makedirs(args.base_log_dir)\n\tstart = datetime.datetime.now()\n\tlogging.basicConfig(level = logging.INFO,\n\t\t\t\t\tfilename = args.base_log_dir + args.v + '-' + str(time.time()) + '.log',\n\t\t\t\t\tfilemode = 'a',\n\t\t\t\t\t)\n\tprint('start! '+str(start))\n\tlogging.info('start! '+str(start))\n\tlogging.info('Parameter:')\n\tlogging.info(str(args))\n\tlogging.info('\\n-------------------------------------------------------------\\n')\n\nif __name__ == '__main__':\n\targs = parse_args()\n\n\tos.environ['CUDA_VISIBLE_DEVICES'] = args.cuda\n\n\tif args.seed != -1:\n\t\trandom.seed(args.seed)\n\t\tnp.random.seed(args.seed)\n\t\ttf.set_random_seed(args.seed)\n\tinit_log(args)\n\tmain(args)","sub_path":"experiment/combineRL-TRFL/Kaggle/NexttNet_DDPG.py","file_name":"NexttNet_DDPG.py","file_ext":"py","file_size_in_byte":15396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"462419649","text":"from django.shortcuts import render\nfrom django.db.models import Sum, Count\nfrom django.conf import settings\n\nfrom inventario.models import Articulos\nfrom inventario.choices import CATEGORIAS, ESTADO\n\nimport pygal \nimport os\n\ndef stats_dashboard(request):\n if not Articulos.objects.all():\n return render(request, 'reportes/stats_vacio.html')\n else:\n aggregate = Articulos.objects.aggregate(valor_sum=Sum('valor'), moi_sum=Sum('moi'))\n total_art = Articulos.objects.all().count()\n available = Articulos.objects.filter(disponible=True).count()\n categories = Articulos.objects.values('categoria').annotate(Count('categoria')).order_by('-categoria__count')\n categories_display = [{'cat':CATEGORIAS[c['categoria']][1], 'count': c['categoria__count']} for c in categories]\n status = Articulos.objects.values('estado').annotate(Count('estado')).order_by('-estado__count')\n status_display = [{'status':ESTADO[s['estado']][1], 'count': s['estado__count']} for s in status]\n \n categories_chart = charts(categories_display) \n status_chart = charts(status_display)\n\n return render(request, 'reportes/stats_dashboard.html', {\n 'aggregate': aggregate,\n 'total_art': total_art,\n 'available': available,\n 'categories': categories_display,\n 'status': status_display,\n 'categories_chart': categories_chart,\n 'status_chart': status_chart,\n })\n \n\ndef charts(data):\n\n config = pygal.Config()\n css = os.path.join(settings.BASE_DIR, 'static/charts.css')\n config.css.append('file://' + css)\n pie_chart = pygal.Pie(disable_xml_declaration=True, config=config, legend_box_size=35, width=1100)\n \n for d in data:\n values = list(d.values())\n pie_chart.add(values[0], values[1])\n\n chart = pie_chart.render()\n\n return chart\n ","sub_path":"reportes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"69"} +{"seq_id":"43272403","text":"# coding: UTF-8\n\nimport lib_general as my_general\nimport customizer as my_cust\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nimport keras\n\n\nroot_path = my_general.root_path\ncurr_ticker = my_general.name_ticker\nspider = my_cust.spider\n\ncurr_path = root_path + 'Helper\\\\Classifier_politics_news\\\\'\n\n# ______________________________ Parser ______________________________\n\n\ndef get_html(url):\n r = my_general.requests.get(url)\n return r.text\n\n\ndef get_page_data(html, article_data):\n soup = my_general.BeautifulSoup(html, 'lxml')\n divs = soup.find('div', class_='list list-tags')\n ads = divs.find_all('div', class_='list-item', limit=10)\n\n article_data.clear()\n title = ''\n addit = ''\n href = ''\n time = ''\n for ad in ads:\n try:\n div = ad.find('div', class_='list-item__content').find('a',\n class_='list-item__title color-font-hover-only');\n title = div.text;\n\n href = div.get('href');\n\n title_picture = ad.find('div', class_='list-item__content') \\\n .find('a', class_='list-item__image') \\\n .find('picture') \\\n .find('img') \\\n .get('title')\n addit = title_picture;\n\n time = ad.find('div', class_='list-item__info') \\\n .find('div', class_='list-item__date').text\n time = time.split(', ')\n time = time[-1]\n\n data = {'title': title, 'additionally': addit, 'href': href, 'time': time}\n article_data.append(data)\n\n except:\n title = 'Error'\n addit = 'Error'\n href = 'Error'\n time = 'Error'\n\n return article_data\n\n\ndef main():\n print(\"\\n__________________ Politic news __________________\\n\")\n\n base_url = \"https://ria.ru/politics/\"\n article_data = []\n hash_news_p_n = []\n\n url_gen = base_url\n html = get_html(url_gen)\n article_data = get_page_data(html, article_data)\n\n # print(article_data.__len__())\n file_name = 'politics_news'\n my_general.write_data_json(article_data, curr_path, file_name)\n\n # _________________________________________________________________________________\n\n # Check on repeat\n\n hash_news_p_n = my_general.read_data_json(curr_path, 'hash_news_p_n')\n\n file_name = 'politics_news'\n if my_general.md5(curr_path + file_name + '.json') == hash_news_p_n[0][\"hash\"]:\n print(\"___ No the new politics news ___\")\n return\n\n # _________________________________________________________________________________\n\n count_sentences = article_data.__len__()\n count_words = 30\n count_charters = 30\n\n # _________________________________________________________________________________\n\n # Creating list of news + to Lower Case + delete ',' and '.'\n\n file_name = 'politics_news'\n news = my_general.read_data_json(curr_path, file_name)\n\n listSpider_E_N = []\n for item in news:\n listSpider_E_N.append(item)\n\n # print(listSpider_E_N)\n\n reg = my_general.re.compile('[^а-яА-Я -]')\n\n for obj in listSpider_E_N:\n obj['title'] = obj['title'].lower()\n obj['title'] = reg.sub('', obj['title'])\n obj['additionally'] = obj['additionally'].lower()\n obj['additionally'] = reg.sub('', obj['additionally'])\n # print(obj.title, obj.additionally, obj.href, obj.time, sep=' ')\n\n # _________________________________________________________________________________\n\n # Deleting repeats hrefs\n\n # print(listSpider_E_N[0].title,\n # listSpider_E_N[0].additionally,\n # listSpider_E_N[0].href,\n # listSpider_E_N[0].time,\n # sep=' ')\n\n idx_1 = 0\n idx_2 = 0\n for idx_1 in range(1, len(listSpider_E_N) - 1):\n ref_href = listSpider_E_N[idx_1]['href']\n idx_2 = idx_1 + 1\n for j in range(idx_2, len(listSpider_E_N) - 1):\n if listSpider_E_N[j]['href'] == ref_href:\n listSpider_E_N.remove(listSpider_E_N[j])\n\n # print(listSpider_E_N[0].title,\n # listSpider_E_N[0].additionally,\n # listSpider_E_N[0].href,\n # listSpider_E_N[0].time,\n # sep=' ')\n\n # _________________________________________________________________________________\n\n # Normalization the list of news\n\n morph = my_general.pymorphy2.MorphAnalyzer()\n\n for obj in listSpider_E_N:\n obj['title'] = (' '.join([morph.normal_forms(w)[0] for w in obj['title'].split()]))\n obj['additionally'] = (' '.join([morph.normal_forms(w)[0] for w in obj['additionally'].split()]))\n\n # _________________________________________________________________________________\n\n # Read reference words from json file\n\n # listParams_E_N = read_params_xlsx()\n file_name = 'params'\n listParams_E_N = my_general.read_data_json(curr_path, file_name)\n # write_params_json(listParams_E_N)\n # convert_json_to_xlsx()\n\n # _________________________________________________________________________________\n\n # Normalization reference words and rewrite json file\n #\n # morph = pymorphy2.MorphAnalyzer()\n #\n # newListParams_E_N = []\n # for obj in listParams_E_N:\n # new_name = ' '.join([morph.normal_forms(w)[0] for w in obj.get('name').split()])\n # new_synonyms = ' '.join([morph.normal_forms(w)[0] for w in obj.get('synonyms').split()])\n # params = {'name': new_country, 'synonyms': new_synonyms, 'impact': item.get('impact')}\n # newListParams_E_N.append(params)\n #\n # write_params_json(newListParams_E_N)\n # listParams_E_N = newListParams_E_N\n #\n # _________________________________________________________________________________\n\n # Get only text information from title and additionally\n\n newListSpider_E_N = []\n time_news = []\n for news in listSpider_E_N:\n newListSpider_E_N.append(news['title'] + ' ' + news['additionally'])\n time_news.append(news['time'])\n\n listSpider_E_N = newListSpider_E_N\n\n # _________________________________________________________________________________\n\n # Transform to array words\n\n listWords = []\n for news in listSpider_E_N:\n listWords.append(news.split())\n\n # _________________________________________________________________________________\n\n # Delete to array words\n\n for sentence in listWords:\n # print(sentence)\n for word in sentence:\n p = morph.parse(word)[0]\n if (p.tag.POS == 'ADVB') or\\\n (p.tag.POS == 'NPRO') or\\\n (p.tag.POS == 'PRED') or\\\n (p.tag.POS == 'PREP') or\\\n (p.tag.POS == 'CONJ') or\\\n (p.tag.POS == 'PRCL') or\\\n (p.tag.POS == 'INTJ'):\n sentence.remove(word)\n # print(sentence)\n # _________________________________________________________________________________\n\n # Transform to digital mode\n\n # print(listWords[0][0])\n\n newListWords = []\n listWordsToNN = my_general.np.zeros((count_sentences, count_words, count_charters))\n\n idx_sentence = 0\n for sentence in listWords:\n idx_word = 0\n for word in sentence:\n new_word = []\n idx_charter = 0\n for charter in word:\n idx = 0;\n # numbers\n for i in range(48, 57 + 1):\n if charter == chr(i):\n idx = i\n new_word.append(i)\n # Latin uppers\n for i in range(65, 90 + 1):\n if charter == chr(i):\n idx = i\n new_word.append(i)\n # Latin downs\n for i in range(97, 122 + 1):\n if charter == chr(i):\n idx = i\n new_word.append(i)\n # Cyrillic\n for i in range(1072, 1103 + 1):\n if charter == chr(i):\n idx = i\n new_word.append(i)\n\n listWordsToNN[idx_sentence][idx_word][idx_charter] = idx\n idx_charter = idx_charter + 1\n\n idx_word = idx_word + 1\n newListWords.append(new_word)\n\n idx_sentence = idx_sentence + 1\n\n # print(newListWords)\n\n # print(listWordsToNN[0])\n\n # _________________________________________________________________________________\n\n # Prepare weights\n # Finding reference words to array words\n\n # _________________________________________________________________________________\n\n # For Trainging NN\n\n # _________________________________________________________________________________\n\n # future_weigths = np.zeros(length_sentence, dtype=float)\n list_future_weigths = my_general.np.zeros((len(listWords), count_words), dtype=float)\n\n idx_word = 0\n idx_sentence = 0\n for header in listWords:\n # print(header)\n for obj in header:\n # print(obj.lower())\n for params in listParams_E_N:\n if my_general.fuzz.ratio(params.get('name'), obj.lower()) > 90:\n # print(\"I found of name! --->>> \" + str(obj))\n list_future_weigths[idx_sentence][idx_word] = float(params.get('impact'))\n break\n else:\n if len(params.get('synonyms')) >= 1:\n for it in params.get('synonyms'):\n if my_general.fuzz.ratio(str(it), str(obj.lower())) > 80:\n # print(\"I found of synonyms! --->>> \" + str(obj.lower()))\n list_future_weigths[idx_sentence][idx_word] = float(params.get('impact'))\n break\n idx_word = idx_word + 1\n idx_word = 0\n idx_sentence = idx_sentence + 1\n\n # print(list_future_weigths[len(listWords) - 2])\n # print(list_future_weigths)\n # _________________________________________________________________________________\n\n # Appending feature of applicants to list to json file\n # 1 day for remove from applicants.json\n # 240 it's 50% <- 1 day - 24 hours - 48 query * 10 news\n # 384 it's 80% <- 1 day - 24 hours - 48 query * 10 news\n # 3 day for appending to params.json\n\n border = 100\n\n idx_word = 0\n idx_sentence = 0\n for header in listWords:\n # print(header)\n for obj in header:\n if list_future_weigths[idx_sentence][idx_word] == 0:\n file_name = 'applicants'\n feature_list_applicants = my_general.read_data_json(curr_path, file_name)\n\n # find to feature_list_applicants obj\n success = 0\n # Increase count\n for item in feature_list_applicants:\n # print(item[\"name\"], item[\"count\"], sep=' ')\n if obj == item[\"name\"]:\n item[\"count\"] = item[\"count\"] + 1\n # print(\"I found of name! --->>> \" + str(item[\"count\"]))\n file_name = 'applicants'\n my_general.write_data_json(feature_list_applicants, curr_path, file_name)\n success = 1\n\n if item[\"count\"] >= border:\n rng = my_general.np.random.default_rng()\n file_name = 'params'\n list_params = my_general.read_data_json(curr_path, file_name)\n\n list_params.append({\"name\": item[\"name\"],\n \"synonyms\": [\"\"],\n \"impact\": (rng.random() - 0.5)\n })\n file_name = 'params'\n my_general.write_data_json(list_params, curr_path, file_name)\n feature_list_applicants.remove(item)\n\n file_name = 'applicants'\n my_general.write_data_json(feature_list_applicants, curr_path, file_name)\n\n break\n # Add new feature\n if success == 0:\n new_feature_applicant = {\"name\": obj, \"count\": 1}\n feature_list_applicants.append(new_feature_applicant)\n file_name = 'applicants'\n my_general.write_data_json(feature_list_applicants, curr_path, file_name)\n # print(obj)\n\n idx_word = idx_word + 1\n idx_word = 0\n idx_sentence = idx_sentence + 1\n\n\n # feature_list_applicants.append()\n\n # ______________________________ NN ______________________________\n\n # logging.basicConfig(level=logging.DEBUG)\n\n # curr_day = datetime.date(2020, 1, 1)\n curr_day = my_general.datetime.date(my_general.datetime.datetime.now().year,\n my_general.datetime.datetime.now().month,\n my_general.datetime.datetime.now().day)\n # print(curr_day)\n exporter = my_general.Exporter()\n data = exporter.lookup(name=curr_ticker, market=my_general.Market.ETF_MOEX)\n # print(data.head())\n stock = exporter.download(data.index[0], market=my_general.Market.ETF_MOEX, start_date=curr_day)\n # print(stock.head())\n\n file_name = curr_path + 'stocks_' + str(curr_ticker) + '.csv'\n stock.to_csv(file_name)\n\n time_value = stock.get('